Search completed in 1.20 seconds.
4880 results for "min":
Your results are loading. Please wait...
PerformanceNavigationTiming.domInteractive - Web APIs
the dominteractive read-only property returns a timestamp representing the time value equal to the time immediately before the user agent sets the current document readiness of the current document to interactive. syntax perfentry.dominteractive; return value a timestamp representing the time value equal to the time immediately before the user agent sets the current document readiness of the current document to interactive. example the following example illustrates this property's usage. ...
... the user agent sets the current document readiness of the current document to interactive. syntax perfentry.dominteractive; return value a timestamp representing the time value equal to the time immediately before the user agent sets the current document readiness of the current document to interactive. example the following example illustrates this property's usage. ...
...ntries = performance.getentriesbytype("navigation"); for (var i=0; i < perfentries.length; i++) { console.log("= navigation entry[" + i + "]"); var p = perfentries[i]; // dom properties console.log("dom content loaded = " + (p.domcontentloadedeventend - p.domcontentloadedeventstart)); console.log("dom complete = " + p.domcomplete); console.log("dom interactive = " + p.dominteractive); // document load and unload time console.log("document load = " + (p.loadeventend - p.loadeventstart)); console.log("document unload = " + (p.unloadeventend - p.unloadeventstart)); // other properties console.log("type = " + p.type); console.log("redirectcount = " + p.redirectcount); } } specifications specification status comment ...
...And 2 more matches
PerformanceTiming.domInteractive - Web APIs
this property can be used to measure the speed of loading web sites that users feels. nevertheless there are a few caveats that happens if scripts are blocking rendering and not loaded asynchronously or with custom web fonts. ...
... thrown. this property can be used to measure the speed of loading web sites that users feels. nevertheless there are a few caveats that happens if scripts are blocking rendering and not loaded asynchronously or with custom web fonts. 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. syntax time = performancetiming.dominteractive; specifications specification status comment navigation timingthe definition of 'performancetiming.dominteractive' in that specification. recommendation initial definition. ...
PerformanceResourceTiming.serverTiming - Web APIs
the servertiming read-only property returns an array of performanceservertiming entries containing server timing metrics. syntax resource.servertiming; specifications specification status comment server timingthe definition of 'servertiming' in that specification. working draft initial definition. ...
Web Accessibility: Understanding Colors and Luminance - Accessibility
overview colors, and how they are used, are a major component of accessibility. at the surface, the subject seems simple, but it is actually a complex subject because color is as much about the physiology of the eye and human perception as it is about light emitting from a computer screen. environment matters. perception of color in a well-lit room will be different than perception of that same color on that same computer screen in a dark room. ...
...the health of his eyes, and more all affect how that color is received by the viewer. how the viewer perceives color after it gets to his eyes is yet another matter, and can be affected by overall health. luckily, css media queries level 5 will be a game-changer in accessibility initiatives, because it will allow users to select settings that accomodate their needs best. ...
...ives color after it gets to his eyes is yet another matter, and can be affected by overall health. luckily, css media queries level 5 will be a game-changer in accessibility initiatives, because it will allow users to select settings that accomodate their needs best. color, contrast, and luminance are among the most central and critical concepts to creating accessible web content with color. luminance is of particular importance, however, because at the end of the day, understanding of what it is and how it is employed enables accessibility for those who are color-blind, as well as those who can perceive color. it is the luminance contrast that enable the color-blind to distinguish dark against light. luminance must be established before the contrast may be. when speaking of color contr...
...And 40 more matches
Navigation and resource timings - Web Performance
navigation timings are metrics measuring a browser's document navigation events. resource timings are detailed network timing measurements regarding the loading of an application's resources. both provide the same read-only properties, but navigation timing measures the main document's timings whereas the resource timing provides the times for all the assets or resources called in by that main document and the resources' requested resources. the general performance timings below have been deprecated in favor of the performance entry api, which provides for marking and measuring times along the navigation and resource loading process. while deprecated, they are supported in all browsers. ...
...rce timing provides the times for all the assets or resources called in by that main document and the resources' requested resources. the general performance timings below have been deprecated in favor of the performance entry api, which provides for marking and measuring times along the navigation and resource loading process. while deprecated, they are supported in all browsers. performance timings the performancetiming api, a javascript api for measuring the loading performance of the requested page, is deprecated but supported in all browsers. it has been replaced with the performancenavigationtiming api. the performance timing api provided read only times, in milliseconds(ms), describing at what time each point in the page loading process was reached. as displayed in the image below,...
...es, in milliseconds(ms), describing at what time each point in the page loading process was reached. ...
...And 28 more matches
animation-timing-function - CSS: Cascading Style Sheets
the animation-timing-function css property sets how an animation progresses through the duration of each cycle. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. it is often convenient to use the shorthand property animation to set all animation properties at once. ...
...e duration of each cycle. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. it is often convenient to use the shorthand property animation to set all animation properties at once. ...
...source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. it is often convenient to use the shorthand property animation to set all animation properties at once. ...
...And 24 more matches
minmax() - CSS: Cascading Style Sheets
Web › CSS › minmax
the minmax() css function defines a size range greater than or equal to min and less than or equal to max. it is used with css grids. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...tion defines a size range greater than or equal to min and less than or equal to max. it is used with css grids. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
... range greater than or equal to min and less than or equal to max. it is used with css grids. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...And 23 more matches
transition-timing-function - CSS: Cascading Style Sheets
the transition-timing-function css property sets how intermediate values are calculated for css properties being affected by a transition effect. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. this, in essence, lets you establish an acceleration curve so that the speed of the transition can vary over its duration. this acceleration curve is defined using one <timing-function> for each property to be transitioned. you may specify multiple timing functions; each one will be applied to the corresponding property as specified by the transition-property property, which acts as a transition-property list. if there are...
...an acceleration curve so that the speed of the transition can vary over its duration. this acceleration curve is defined using one <timing-function> for each property to be transitioned. you may specify multiple timing functions; each one will be applied to the corresponding property as specified by the transition-property property, which acts as a transition-property list. if there are fewer timing functions specified than in the transition-property list, the user agent must calculate which value is used by repeating the list of values until there is one for each transition property. ...
...timing functions; each one will be applied to the corresponding property as specified by the transition-property property, which acts as a transition-property list. if there are fewer timing functions specified than in the transition-property list, the user agent must calculate which value is used by repeating the list of values until there is one for each transition property. if there are more timing functions, the list is simply truncated to the right size. in both cases, the css declaration stays valid. ...
...And 23 more matches
Live streaming web audio and video - Developer guides
live streaming technology is often employed to relay live events such as sports, concerts and more generally tv and radio programmes that are output live. often shortened to just streaming, live streaming is the process of transmitting media 'live' to computers and devices. this is a fairly complex and nascent subject with a lot of variables, so in this article, we'll introduce you to the subject and let you know how you can get started. the key consideration when streaming media to a browser is the fact that rather than playing a finite file we are relaying a file that is being created on the fly and has no pre-determined start or end. key differences between streamed and static media in this case, we are using static media to describe media that is represented by a file, wheth...
...vered — like most other files — to the browser. this is often known as a progressive download. live streamed media lacks a finite start and end time as rather than a static file, it is a stream of data that the server passes on down the line to the browser and is often adaptive (see below). usually, we require different formats and special server-side software to achieve this. adaptive streaming one of the main priorities for live streaming is to keep the player synchronized with the stream: adaptive streaming is a technique for doing this in the case of low bandwidth. the idea is that the data transfer rate is monitored and if it looks like it's not keeping up, we drop down to a lower bandwidth (and consequently lower quality) stream. in order to have this capability, we need to use f...
...streaming is to keep the player synchronized with the stream: adaptive streaming is a technique for doing this in the case of low bandwidth. the idea is that the data transfer rate is monitored and if it looks like it's not keeping up, we drop down to a lower bandwidth (and consequently lower quality) stream. in order to have this capability, we need to use formats that facilitate this. live streaming formats generally allow adaptive streaming by breaking streams into a series of small segments and making those segments available at different qualities and bit rates. streaming audio and video on demand streaming technology is not used exclusively for live streams. it can also be used instead of the traditional progressive download method for audio and video on demand: there are several adv...
...And 22 more matches
PerformanceTiming - Web APIs
these properties each describe the time at which a particular point in the page loading process was reached. ...
... these properties each describe the time at which a particular point in the page loading process was reached. ...
... these properties each describe the time at which a particular point in the page loading process was reached. ...
...And 20 more matches
Setting up adaptive streaming media sources - Developer guides
we are required to provide several different quality files split up over several time points. ...
...we are required to provide several different quality files split up over several time points. ...
...we are required to provide several different quality files split up over several time points. ...
...And 19 more matches
dominant-baseline - SVG: Scalable Vector Graphics
others only re-establish the baseline-table font-size. when the initial value, auto, would give an undesired result, this property can be used to explicitly set the desired scaled-baseline-table. ...
...others only re-establish the baseline-table font-size. when the initial value, auto, would give an undesired result, this property can be used to explicitly set the desired scaled-baseline-table. ...
...others only re-establish the baseline-table font-size. when the initial value, auto, would give an undesired result, this property can be used to explicitly set the desired scaled-baseline-table. ...
...And 18 more matches
min-width - CSS: Cascading Style Sheets
Web › CSS › min-width
the min-width css property sets the minimum width of an element. it prevents the used value of the width property from becoming smaller than the value specified for min-width. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. the element's width is set to the value of min-width whenever min-width is larger than max-width or width. ...
...the value specified for min-width. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. the element's width is set to the value of min-width whenever min-width is larger than max-width or width. syntax /* <length> value */ min-width: 3.5em; /* <percentage> value */ min-width: 10%; /* keyword values */ min-width: max-content; min-width: min-content; min-width: fit-content(20em); /* global values */ min-width: inherit; min-width: initial; min-width: unset; values <length> defines the min-width as an absolute value. <percentage> defines the min-width as a percentage of the containing block's width. auto the b...
...ue */ min-width: 10%; /* keyword values */ min-width: max-content; min-width: min-content; min-width: fit-content(20em); /* global values */ min-width: inherit; min-width: initial; min-width: unset; values <length> defines the min-width as an absolute value. <percentage> defines the min-width as a percentage of the containing block's width. auto the browser will calculate and select a min-width for the specified element. none no limit on the size of the box. max-content the intrinsic preferred min-width. min-content the intrinsic minimum min-width. fit-content(<length-percentage>) uses the fit-content formula with the available space replaced by the specified argument, i.e. min(max-content, max(min-content, argument)). formal definition initial valueautoapplies toall el...
...And 17 more matches
Using the Resource Timing API - Web APIs
the resource timing api provides a way to retrieve and analyze detailed network timing data regarding the loading of an application's resource(s). an application can use the timing metrics to determine, for example, the length of time it takes to fetch a specific resource such as an xmlhttprequest, <svg>, image, script, etc.). the interface's properties create a resource loading timeline with high-resolution timestamps for network events such as redirect start and end times, fetch start, dns lookup start and end times, response start and end times, etc. the interface also includes other properties that provide data about the size of the fetched resource as well as the type of resource that initiated the fetch. this document shows the use of resource timing interfaces. for more details abou...
... in the see also section. a live version of the examples is available on github, as is the source code. pull requests and bug reports are welcome. resource loading phases an application can get timestamps for the various phases of resource loading such as redirection, dns lookup, and tcp connection setup. those phases and their property names are illustrated in figure 1. figure 1. ...
...pplication can get timestamps for the various phases of resource loading such as redirection, dns lookup, and tcp connection setup. those phases and their property names are illustrated in figure 1. figure 1. resource timing properties an application developer can use the property values to calculate the length of time a phase takes and that information can help diagnose performance issues. 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). this example also calculates the time from the start o...
...And 16 more matches
PerformanceResourceTiming - Web APIs
the interface's properties create a resource loading timeline with high-resolution timestamps for network events such as redirect start and end times, fetch start, dns lookup start and end times, response start and end times, etc.. additionally, the interface extends performanceentry with other properties which provide data about the size of the fetched resource as well as the type of resource that initiated the fetch. ...
...vide data about the size of the fetched resource as well as the type of resource that initiated the fetch. ...
... data about the size of the fetched resource as well as the type of resource that initiated the fetch. ...
...And 15 more matches
PerformanceNavigationTiming - Web APIs
the performancenavigationtiming interface provides methods and properties to store and retrieve metrics regarding the browser's document navigation events. for example, this interface can be used to determine how much time it takes to load or unload a document. ...
... for example, this interface can be used to determine how much time it takes to load or unload a document. ...
... example, this interface can be used to determine how much time it takes to load or unload a document. ...
...And 14 more matches
min-block-size - CSS: Cascading Style Sheets
the min-block-size css property defines the minimum horizontal or vertical size of an element's block, depending on its writing mode. it corresponds to either the min-width or the min-height property, depending on the value of writing-mode. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...ck, depending on its writing mode. it corresponds to either the min-width or the min-height property, depending on the value of writing-mode. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...iting mode. it corresponds to either the min-width or the min-height property, depending on the value of writing-mode. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...And 10 more matches
min-inline-size - CSS: Cascading Style Sheets
the min-inline-size css property defines the horizontal or vertical minimal size of an element's block, depending on its writing mode. it corresponds to either the min-width or the min-height property, depending on the value of writing-mode. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...ck, depending on its writing mode. it corresponds to either the min-width or the min-height property, depending on the value of writing-mode. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...ting mode. it corresponds to either the min-width or the min-height property, depending on the value of writing-mode. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...And 10 more matches
Resource Timing API - Web APIs
the resource timing interfaces enable retrieving and analyzing detailed network timing data regarding the loading of an application's resource(s). an application can use the timing metrics to determine, for example, the length of time it takes to load a specific resource, such as an xmlhttprequest, <svg>, image, or script. the interface's properties create a resource loading timeline with high-resolution timestamps for network events such as redirect start and end times, dns lookup start and end times, request start, response start and end times, etc. the interface also includes other properties that provide data about the size of the fetched resource as well as the type of resource that initiated the fetch. this document provides an overview of the resource timing interfaces. for more det...
...es, request start, response start and end times, etc. the interface also includes other properties that provide data about the size of the fetched resource as well as the type of resource that initiated the fetch. this document provides an overview of the resource timing interfaces. 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. for a graphical representation of the resource timing processing model see the resource timing phases figure. the performanceresourcetiming interface extends the performanceentry for performance entries which have an entrytype of "resource". high-resolution timestamps several of the resource timing properties return high-resolution timestamps. ...
...r the browser receives the last byte of the resource. if the resource is loaded via a secure connection a secureconnectionstart timestamp will be available between the connection start and end events. when cors is in effect, many of these values are returned as zero unless the server's access policy permits these values to be shared. this requires the server providing the resource to send the timing-allow-origin http response header with a value specifying the origin or origins which are allowed to get the restricted timestamp values. the properties which are returned as 0 by default when loading a resource from a domain other than the one of the web page itself: redirectstart, redirectend, domainlookupstart, domainlookupend, connectstart, connectend, secureconnectionstart, requeststart, a...
...And 9 more matches
HTML attribute: min - HTML: Hypertext Markup Language
Web › HTML › Attributes › min
the min attribute defines the minimum value that is acceptable and valid for the input containing the attribute. if the value of the element is less than this, the element fails constraint validation. this value must be less than or equal to the value of the max attribute. if a value is specified for min that isn't a valid number, the input has no minimum value. valid for the numeric input types, including the date, month, week, time, datetime-local, number and range types, and the <meter> element, the min attribute is a number that specifies the most negative value a form control to be considered valid. ...
...lid for the numeric input types, including the date, month, week, time, datetime-local, number and range types, and the <meter> element, the min attribute is a number that specifies the most negative value a form control to be considered valid. syntax if any is not explicity set, valid values for the number, date/time input types, and range input types are equal to the basis for stepping - the min value and increments of the step value, up to the max value, if specified. for example, if we have <input type="number" min="10" step="2"> any even integer, 10 or great, is valid. ...
...for stepping - the min value and increments of the step value, up to the max value, if specified. for example, if we have <input type="number" min="10" step="2"> any even integer, 10 or great, is valid. if omitted, <input type="number">, any integer is valid, but floats, like 4.2, are not valid, as step defaults to 1. ...
...And 9 more matches
Dominators - Firefox Developer Tools
with a garbage-collected language, like javascript, the programmer doesn't generally have to worry about deallocating memory. ...
... with a garbage-collected language, like javascript, the programmer doesn't generally have to worry about deallocating memory. ...
... with a garbage-collected language, like javascript, the programmer doesn't generally have to worry about deallocating memory. they can just create and use objects, and when the objects are no longer needed, the runtime takes care of cleaning up, and frees the memory the objects occupied. ...
...And 8 more matches
General asynchronous programming concepts - Learn web development
asynchronous? normally, a given program's code runs straight along, with only one thing happening at once. ...
... asynchronous? normally, a given program's code runs straight along, with only one thing happening at once. ...
...ing experience and isn't a good use of computer processing power — especially in an era in which computers have multiple processor cores available. there's no sense sitting there waiting for something when you could let the other task chug along on another processor core and let you know when it's done. this lets you get other work done in the meantime, which is the basis of asynchronous programming. it is up to the programming environment you are using (web browsers, in the case of web development) to provide you with apis that allow you to run such tasks asynchronously. blocking code asynchronous techniques are very useful, particularly in web programming. when a web app runs in a browser and it executes an intensive chunk of code without returning control to the browser, the browser ca...
...And 7 more matches
Dominators view - Firefox Developer Tools
the dominators view is new in firefox 46. starting in firefox 46, the memory tool includes a new view called the dominators view. this is useful for understanding the "retained size" of objects allocated by your site: that is, the size of the objects themselves plus the size of the objects that they keep alive through references. if you already know what shallow size, retained size, and dominators are, skip to the dominators ui section. otherwise, you might want to review the article on dominators concepts. dominators ui to see the dominators view for a snapshot, select "dominators" in the "view" drop-down list. ...
...plus the size of the objects that they keep alive through references. if you already know what shallow size, retained size, and dominators are, skip to the dominators ui section. otherwise, you might want to review the article on dominators concepts. dominators ui to see the dominators view for a snapshot, select "dominators" in the "view" drop-down list. it looks something like this: the dominators view consists of two panels: the dominators tree panel shows you which nodes in the snapshot are retaining the most memory the retaining paths panel (new in firefox 47) shows the 5 shortest retaining paths for a single node. dominators tree panel the dominators tree tells you which objects in the snapshot are retaining the most memory. in the main part of the ui, the first row is l...
...tely underneath that is an entry for: every gc root node. in gecko, there is more than one memory graph, and therefore more than one root. there may be many (often temporary) roots. for example: variables allocated on the stack need to be rooted, or internal caches may need to root their​ elements. any other node that's referenced from two different roots (since in this case, neither root dominates it). each entry displays: the retained size of the node, as bytes and as a percentage of the total the shallow size of the node, as bytes and as a percentage of the total the nodes's name and address in memory. entries are ordered by the amount of memory that they retain. for example: in this screenshot we can see five entries under "gc roots". the first two are call and window ob...
...And 7 more matches
EffectTiming.delay - Web APIs
defaults to 0. ...
...defaults to 0. ...
...defaults to 0. ...
...And 7 more matches
Navigation Timing API - Web APIs
the navigation timing api provides data that can be used to measure the performance of a web site. unlike javascript-based libraries that have historically been used to collect similar information, the navigation timing api can be much more accurate and reliable. this article currently describes navigation timing level 1. there is a specification for level 2, but it is not yet covered here. 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. this api lets you measure data that was previously difficult to obtain, such as the amount of time needed to unload the previous page, how long domain lookups take, the total time spent executing the window's load ha...
...lets you measure data that was previously difficult to obtain, such as the amount of time needed to unload the previous page, how long domain lookups take, the total time spent executing the window's load handler, and so forth. interfaces performance the window.performance property returns a performance object. ...
...reviously difficult to obtain, such as the amount of time needed to unload the previous page, how long domain lookups take, the total time spent executing the window's load handler, and so forth. interfaces performance the window.performance property returns a performance object. ...
...And 7 more matches
min-height - CSS: Cascading Style Sheets
<length> a non-negative absolute or relative length. <percentage> a percentage value relative to the height of the initial viewport at zoom factor 1.0 for vertical lengths. must be non-negative. ...
... <length> a non-negative absolute or relative length. <percentage> a percentage value relative to the height of the initial viewport at zoom factor 1.0 for vertical lengths. must be non-negative. ...
... <length> a non-negative absolute or relative length. <percentage> a percentage value relative to the height of the initial viewport at zoom factor 1.0 for vertical lengths. must be non-negative. ...
...And 7 more matches
Timing element visibility with the Intersection Observer API - Web APIs
pi makes it easy to be asynchronously notified when elements of interest become more or less obscured by a shared ancestor node or element, including the document itself. in this article, we'll build a mock blog which has a number of ads interspersed among the contents of the page, then use the intersection observer api to track how much time each ad is visible to the user. when an ad exceeds one minute of visible time, it will be replaced with a new one. although many aspects of this example will not match real world usage (in particular, the articles all have the same text and aren't loaded from a database, and there are just a handful of simple text-only ads that are selected from an array), this should provide enough understanding of the api to quickly learn how to apply the intersection...
.... let's look at the style for each component of the page individually. the basics we provide styles for the <body> and <main> elements to define the site's background as well as the grid the various parts of the site will be placed in. body { font-family: "open sans", "arial", "helvetica", sans-serif; background-color: aliceblue; } .wrapper { display: grid; grid-template-columns: auto minmax(min-content, 1fr); grid-template-rows: auto minmax(min-content, 1fr); max-width: 700px; margin: 0 auto; background-color: aliceblue; } the site's <body> is configured here to use one of a number of common sans-serif fonts, and to use "aliceblue" as the background color. then the "wrapper" class is defined; it wraps the entire blog, including the header, sidebar, and body content (arti...
...e in entry.time, then add the ad to the set visibleads so we know to process it as time goes by. if the ad has transitioned to the not-intersecting state, we remove the ad from the set of visible ads. then we have one special behavior: we look to see if entry.ratio is 0.0; if it is, that means the element has become totally obscured. if that's the case, and the ad has been visible for at least a minute total, we call a function we'll create called replacead() to replace the existing ad with a new one. this way, the user sees a variety of ads over time, but the ads are only replaced while they can't be seen, resulting in a smooth experience. handling periodic actions our interval handler, handlerefreshinterval(), is called about once per second courtesy of the call to setinterval() made in ...
...And 6 more matches
Using the aria-valuemin attribute - Accessibility
note: opinions may differ on how assistive technology should handle this technique. ...
... note: opinions may differ on how assistive technology should handle this technique. ...
... note: opinions may differ on how assistive technology should handle this technique. ...
...And 6 more matches
min-width - CSS: Cascading Style Sheets
<length> a non-negative absolute or relative length. <percentage> a percentage value relative to the width or height of the initial viewport at zoom factor 1.0, for horizontal and vertical lengths respectively. must be non-negative. ...
... <length> a non-negative absolute or relative length. <percentage> a percentage value relative to the width or height of the initial viewport at zoom factor 1.0, for horizontal and vertical lengths respectively. must be non-negative. ...
... <length> a non-negative absolute or relative length. <percentage> a percentage value relative to the width or height of the initial viewport at zoom factor 1.0, for horizontal and vertical lengths respectively. must be non-negative. ...
...And 6 more matches
min() - CSS: Cascading Style Sheets
Web › CSS › min
the min() css function lets you set the smallest (most negative) value from a list of comma-separated expressions as the value of a css property value. the min() function can be used anywhere a <length>, <frequency>, <angle>, <time>, <percentage>, <number>, or <integer> is allowed. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. in the first above example, the width will be at most 200px, but will be smaller if the viewport is less than 400px wide (in which case 1vw would be 4px, so 50vw would be 200px). in other words, the maximum width is 200px. ...
... repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. in the first above example, the width will be at most 200px, but will be smaller if the viewport is less than 400px wide (in which case 1vw would be 4px, so 50vw would be 200px). in other words, the maximum width is 200px. think of the min() value as providing the maximum value a property can have. syntax the min() function takes one or more comma-separated expressions as its parameter, with the smallest (most negative) expression value result used as the value. 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 ...
...r each value in your expression, if you wish. you may also use parentheses to establish computation order when needed. notes math expressions involving percentages for widths and heights on table columns, table column groups, table rows, table row groups, and table cells in both auto and fixed layout tables may be treated as if auto had been specified. it is permitted to nest max() and other min() functions as expression values. 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. make sure to put a space on each si...
...And 6 more matches
performance.clearResourceTimings() - Web APIs
the clearresourcetimings() method removes all performance entries with an entrytype of "resource" from the browser's performance data buffer and sets the size of the performance data buffer to zero. to set the size of the browser's performance data buffer, use the performance.setresourcetimingbuffersize() method. note: this feature is available in web workers. syntax performance.clearresourcetimings(); arguments void return value none this method has no return value. ...
...he performance.setresourcetimingbuffersize() method. note: this feature is available in web workers. syntax performance.clearresourcetimings(); arguments void return value none this method has no return value. ...
...ings(); arguments void return value none this method has no return value. ...
...And 5 more matches
:indeterminate - CSS: Cascading Style Sheets
the :indeterminate css pseudo-class represents any form element whose state is indeterminate, such as checkboxes which have their html indeterminate attribute set to true, radio buttons which are members of a group in which all radio buttons are unchecked, and indeterminate <progress> elements. ...
... the :indeterminate css pseudo-class represents any form element whose state is indeterminate, such as checkboxes which have their html indeterminate attribute set to true, radio buttons which are members of a group in which all radio buttons are unchecked, and indeterminate <progress> elements. ...
... the :indeterminate css pseudo-class represents any form element whose state is indeterminate, such as checkboxes which have their html indeterminate attribute set to true, radio buttons which are members of a group in which all radio buttons are unchecked, and indeterminate <progress> elements. ...
...And 5 more matches
Date.prototype.setMinutes() - JavaScript
msvalue optional. a number between 0 and 999, representing the milliseconds. ...
... msvalue optional. a number between 0 and 999, representing the milliseconds. ...
... msvalue optional. a number between 0 and 999, representing the milliseconds. ...
...And 5 more matches
WebAssembly.compileStreaming() - JavaScript
return value a promise that resolves to a webassembly.module object representing the compiled module. exceptions if buffersource is not a typed array, a typeerror is thrown. ...
... return value a promise that resolves to a webassembly.module object representing the compiled module. exceptions if buffersource is not a typed array, a typeerror is thrown. ...
... return value a promise that resolves to a webassembly.module object representing the compiled module. exceptions if buffersource is not a typed array, a typeerror is thrown. ...
...And 5 more matches
Graceful asynchronous programming with Promises - Learn web development
(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. it then calls getusermedia(), asking for a stream that has both video and audio tracks, then once that's been obtained, sets up a video element to show the stream coming from the camera as a "self view," then takes each of the stream's tracks and adds them to the webrtc rtcpeerconnection representing a connection to another user. after that, the status display is updated to say "connected". if getusermedia() fails, the catch block runs. this uses setstatusmessage() to update the status box to indicate that an error occurred. the important thing here is that th...
...e the status box to indicate that an error occurred. the important thing here is that the getusermedia() call returns almost immediately, even if the camera stream hasn't been obtained yet. even if the handlecallbutton() function has already returned to the code that called it, when getusermedia() has finished working, it calls the handler you provide. as long as the app doesn't assume that streaming has begun, it can just keep on running. note: you can learn more about this somewhat advanced topic, if you're interested, in the article signaling and video calling. code similar to this, but much more complete, is used in that example. the trouble with callbacks to fully understand why promises are a good thing, it helps to think back to old-style callbacks and to appreciate why they are ...
...ey are problematic. let's talk about ordering pizza as an analogy. there are certain steps that you have to take for your order to be successful, which doesn't really make sense to try to execute out of order, or in order but before each previous step has quite finished: you choose what toppings you want. this can take a while if you are indecisive, and may fail if you just can't make up your mind, or decide to get a curry instead. you then place your order. this can take a while to return a pizza and may fail if the restaurant does not have the required ingredients to cook it. you then collect your pizza and eat. this might fail if, say, you forgot your wallet so can't pay for the pizza! with old-style callbacks, a pseudo-code representation of the above functionality might look some...
...And 4 more matches
Server-side website programming first steps - Learn web development
however, you do need to understand how the web works. ...
... however, you do need to understand how the web works. ...
...and "why is it so useful?". we then provide an overview of some of the most popular server-side web frameworks, along with guidance on how to select the most suitable framework for creating your first site. finally, we provide a high-level introductory article about web server security. prerequisites before starting this module, you don't need to have any knowledge of server-side website programming, or indeed any other type of programming. however, you do need to understand how the web works. we recommend that you first read the following topics: what is a web server? what software do i need to build a website? how do you upload files to a web server? with that basic understanding, you'll be ready to work your way through the modules in this section. guides introduction to th...
...And 4 more matches
NSPR's Position On Abrupt Thread Termination
this memo describes my position on a facility that is currently under discussion for inclusion in the netscape portable runtime (nspr); the ability of a thread to abruptly exit. i resist including this function in nspr because it results in bad programming practice and unsupportable programs. threads are not processes. abrupt termination has been available in the unix/c environment for some time (exit()), and i assume that the basic semantics defined there are applicable here. in that environment, exit() may be called and any time, and results in the calling thread's immediate termination. in the situation where it was defined (unix), which has only a single thread of execution, that is equivalent to terminating the process. the process abstraction is then responsible for closing a...
...this practice does not extend to threads. threads run within the confines of a process (or similar abstractions in other environments). ...
... they do not maintain the full protection domain provided by a process. so in a threaded environment, what is the parallel to unix' exit()? nspr has defined a function, callable by any thread within a process at any time, called pr_processexit(). this is identical to unix exit() and was so named in an effort to make the obvious even more so. when called, the process exits, closing files and reclaiming the process' storage. certain people have been disappointed when nspr did not provide a functional equivalent to exit just a particular thread. apparently they have failed to consider the ramifications. if a thread was to abruptly terminate, there is no recording of what resources it owns and should therefore be reclaimed. those resources are in fact, owned by the process and shared by all the t...
...And 4 more matches
EffectTiming.fill - Web APIs
Web › API › EffectTiming › fill
for example, setting fill to "none" means the animation's effects are not applied to the element if the current time is outside the range of times during which the animation is running, while "forwards" ensures that once the animation's end time has been passed, the element will continue to be drawn in the state it was in at its last rendered frame. ...
...imation's end time has been passed, the element will continue to be drawn in the state it was in at its last rendered frame. note that authors are discouraged from using fill modes to persist the effect of an animation indefinitely. see the alternatives to fill modes section below for approaches that are simpler and more performant. ...
...was in at its last rendered frame. note that authors are discouraged from using fill modes to persist the effect of an animation indefinitely. see the alternatives to fill modes section below for approaches that are simpler and more performant. element.animate(), and keyframeeffect() accept an object of timing properties including fill. the value of fill corresponds directly to fill in effecttiming objects returned by gettiming() in animationeffect and keyframeeffect. syntax var timingproperties = { fill: "none" | "forwards" | "backwards" | "both" | "auto" } value a domstring indicating the fill type to use in order to properly render an affected element when outside the animation's active interval (that is, when it's not actively animating). the default is "auto". "none" the a...
...And 4 more matches
PerformanceServerTiming - Web APIs
note: this feature is available in web workers. the performanceservertiming interface surfaces server metrics that are sent with the response in the server-timing http header. this interface is restricted to the same origin, but you can use the timing-allow-origin header to specify the domains that are allowed to access the server metrics. note that this interface is only available in secure contexts (https) in some browsers. properties performanceservertiming.descriptionread only a domstring value of the server-specified metric description, or an empty string. performanceservertiming.durationread only a double that contains the server-specified metric duration, or value 0.0. performanceservertiming.nameread only a domstring value of the server-specified metric name. ...
...owsers. properties performanceservertiming.descriptionread only a domstring value of the server-specified metric description, or an empty string. performanceservertiming.durationread only a double that contains the server-specified metric duration, or value 0.0. performanceservertiming.nameread only a domstring value of the server-specified metric name. methods performanceservertiming.tojson() returns a domstring that is the json representation of the performanceservertiming object. ...
...formanceservertiming.durationread only a double that contains the server-specified metric duration, or value 0.0. performanceservertiming.nameread only a domstring value of the server-specified metric name. methods performanceservertiming.tojson() returns a domstring that is the json representation of the performanceservertiming object. ...
...And 4 more matches
RTCIceCandidatePairStats.availableIncomingBitrate - Web APIs
the value is reported in bits per second and is computed over a 1-second interval. ...
...the value is reported in bits per second and is computed over a 1-second interval. ...
...the value is reported in bits per second and is computed over a 1-second interval. ...
...And 4 more matches
WebAssembly.instantiateStreaming() - JavaScript
importobject optional an object containing the values to be imported into the newly-created instance, such as functions or webassembly.memory objects. there must be one matching property for each declared import of the compiled module or else a webassembly.linkerror is thrown. ...
...tance: a webassembly.instance object that contains all the exported webassembly functions. exceptions if either of the parameters are not of the correct type or structure, a typeerror is thrown. if the operation fails, the promise rejects with a webassembly.compileerror, webassembly.linkerror, or webassembly.runtimeerror, depending on the cause of the failure. ...
... the exported webassembly functions. exceptions if either of the parameters are not of the correct type or structure, a typeerror is thrown. if the operation fails, the promise rejects with a webassembly.compileerror, webassembly.linkerror, or webassembly.runtimeerror, depending on the cause of the failure. ...
...And 4 more matches
Capturing a minidump
minidumps are files created by various windows tools which record the complete state of a program as it's running, or as it was at the moment of a crash. small minidumps are created by the breakpad crash reporting tool, but sometimes that's not sufficient to diagnose a problem. for example, if the application is hanging (not responding to input, but hasn't crashed) then breakpad is not triggered, and it can be difficult to determine where the problem lies. sometimes a more complete form of minidump is needed to see additional details about a crash, in which case manual capture of a minidump is desired. this page describes how to capture these minidumps on windows, to permit better debugging. ...
...anging (not responding to input, but hasn't crashed) then breakpad is not triggered, and it can be difficult to determine where the problem lies. sometimes a more complete form of minidump is needed to see additional details about a crash, in which case manual capture of a minidump is desired. this page describes how to capture these minidumps on windows, to permit better debugging. privacy and minidumps warning! ...
..., but hasn't crashed) then breakpad is not triggered, and it can be difficult to determine where the problem lies. sometimes a more complete form of minidump is needed to see additional details about a crash, in which case manual capture of a minidump is desired. this page describes how to capture these minidumps on windows, to permit better debugging. privacy and minidumps warning! ...
...And 3 more matches
nsIMsgIncomingServer
nsimsgincomingserver mailnews/base/public/nsimsgincomingserver.idlscriptable ??? add brief description of interface ??? ...
...rbird 3.0 / seamonkey 2.0) method overview void clearallvalues(); void cleartemporaryreturnreceiptsfilter(); void closecachedconnections(); void configuretemporaryfilters(in nsimsgfilterlist filterlist); void configuretemporaryreturnreceiptsfilter(in nsimsgfilterlist filterlist); obsolete since gecko 1.8 void displayofflinemsg(in nsimsgwindow awindow); boolean equals(in nsimsgincomingserver server); void forgetpassword(); void forgetsessionpassword(); astring generateprettynameformigration(); boolean getboolattribute(in string name); boolean getboolvalue(in string attr); acstring getcharattribute(in string name); acstring getcharvalue(in string attr); nsilocalfile getfilevalue(in string relpref, in string abspref); nsimsgfilterlist getfilterlist(in nsimsgwin...
...g value); void setintvalue(in string attr, in long value); void setunicharattribute(in string name, in astring value); void setunicharvalue(in string attr, in astring value); void shutdown(); void storepassword(); astring tostring(); void writetofoldercache(in nsimsgfoldercache foldercache); attributes attribute type description accountmanagerchrome astring read only. biffminutes long biffstate unsigned long canbedefaultserver boolean read only. cancompactfoldersonserver boolean read only. cancreatefoldersonserver boolean candelete boolean can this server be removed from the account manager? for instance, local mail is not removable, but an imported folder is. canemptytrashonexit boolean read only. canfilemessagesonserver boolean canhavefilters...
...And 3 more matches
PerformanceFrameTiming - Web APIs
a frame represents the amount of work a browser does in one event loop such as processing dom events, resizing, scrolling, rendering, css animations, etc.. a frame rate of 60fps (frames per second) for a 60hz refresh rate is the target for a good responsive user experience. this means the browser should process a frame in about 16.7ms. an application can register a performanceobserver for "frame" performance entry types and the observer can retrieve data about the duration of each frame event. this information can be used to help identify areas that take too long to provide a good user experience. ...
... this information can be used to help identify areas that take too long to provide a good user experience. ...
...s information can be used to help identify areas that take too long to provide a good user experience. ...
...And 3 more matches
PerformanceLongTaskTiming - Web APIs
the performancelongtasktiming interface of the the long tasks api reports instances of long tasks. ...
... the performancelongtasktiming interface of the the long tasks api reports instances of long tasks. ...
... the performancelongtasktiming interface of the the long tasks api reports instances of long tasks. ...
...And 3 more matches
PerformancePaintTiming - Web APIs
the performancepainttiming interface of the paint timing provides timing information about "paint" (also called "render") operations during web page construction. "paint" refers to conversion of the render tree to on-screen pixels. an application can register a performanceobserver for "paint" performance entry types and the observer can retrieve the times that paint events occur. use this information to help identify areas that take too long to provide a good user experience. ...
...s occur. use this information to help identify areas that take too long to provide a good user experience. ...
...cur. use this information to help identify areas that take too long to provide a good user experience. ...
...And 3 more matches
TaskAttributionTiming - Web APIs
the taskattributiontiming interface of the long tasks api returns information about the work involved in a long task and its associate frame context. the frame context, also called the container, is the iframe, embed or object that is being implicated, on the whole, for a long task. ...
...led the container, is the iframe, embed or object that is being implicated, on the whole, for a long task. ...
...the container, is the iframe, embed or object that is being implicated, on the whole, for a long task. ...
...And 3 more matches
DASH Adaptive Streaming for HTML 5 Video - HTML: Hypertext Markup Language
this means that it allows for a video stream to switch between bit rates on the basis of network performance, in order to keep a video playing. browser support firefox 21 includes an implementation of dash for html5 webm video which is turned off by default. it can be enabled via "about:config" and the "media.dash.enabled" preference. firefox 23 removed support for dash for html5 webm video. it will be replaced by an implementation of the media source extensions api which will allow support for dash via javascript libraries such as dash.js. see bug 778617 for details. ...
...ed ith 3.2.5). 1. use your existing webm file to create one audio file and multiple video files. 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. ...
...o 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. ...
...And 3 more matches
Server-Timing - HTTP
the server-timing header communicates one or more metrics and descriptions for a given request-response cycle. it is used to surface any backend server timing metrics (e.g. database read/write, cpu time, file system access, etc.) in the developer tools in the user's browser or in the performanceservertiming interface. header type response header forbidden header name no syntax the syntax of the server-timing header allows you to communicate metrics in different ways: server metric name only, metric with value, metric with value and description, and metric with description. the specification advices that names and descriptions should be kept as short as possible (use abbreviations and omit optional values where possible) to minimize the http overhead. // sin...
...r-timing header allows you to communicate metrics in different ways: server metric name only, metric with value, metric with value and description, and metric with description. the specification advices that names and descriptions should be kept as short as possible (use abbreviations and omit optional values where possible) to minimize the http overhead. ...
...ferent ways: server metric name only, metric with value, metric with value and description, and metric with description. the specification advices that names and descriptions should be kept as short as possible (use abbreviations and omit optional values where possible) to minimize the http overhead. ...
...And 3 more matches
Intl.Locale.prototype.minimize() - JavaScript
description this method carries out the reverse of maximize(), removing any language, script, or region subtags from the locale language identifier (essentially the contents of basename). ...
... description this method carries out the reverse of maximize(), removing any language, script, or region subtags from the locale language identifier (essentially the contents of basename). ...
...against locale.basename. description this method carries out the reverse of maximize(), removing any language, script, or region subtags from the locale language identifier (essentially the contents of basename). this is useful when there are superfluous subtags in the language identifier; for instance, "en-latn" can be simplified to "en", since "latn" is the only script used to write english. ...
...And 3 more matches
Guide to streaming audio and video - Web media technologies
hls may also be supported in other environments, although in some cases this support is conditional. ...
...hls may also be supported in other environments, although in some cases this support is conditional. ...
...hls may also be supported in other environments, although in some cases this support is conditional. ...
...And 3 more matches
ScriptEngineMinorVersion - Archive of obsolete content
non-standard. do not use! ...
... non-standard. do not use! ...
... non-standard. do not use! ...
...And 2 more matches
Making asynchronous programming easier with async and await - Learn web development
ffect of setting off their associated processes all running simultaneously. next, we await their results — because the promises all started processing at essentially the same time, the promises will all fulfill at the same time; when you run the second example, you'll see the alert box reporting a total run time of just over 3 seconds! you'll have to test your code carefully, and bear this in mind if performance starts to suffer. another minor inconvenience is that you have to wrap your awaited promises inside an async function. async/await class methods as a final note before we move on, you can even add async in front of class/object methods to make them return promises, and await promises inside them. take a look at the es class code we saw in our object-oriented javascript article,...
...w person('han', 'solo', 25, 'male', ['smuggling']); the first class method could now be used something like this: han.greeting().then(console.log); browser support one consideration when deciding whether to use async/await is support for older browsers. they are available in modern versions of most browsers, the same as promises; the main support problems come with internet explorer and opera mini. if you want to use async/await but are concerned about older browser support, you could consider using the babeljs library — this allows you to write your applications using the latest javascript and let babel figure out what changes if any are needed for your user’s browsers. on encountering a browser that does not support async/await, babel's polyfill can automatically provide fallbacks ...
...here you have it — async/await provide a nice, simplified way to write async code that is simpler to read and maintain. ...
...And 2 more matches
Server-side website programming - Learn web development
most major websites use some kind of server-side technology to dynamically display data as required. for example, imagine how many products are available on amazon, and imagine how many posts have been written on facebook. ...
... most major websites use some kind of server-side technology to dynamically display data as required. for example, imagine how many products are available on amazon, and imagine how many posts have been written on facebook. ...
...ient, 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. in the modern world of web development, learning about server-side development is highly recommended. ...
...And 2 more matches
EffectTiming.duration - Web APIs
the duration property of the dictionary effecttiming in the web animations api specifies the duration in milliseconds that a single iteration (from beginning to end) the animation should take to complete. element.animate(), keyframeeffectreadonly(), and keyframeeffect() all accept an object of timing properties including duration. the value of duration corresponds directly to animationeffecttimingreadonly.duration in timing objects returned by animationeffectreadonly, keyframeeffectreadonly, and keyframeeffect. syntax var timingproperties = { duration: durationinmilliseconds | "auto" }; timingproperties.duration = durationinmilliseconds | "auto"; value the number of milliseconds long a single beginning-to-end iteration of the animation should take. the default is "auto".
...nce in the future, "auto" will be expanded to take into account the duration of any child effects. consider using "auto" rather than 0 if that makes sense. exceptions typeerror the specified value is either a string other than "auto", a number less than zero, nan, or some other type of object entirely. ...
...uration of any child effects. consider using "auto" rather than 0 if that makes sense. exceptions typeerror the specified value is either a string other than "auto", a number less than zero, nan, or some other type of object entirely. ...
...And 2 more matches
MediaSettingsRange.min - Web APIs
working draft initial definition. ...
... working draft initial definition. ...
... working draft initial definition. ...
...And 2 more matches
User Timing API - Web APIs
the user timing interface allows the developer to create application specific timestamps that are part of the browser's performance timeline. there are two types of user defined timing event types: the "mark" event type and the "measure" event type. mark events are named by the application and can be set at any location in an application. measure events are also named by the application but they are placed between two marks thus they are effectively a midpoint between two marks. this document provides an overview of the mark and measure performance event types including the four user timing methods that extend the performance interface. for more details and example code regarding these two performance event types and the methods, see using the user timing api. performance marks a perform...
...ure will be placed between (in the performance timeline). the measure's performance entry will have the following property values: entrytype - set to "measure". name - set to the "name" given when the measure was created. starttime - set to the timestamp when measure() was called. duration - set to a domhighrestimestamp that is the duration of the measure (typically, the end mark timestamp minus the start mark timestamp). retrieving performance measures the performance interface has three methods that can be used to retrieve a measure: performance.getentries() returns all performance entries in the performance timeline. finding the measure entries requires checking each entry's entrytype for "measure". performance.getentriesbyname(name, entrytype) returns all performance entri...
...moving performance measures to remove a specific measure from the performance timeline, call performance.clearmeasures(name) where name is the name of the measure(s) you want removed. if this method is called with no arguments, all measure type entries will be removed from the performance timeline. ...
...And 2 more matches
min-height - CSS: Cascading Style Sheets
the min-height css property sets the minimum height of an element. it prevents the used value of the height property from becoming smaller than the value specified for min-height. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. the element's height is set to the value of min-height whenever min-height is larger than max-height or height. ...
...lue specified for min-height. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. the element's height is set to the value of min-height whenever min-height is larger than max-height or height. syntax /* <length> value */ min-height: 3.5em; /* <percentage> value */ min-height: 10%; /* keyword values */ min-height: max-content; min-height: min-content; min-height: fit-content(20em); /* global values */ min-height: inherit; min-height: initial; min-height: unset; values <length> defines the min-height as an absolute value. <percentage> defines the min-height as a percentage of the containing block's height. ...
...height: 10%; /* keyword values */ min-height: max-content; min-height: min-content; min-height: fit-content(20em); /* global values */ min-height: inherit; min-height: initial; min-height: unset; values <length> defines the min-height as an absolute value. <percentage> defines the min-height as a percentage of the containing block's height. auto the browser will calculate and select a min-height for the specified element. none no limit on the size of the box. max-content the intrinsic preferred min-height. min-content the intrinsic minimum min-height. fit-content(<length-percentage>) uses the fit-content formula with the available space replaced by the specified argument, i.e. min(max-content, max(min-content, argument)). formal definition initial valueautoapplies toall...
...And 2 more matches
Implementing Download Resuming
the interfaces in question exist in the form they are described here since gecko 1.8a4 (firefox 1.5, seamonkey 1.0, xulrunner 1.8.0.1). introduction various protocols support getting partial files. this means that if a download was interrupted, it can be resumed from that point on, rather than regetting the whole file. the necko implementations of http 1.1 (rfc 2616) as well as ftp support this feature. ...
...port this feature. not only is the ability to specify a start position important, but it's also important to have some assurance that the file did not change since the initial download attempt. that would lead to a situation where the first part of the file corresponds to the initial version, while the latter part belongs to a different version, leading to an unusable result. the interface resuming is done using the nsiresumablechannel interface. the expected way to use it is this: for all downloads that happen, get the entityid from the channel, and store it for later use. the entity id is what ensures that the file remains unchanged. this can also be used to check whether the download is resumable: if it is not (e.g. the server is not using http 1.1), then accessing this attribute wil...
...e: if it is not (e.g. the server is not using http 1.1), then accessing this attribute will throw an ns_error_not_resumable exception. if the download gets interrupted, necko will call the stream listener's onstoprequest method with a failure status. (todo: document what webbrowserpersist/exthandler do). the front-end code can then notify the user of this, and offer to resume the download. resuming a download in order to resume a download, you should create a channel as usual (using nsiioservice). then, you can check if it implements nsiresumablechannel. if it does not, the protocol does not support resuming. otherwise, call resumeat with the desired start position, and the previously stored entity id. (it is possible to pass an empty string as the id; however, this means that you have no...
...annot append to existing files (as opposed to overwriting them), and is therefore not usable for this task (see bug 129921). detecting when a file changed if the file changed (that is, the entity id does not match), then necko will notify the stream listener with an ns_error_entity_changed error code. the front-end may want to offer the user to get the new file from scratch in such a case. resuming not supported in some cases, it's not possible to detect whether the server supports resuming until the user actually tries to resume. in such a case, the stream listener will get an ns_error_not_resumable status. here, too, the front-end may want to offer downloading the entire file from scratch. ...
Examine and edit CSS - Firefox Developer Tools
you can: toggle pseudo-classes; toggle classes; add a new rule; change the display based on the color scheme preference (as of firefox 72, you must set devtools.inspector.color-scheme-simulation.enabled to true in the configuration editor to enable this feature); change the display based on print media rules. a warning icon appears next to unsupported css properties or rules that have invalid values. ...
...r over a declaration, a checkbox appears next to it: you can use this to toggle the declaration on or off. filename and line number: on the right-hand side is a link to the rule. see link to css file. if the element has a display: grid declaration, then it gets a grid icon next to it, like this: . click that icon to display the grid overlaid on the page, including grid lines and tracks. see examine grid layouts for more on this. to view user-agent styles (i.e., browser-default css rules), enable "inspector > show browser styles" under the developer tool settings panel. (note that this setting is independent of the "browser styles" checkbox in the computed view.) user-agent styles are displayed against a different background, and the link to the filename and line number contains the prefi...
..., :focus-within and :visited pseudo-classes for the selected element: this feature can also be accessed from the popup menu in the html view. if you enable one of these pseudo-classes for a node, an orange dot appears in the markup view next to all nodes to which the pseudo-class has been applied. in addition, the information that appears on the page itself show you what pseudo-class you are examining. for example: viewing and changing classes on an element with an element selected in the html pane, you can click the .cls button in the rules pane toolbar, to display the classes defined on that element. you can clear the checkbox for a particular class name, to see how the element would appear without that class applied to it. you can add a class to the element by typing a name in th...
...ng the button repeatedly: icon value description null the prefers-color-scheme media feature is not defined. light the user prefers a light interface. dark the user prefers a dark interface. note that the first three states of the button may be difficult to distinguish visually. they typically produce a similar effect. examine computed css to see the complete computed css for the selected element, select the computed panel in the righthand pane. this panel shows the calculated value that each css property has for the selected element. (this calculated value is exactly the same as what getcomputedstyle would return.) you can tab through the styles to select them, and you can find more information about each propert...
EffectTiming.easing - Web APIs
the effecttiming dictionary's easing property in the web animations api specifies the timing function used to scale the time to produce easing effects, where easing is the rate of the animation's change over time. element.animate(), keyframeeffectreadonly(), and keyframeeffect() all accept an object of timing properties including easing. the value of easing corresponds directly to animationeffecttimingreadonly.easing in timing objects returned by animationeffectreadonly, keyframeeffectreadonly, and keyframeeffect. syntax var timingproperties = { easing: single-transition-timing-function } timingproperties.easing = single-transition-timing-function value a string defining the timing function to use for easing transitions during the animation process. accepts several pre-d...
...ing objects returned by animationeffectreadonly, keyframeeffectreadonly, and keyframeeffect. syntax var timingproperties = { easing: single-transition-timing-function } timingproperties.easing = single-transition-timing-function value a string defining the timing function to use for easing transitions during the animation process. accepts several pre-defined domstring values, a steps() timing function like steps(5, end), or a custom cubic-bezier value like cubic-bezier(0.42, 0, 0.58, 1). defaults to linear. available values include: linear a constant rate of change, neither accelerating nor deccelerating. cubic-bezier(<number>, <number>, <number>, <number>) specifies a cubic bézier timing function. the four numbers specify points p1 and p2 of the curve as (x1, y1, x2, y2). ...
...c-bezier(0.25, 0.1, 0.25, 1). ease-in an accelerated rate of change, going from slow to fast. equivalent to cubic-bezier(0.42, 0, 1, 1). ease-out another decelerated rate of change, going from fast to slow. equivalent to cubic-bezier(0, 0, 0.58, 1). ease-in-out this rate of change speeds up in the middle. equivalent to cubic-bezier(0.42, 0, 0.58, 1). frames(<integer>) specifies a frames timing function, which breaks the animation down into a number of equal time intervals but also displays the start (0%) and end (100%) states for an equal amount of time to the other intervals. the browser flips to a different static frame when each interval is reached, rather than animating smoothly. see github for a simple example that illustrates the difference between steps() and frames(). steps(<...
...mber of equal time intervals but also displays the start (0%) and end (100%) states for an equal amount of time to the other intervals. the browser flips to a different static frame when each interval is reached, rather than animating smoothly. see github for a simple example that illustrates the difference between steps() and frames(). steps(<integer>[, [ start | end ] ]?) specifies a step timing function, which breaks the animation down into a number of equal time intervals. the browser flips to a different static frame when each interval is reached, rather than animating smoothly. the first parameter specifies the number of intervals in the function. it must be a positive integer (greater than 0). the second parameter, which is optional, specifies the point at which the change of value...
Using Navigation Timing - Web APIs
the navigation timing api lets you easily obtain detailed and highly accurate timing information to help isolate performance problems with your site's code or resources. unlike other tools or libraries, the navigation timing api lets you gather information that only the browser can provide at a level of accuracy much improved over other techniques. it also offers the advantage of being able to provide timing information as perceived by the user rather than data that has no correlation to what the user experiences. 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. for example, to measure the perceived loading time for a page: window.addeventlistener("load", function(...
...rrelation to what the user experiences. 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. for example, to measure the perceived loading time for a page: window.addeventlistener("load", function() { let now = new date().gettime(); let loadingtime = now - performance.timing.navigationstart; document.queryselector(".output").innertext = loadingtime + " ms"; }, false); this code, executed when the load event occurs, subtracts from the current time the time at which the navigation whose timing was recorded began (performance.timing.navigationstart), and outputs that information to the screen by inserting it into an element. html <div class="output"> </...
...ationstart), and outputs that information to the screen by inserting it into an element. html <div class="output"> </div> css .output { border: 1px solid #bbb; font: 16px "open sans", "helvetica", "arial", sans-serif; } in tandem with appropriate html and css, the result is: the values listed are for the <iframe> in which the sample is presented above. for a list of the available timing values you can look for in performancetiming, see the performancetiming interface's properties section. determining navigation type to put the timing information obtained from performancetiming into the correct perspective, you need to know more about what sort of load operation occurred. in particular, you need to know: was this a load or a reload? was this a navigation or a move forward ...
...required in order to complete the navigation? this information is provided by the performance.navigation property, which returns a performancenavigation object that includes the needed information. let's add this information to the example above. ...
Performance: resourcetimingbufferfull event - Web APIs
the resourcetimingbufferfull event is fired when the browser's resource timing buffer is full. bubbles yes cancelable yes interface event event handler property onresourcetimingbufferfull examples the following example sets a callback function on the onresourcetimingbufferfull property. ...
...etimingbufferfull event is fired when the browser's resource timing buffer is full. bubbles yes cancelable yes interface event event handler property onresourcetimingbufferfull examples the following example sets a callback function on the onresourcetimingbufferfull property. ...
... resource timing buffer is full. bubbles yes cancelable yes interface event event handler property onresourcetimingbufferfull examples the following example sets a callback function on the onresourcetimingbufferfull property. ...
...nt handler property onresourcetimingbufferfull examples the following example sets a callback function on the onresourcetimingbufferfull property. 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. candidate recommendation ...
Using the User Timing API - Web APIs
the user timing interface allows the developer to create application specific timestamps that are part of the browser's performance timeline. there are two types of user defined timing entry types: the "mark" entry type and the "measure" entry type. mark events are named by the application and can be set at any location in an application. measure events are also named by the application but they are placed between two marks thus they are effectively a midpoint between two marks. this document shows how to create mark and measure performance entry types and how to use user timing methods (which are extensions of the performance interface) to retrieve and remove entries from the browser's performance timeline. a live version of the examples is available on github, as is the source code. pul...
...turn; } log("clear measures", 1); if (typeof obj == "string") { log("... cleared '" + obj + "' measure(s)", 1); performance.clearmeasures(obj); } else { // no argument specified so clear all measures log("... ...
...else { // no argument specified so clear all measures log("... ...
..."... ...
SyntaxError: unterminated string literal - JavaScript
string literals must be enclosed by single (') or double (") quotes. javascript makes no distinction between single-quoted strings and double-quoted strings. escape sequences work in strings created with either single or double quotes. ...
...string literals must be enclosed by single (') or double (") quotes. javascript makes no distinction between single-quoted strings and double-quoted strings. escape sequences work in strings created with either single or double quotes. ...
...string literals must be enclosed by single (') or double (") quotes. javascript makes no distinction between single-quoted strings and double-quoted strings. escape sequences work in strings created with either single or double quotes. ...
...teral, you have escaped your string literal correctly, your string literal isn't split across multiple lines. examples multiple lines you can't split a string across multiple lines like this in javascript: var longstring = 'this is a very long string which needs to wrap across multiple lines because otherwise my code is unreadable.'; // syntaxerror: unterminated string literal instead, use the + operator, a backslash, or template literals. the + operator variant looks like this: var longstring = 'this is a very long string which needs ' + 'to wrap across multiple lines because ' + 'otherwise my code is unreadable.'; or you can use the backslash character ("\") at the end of each line to indicate that the string w...
Date.prototype.setUTCMinutes() - JavaScript
the setutcminutes() method sets the minutes for a specified date according to universal time. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax dateobj.setutcminutes(minutesvalue[, secondsvalue[, msvalue]]) parameters minutesvalue an integer between 0 and 59, representing the minutes. secondsvalue optional. an integer between 0 and 59, representing the seconds. if you specify the secondsvalue parameter, you must also specify the minutesvalue. msvalue optional. a number between 0 and 999, representing the milliseconds. ...
...svalue]]) parameters minutesvalue an integer between 0 and 59, representing the minutes. secondsvalue optional. an integer between 0 and 59, representing the seconds. if you specify the secondsvalue parameter, you must also specify the minutesvalue. msvalue optional. a number between 0 and 999, representing the milliseconds. if you specify the msvalue parameter, you must also specify the minutesvalue and secondsvalue. return value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date. description if you do not specify the secondsvalue and msvalue parameters, the values returned from getutcseconds() and getutcmilliseconds() methods are used. ...
...e parameter, you must also specify the minutesvalue and secondsvalue. return value the number of milliseconds between 1 january 1970 00:00:00 utc and the updated date. description if you do not specify the secondsvalue and msvalue parameters, the values returned from getutcseconds() and getutcmilliseconds() methods are used. if a parameter you specify is outside of the expected range, setutcminutes() attempts to update the date information in the date object accordingly. for example, if you use 100 for secondsvalue, the minutes will be incremented by 1 (minutesvalue + 1), and 40 will be used for seconds. ...
...eters, the values returned from getutcseconds() and getutcmilliseconds() methods are used. if a parameter you specify is outside of the expected range, setutcminutes() attempts to update the date information in the date object accordingly. for example, if you use 100 for secondsvalue, the minutes will be incremented by 1 (minutesvalue + 1), and 40 will be used for seconds. examples using setutcminutes() var thebigday = new date(); thebigday.setutcminutes(43); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcminutes' in that specification. ...
Math.min() - JavaScript
the static function math.min() returns the lowest-valued number passed into it, or nan if any parameter isn't a number and can't be converted into one. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax math.min([value1[, value2[, ...]]]) parameters value1, value2, ... zero or more numbers among which the lowest value will be selected and returned. return value the smallest of the given numbers. if any one or more of the parameters cannot be converted into a number, nan is returned. the result is infinity if no parameters are provided. ...
...nd us a pull request. syntax math.min([value1[, value2[, ...]]]) parameters value1, value2, ... zero or more numbers among which the lowest value will be selected and returned. return value the smallest of the given numbers. if any one or more of the parameters cannot be converted into a number, nan is returned. the result is infinity if no parameters are provided. description because min() is a static method of math, you always use it as math.min(), rather than as a method of a math object you created (math is not a constructor). if no arguments are given, the result is infinity. if at least one of arguments cannot be converted to a number, the result is nan. ...
..., nan is returned. the result is infinity if no parameters are provided. description because min() is a static method of math, you always use it as math.min(), rather than as a method of a math object you created (math is not a constructor). if no arguments are given, the result is infinity. if at least one of arguments cannot be converted to a number, the result is nan. 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. ...
... number, the result is nan. 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. for instance, this var x = f(foo); if (x > boundary) { x = boundary; } may be written as this var x = math.min(f(foo), boundary); math.max() can be used in a similar way to clip a value at the other end. specifications specification ecmascript (ecma-262)the definition of 'math.min' in that specification. ...
min - SVG: Scalable Vector Graphics
Web › SVG › Attribute › min
the min attribute specifies the minimum value of the active animation duration. ...
... the min attribute specifies the minimum value of the active animation duration. ...
...the value must be greater than 0. specification...
...ues="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 length of the minimum value of the active duration, measured in local time. the value must be greater than 0. specifications specification status comment svg animations level 2the definition of 'min' in that specification. editor's draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of 'min' in that specification. recommendation in...
Computer Programming - MDN Web Docs Glossary: Definitions of Web-related terms
computer programming is a process of composing and organizing a collection of instructions. these tell a computer/software program what to do in a language which the computer understands. these instructions come in the form of many different languages such as c++, java, javascript, html, python, ruby, and rust. using an appropriate language, you can program/create all sorts of software. for example, a program that helps scientists with complex calculations, a database that stores huge amounts of data, a web site that allows people to download music, or animation software that allows people to create animated movies. ...
...ript, html, python, ruby, and rust. ...
.... using an appropriate language, you can program/create all sorts of software. ...
Dominator - MDN Web Docs Glossary: Definitions of Web-related terms
in graph theory, node a dominates node b if every path from the root node to b passes through a. this concept is important for garbage collection because it means that b is only reachable through a. so if the garbage collector found a to be unreachable and eligible for reclaiming, than b would also be unreachable and eligible for reclaiming. so objects that a dominates contribute to the retained size of a: that is, the total amount of memory that could be freed if a itself were freed. ...
... garbage collection because it means that b is only reachable through a. so if the garbage collector found a to be unreachable and eligible for reclaiming, than b would also be unreachable and eligible for reclaiming. ...
...nly reachable through a. so if the garbage collector found a to be unreachable and eligible for reclaiming, than b would also be unreachable and eligible for reclaiming. so objects that a dominates contribute to the retained size of a: that is, the total amount of memory that could be freed if a itself were freed. ...
Server Timing - MDN Web Docs Glossary: Definitions of Web-related terms
the server timing specification enables the server to communicate performance metrics from the request-response cycle to the user agent, and utilizes a javascript interface to allow applications to collect, process, and act on these metrics to optimize application delivery. ...
... the server timing specification enables the server to communicate performance metrics from the request-response cycle to the user agent, and utilizes a javascript interface to allow applications to collect, process, and act on these metrics to optimize application delivery. ...
... the server timing specification enables the server to communicate performance metrics from the request-response cycle to the user agent, and utilizes a javascript interface to allow applications to collect, process, and act on these metrics to optimize application delivery. ...
Interval Timing
the type of such arguments is printervaltime. such parameters are common in nspr functions such as those used for i/o operations and operations on condition variables. nspr 2.0 provides interval times that are efficient in terms of performance and storage requirements. ...
...ions such as those used for i/o operations and operations on condition variables. nspr 2.0 provides interval times that are efficient in terms of performance and storage requirements. ...
...due to some administrative action). the counters have no fixed epoch and have a finite period. to make use of these counters, the application must declare a point in time, the epoch, and an amount of time elapsed since that epoch, the interval. in almost all cases the epoch is defined as the value of the interval timer at the time it was sampled. ...
The Rust programming language
rust is a new open-source systems programming language created by mozilla and a community of volunteers, designed to help developers create fast, secure applications which take full advantage of the powerful features of modern multi-core processors. it prevents segmentation faults and guarantees thread safety, all with an easy-to-learn syntax. in addition, rust offers zero-cost abstractions, move semantics, guaranteed memory safety, threads with no data races, trait-based generics, pattern matching, type inference, and efficient c bindings, with a minimum runtime size. to learn more about rust, you can: watch the videos below for a closer look at the power and benefits rust provides. read the book the rust programming language online. download the rust compiler, check out examp...
...d efficient c bindings, with a minimum runtime size. to learn more about rust, you can: watch the videos below for a closer look at the power and benefits rust provides. read the book the rust programming language online. download the rust compiler, check out examples, and learn everything you could possibly wish to know at the rust official web site. ...
...ideos below for a closer look at the power and benefits rust provides. read the book the rust programming language online. download the rust compiler, check out examples, and learn everything you could possibly wish to know at the rust official web site. ...
HeapMinimize
if false, the flush will be scheduled to happen when the app is idle. return values this function return ns_ok if successful. ...
...if false, the flush will be scheduled to happen when the app is idle. return values this function return ns_ok if successful. ...
...if false, the flush will be scheduled to happen when the app is idle. return values this function return ns_ok if successful. ...
CSS Grid Inspector: Examine grid layouts - Firefox Developer Tools
note: the examples shown in the screenshots appearing in this article are jen simmons' futurismo and variations on a grid experiments, and a live named grid area example from rachel andrew. discovering css grids when an html element on your page has display: grid applied to it, a number of features are made available in the devtools to provide easy access to grid features. in the html pane in the html pane, elements laid out using a grid have a "grid" marker beside them. ...
...r each grid overlay on and off (on by default). display area names: turn area names on and off, in the case of grids with named grid areas (on by default, where relevant). extend lines infinitely: by default, grid lines/tracks are only shown inside the element with display: grid set on it; when toggling this option on, the grid lines extend to the edge of the viewport along each axis. mini grid view: a smaller view of the currently overlaid grid. note: your grid preferences such as overlay color and display settings choices are persisted across page loads for each separate page. let's examine these features in more detail. overlay grid each grid present on a page has an entry in the "overlay grid" section: each entry consists of (from left to right): a checkbox allowi...
...es in a grid with named areas, the area names are shown on the grid overlay by default. unchecking the "display area names" box turns them off. extend lines infinitely by default, the grid lines/tracks are only shown inside the element with display: grid set on it. when you check the "extend lines infinitely" option, the grid lines extend to the edge of the viewport along each axis. mini grid view shows a small version of the currently overlaid grid, which is in proportion to the real thing. hovering over the different areas of the mini grid causes the equivalent area on the grid overlay to also highlight, along with a tooltip containing useful information such as the dimensions of that area, its row and column numbers, etc. ...
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(). syntax var curvalue = analysernode.mindecibels; analysernode.mindecibels = newvalue; value a double, representing the minimum decibel value for scaling the fft analysis data, where 0 db is the loudest possible sound, -10 db is a 10th of that, etc. the default value is -100 db. when getting data from getfloatfrequencydata() or getbytefrequencydata(), any frequencies with an amplitude of mindecibels or lower will be returned as 0.0 or 0, respectively. no...
...uestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); analyser.mindecibels = -90; analyser.maxdecibels = -10; ... analyser.fftsize = 256; var bufferlength = analyser.frequencybincount; console.log(bufferlength); var dataarray = new uint8array(bufferlength); canvasctx.clearrect(0, 0, width, height); function draw() { drawvisual = requestanimationframe(draw); analyser.getbytefrequencydata(dataarray); canvasctx.fillstyle = 'rgb(0, 0, 0)'; canvasctx.
... working draft ...
AnimationEffect.getComputedTiming() - Web APIs
the getcomputedtiming() method of the animationeffect interface returns the calculated timing properties for this animation effect. although many of the attributes of the returned object are common to the effecttiming contained in the object returned by the animationeffect.gettiming() method, the values returned by this object differ in the following ways: duration returns the calculated value of the iteration duration. if effecttiming.duration is the string auto, this attribute will return 0. fill the auto value is replaced with the appropriate effecttiming.fill value. these values are comparable to the computed styles of an element returned using window.getcomputedstyle(elem). syntax var currenttimevalues = animation.getcomputedtiming(); parameters none. return value a...
...n duration. if effecttiming.duration is the string auto, this attribute will return 0. fill the auto value is replaced with the appropriate effecttiming.fill value. these values are comparable to the computed styles of an element returned using window.getcomputedstyle(elem). syntax var currenttimevalues = animation.getcomputedtiming(); parameters none. return value a computedeffecttiming dictionary object, which contains the following properties: endtime the end time of the animation in milliseconds from the animation's start (if the keyframeeffect is associated with an animation). (also includes effecttiming.enddelay in that calculation.) activeduration the length of time in milliseconds that the animation's effects will run. this is equal to the iteration duration multip...
... working draft editor's draft. ...
Determining the dimensions of elements - Web APIs
how much room does it use up? if you need to know the total amount of space an element occupies, including the width of the visible content, scrollbars (if any), padding, and border, you want to use the htmlelement.offsetwidth and htmlelement.offsetheight properties. ...
... how much room does it use up? if you need to know the total amount of space an element occupies, including the width of the visible content, scrollbars (if any), padding, and border, you want to use the htmlelement.offsetwidth and htmlelement.offsetheight properties. ...
... how much room does it use up? if you need to know the total amount of space an element occupies, including the width of the visible content, scrollbars (if any), padding, and border, you want to use the htmlelement.offsetwidth and htmlelement.offsetheight properties. ...
EXT_blend_minmax - Web APIs
the ext_blend_minmax extension is part of the webgl api and extends blending capabilities by adding two new blend equations: the minimum or maximum color components of the source and destination colors. webgl extensions are available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: this extension is only available to webgl1 contexts. in webgl2, the functionality of this extension is available on the webgl2 context by default. the constants in webgl2 are gl.min and gl.max. ...
... the webgl tutorial. availability: this extension is only available to webgl1 contexts. in webgl2, the functionality of this extension is available on the webgl2 context by default. the constants in webgl2 are gl.min and gl.max. constants this extension adds two new constants, which can be used in webglrenderingcontext.blendequation() and webglrenderingcontext.blendequationseparate(): ext.min_ext produces the minimum color components of the source and destination colors. ext.max_ext produces the maximum color components of the source and destination colors. ...
...l.max. constants this extension adds two new constants, which can be used in webglrenderingcontext.blendequation() and webglrenderingcontext.blendequationseparate(): ext.min_ext produces the minimum color components of the source and destination colors. ext.max_ext produces the maximum color components of the source and destination colors. examples var ext = gl.getextension('ext_blend_minmax'); gl.blendequation(ext.min_ext); gl.blendequation(ext.max_ext); gl.blendequationseparate(ext.min_ext, ext.max_ext); specifications specification status comment ext_blend_minmaxthe definition of 'ext_blend_minmax' in that specification. recommendation initial definition. ...
EffectTiming.endDelay - Web APIs
the enddelay property of the effecttiming dictionary (part of the web animations api) indicates the number of milliseconds to delay after the active period of an animation sequence. the animation's end time—the time at which an iteration is considered to have finished—is the time at which the animation finishes an iteration (its initial delay, animationeffecttimingreadonly.delay, plus its duration,duration, plus its end delay. this is useful for sequencing animations based on the end time of another animation; note, however, that many of the sequence effectst that will benefit most from this property have not been defined in the specification yet. for now, its main purpose is to represent the value of the svg min attribute. element.animate(), keyframeeffectreadonly(), and ke...
.... this is useful for sequencing animations based on the end time of another animation; note, however, that many of the sequence effectst that will benefit most from this property have not been defined in the specification yet. for now, its main purpose is to represent the value of the svg min attribute. element.animate(), keyframeeffectreadonly(), and keyframeeffect() all accept an object of timing properties including enddelay. ...
...er, that many of the sequence effectst that will benefit most from this property have not been defined in the specification yet. for now, its main purpose is to represent the value of the svg min attribute. element.animate(), keyframeeffectreadonly(), and keyframeeffect() all accept an object of timing properties including enddelay. the value of enddelay corresponds directly to animationeffecttimingreadonly.enddelay in timing objects returned by animationeffectreadonly, keyframeeffectreadonly, and keyframeeffect. syntax var timingproperties = { enddelay: delayinmilliseconds } timingproperties.enddelay = delayinmilliseconds; value a number representing the end delay, specified in milliseconds. the default value is 0. specifications specification status comment ...
EffectTiming.iterationStart - Web APIs
web animations api's effecttiming dictionary's iterationstart property specifies the repetition number which repetition the animation begins at and its progress through it. element.animate(), keyframeeffectreadonly.keyframeeffectreadonly(), and keyframeeffect.keyframeeffect() all accept an object of timing properties including iterationstart. the value of iterationstart corresponds directly to animationeffecttimingreadonly.iterationstart in timing objects returned by animationeffectreadonly, keyframeeffectreadonly, and keyframeeffect. ...
...s through it. element.animate(), keyframeeffectreadonly.keyframeeffectreadonly(), and keyframeeffect.keyframeeffect() all accept an object of timing properties including iterationstart. the value of iterationstart corresponds directly to animationeffecttimingreadonly.iterationstart in timing objects returned by animationeffectreadonly, keyframeeffectreadonly, and keyframeeffect. syntax var timingproperties = { iterationstart = iterationnumber }; timingproperties.iterationstart = iterationnumber; value a floating-point value whose value is at least 0 and is not +infinity, indicating the offset into the number of iterations the animation sequence is to run at which to start animating. iterationstart represents the iteration index at which the animation effect begins as well as its pr...
...ed. since all animations' iteration indexes start at 0, a value of 0.5 would start the animation halfway through its first iteration or loop. meanwhile, a value of 1.2 means the animation will begin playback 20% of the way through its second iteration, and so forth. it's currently undefined what happens if you specify a value of iterationstart which is greater than the value of animationeffecttimingproperties.iterations. see issue 170 in the web animations api specification's issue tracker for details and status of any changes to the specification in this regard. specifications specification status comment web animationsthe definition of 'iterationstart' in that specification. working draft editor's draft. ...
EffectTiming - Web APIs
these properties are all optional, although without setting a duration the animation will not play. simply put, these properties describe how the user agent should go about making the transition from keyframe to keyframe, and how to behave when the animation begins and ends. properties delay optional the number of milliseconds to delay the start of the animation. defaults to 0. ...
...tion optional whether the animation runs forwards (normal), backwards (reverse), switches direction after each iteration (alternate), or runs backwards and switches direction after each iteration (alternate-reverse). defaults to "normal". duration optional the number of milliseconds each iteration of the animation takes to complete. defaults to 0. although this is technically optional, keep in mind that your animation will not run if this value is 0. easing optional the rate of the animation's change over time. accepts the pre-defined values "linear", "ease", "ease-in", "ease-out", and "ease-in-out", or a custom "cubic-bezier" value like "cubic-bezier(0.42, 0, 0.58, 1)". defaults to "linear". enddelay optional the number of milliseconds to delay after the end of an animation. this is p...
... working draft initial definition ...
Using the Frame Timing API - Web APIs
the performanceframetiming interface provides frame timing data about the browser's event loop. a frame represents the amount of work a browser does in one event loop iteration such as processing dom events, resizing, scrolling, rendering, css animations, etc. a frame rate of 60 fps (frames per second) for a 60 hz refresh rate is a common target for a good responsive user experience. this means the browser should process a frame in about 16.7ms. an application can register a performanceobserver for "frame" performance entry types and the observer will have data about the duration of each frame event. this data can be used to help identify areas that take too long to provide a good user experience. ...
...ive user experience. this means the browser should process a frame in about 16.7ms. an application can register a performanceobserver for "frame" performance entry types and the observer will have data about the duration of each frame event. this data can be used to help identify areas that take too long to provide a good user experience. this document describes how to use the performanceframetiming interfaces including example code. for an overview of these interfaces see frame timing api. frame observers the performance observer interfaces allow an application to register an observer for specific performance event types. when one of those event types is added to the browser's performance timeline, the application is notified of the event via the observer's callback function that was sp...
...veloper to record a piece of the user's interaction and the data obtained during the recording is used to create a profile of the browser's activity. the profile includes a waterfall of the activity such as event handling, layout, painting, scripting, etc. firefox's performance tool also includes a frame rate graph which provides timestamps for each frame including the average frame rate and the minimum and maximum rates (for a specific recording session). this data, along with the waterfall data, gives an indication of where a site might be having frame related performance problems (for example, by correlating the recording's minimum rates with their respective waterfall events). the performance tool's flame chart and call tree tabs provide data to help analyze the site's javascript usage.
performance.setResourceTimingBufferSize() - Web APIs
the setresourcetimingbuffersize() method sets the browser's resource timing buffer size to the specified number of "resource" performance entry type objects. a browser's recommended resource timing buffer size is at least 150 performance entry objects. note: this feature is available in web workers. syntax performance.setresourcetimingbuffersize(maxsize); arguments maxsize a number representing the maximum number of performance entry objects the browser should hold in its performance entry buffer. return value none this method has no return value. ...
...er size is at least 150 performance entry objects. note: this feature is available in web workers. syntax performance.setresourcetimingbuffersize(maxsize); arguments maxsize a number representing the maximum number of performance entry objects the browser should hold in its performance entry buffer. return value none this method has no return value. example function setresourcetimingbuffersize(maxsize) { if (performance === undefined) { log("browser does not support web performance"); return; } var supported = typeof performance.setresourcetimingbuffersize == "function"; if (supported) { log("... ...
...ould hold in its performance entry buffer. return value none this method has no return value. example function setresourcetimingbuffersize(maxsize) { if (performance === undefined) { log("browser does not support web performance"); return; } var supported = typeof performance.setresourcetimingbuffersize == "function"; if (supported) { log("... performance.setresourcetimingbuffersize() = yes"); performance.setresourcetimingbuffersize(maxsize); } else { log("... performance.setresourcetimingbuffersize() = not supported"); } } specifications specification status comment resource timing level 1the definition of 'setresourcetimingbuffersize()' in that specification. candidate recommendation initial definition. ...
PerformanceEventTiming - Web APIs
the performanceeventtiming interface of the event timing api provides timing information for the event types listed below. auxclick beforeinput click compositionend compositionstart compositionupdate contextmenu dblclick dragend dragenter dragleave dragover dragstart drop input keydown keypress keyup mousedown mouseenter mouseleave mouseout mouseover mouseup pointerover pointerenter pointerdown pointerup pointercancel pointerout pointerleave gotpointercapture lostpointercapture touchstart touchend touchcancel properties performanceeventtiming.processingstart returns the time at which event dispatch started. performanceeventtiming.processingend returns the time at which the event dispatch ended. ...
...useover mouseup pointerover pointerenter pointerdown pointerup pointercancel pointerout pointerleave gotpointercapture lostpointercapture touchstart touchend touchcancel properties performanceeventtiming.processingstart returns the time at which event dispatch started. performanceeventtiming.processingend returns the time at which the event dispatch ended. performanceeventtiming.cancelable returns the associated event's cancelable attribute. performanceeventtiming.target returns the associated event's last target, if it is not removed. methods performanceeventtiming.tojson() converts the performanceeventtiming object to json. examples the following example shows how to use the api for all events: const observer = new performanceobserver(function(list) { ...
...and when) the page was first hidden, see: // https://github.com/w3c/page-visibility/issues/29 // note: ideally this check would be performed in the document <head> // to avoid cases where the visibility state changes before this code runs. let firsthiddentime = document.visibilitystate === 'hidden' ? 0 : infinity; document.addeventlistener('visibilitychange', (event) => { firsthiddentime = math.min(firsthiddentime, event.timestamp); }, {once: true}); // sends the passed data to an analytics endpoint. this code // uses `/analytics`; you can replace it with your own url. function sendtoanalytics(data) { const body = json.stringify(data); // use `navigator.sendbeacon()` if available, falling back to `fetch()`. (navigator.sendbeacon && navigator.sendbeacon('/analytics', body)) || f...
PerformanceNavigationTiming.domContentLoadedEventEnd - Web APIs
esenting the time value equal to the time immediately after the current document's domcontentloaded event completes. syntax perfentry.domcontentloadedeventend; return value a timestamp representing the time value equal to the time immediately after the current document's domcontentloaded event completes. example the following example illustrates this property's usage. ...
...ntries = performance.getentriesbytype("navigation"); for (var i=0; i < perfentries.length; i++) { console.log("= navigation entry[" + i + "]"); var p = perfentries[i]; // dom properties console.log("dom content loaded = " + (p.domcontentloadedeventend - p.domcontentloadedeventstart)); console.log("dom complete = " + p.domcomplete); console.log("dom interactive = " + p.dominteractive); // document load and unload time console.log("document load = " + (p.loadeventend - p.loadeventstart)); console.log("document unload = " + (p.unloadeventend - p.unloadeventstart)); // other properties console.log("type = " + p.type); console.log("redirectcount = " + p.redirectcount); } } specifications specification status comment ...
... working draft initial definition. ...
PerformanceNavigationTiming.loadEventEnd - Web APIs
the loadeventend read-only property returns a timestamp which is equal to the time when the load event of the current document is completed. syntax perfentry.loadeventend; return value a timestamp representing the time when the load event of the current document is completed. example the following example illustrates this property's usage. ...
...ntries = performance.getentriesbytype("navigation"); for (var i=0; i < perfentries.length; i++) { console.log("= navigation entry[" + i + "]"); var p = perfentries[i]; // dom properties console.log("dom content loaded = " + (p.domcontentloadedeventend - p.domcontentloadedeventstart)); console.log("dom complete = " + p.domcomplete); console.log("dom interactive = " + p.dominteractive); // document load and unload time console.log("document load = " + (p.loadeventend - p.loadeventstart)); console.log("document unload = " + (p.unloadeventend - p.unloadeventstart)); // other properties console.log("type = " + p.type); console.log("redirectcount = " + p.redirectcount); } } specifications specification status comment ...
... working draft initial definition. ...
RTCIceCandidatePairStats.nominated - Web APIs
the rtcicecandidatepairstats property nominated specifies whether or not the candidate pair described by the underlying rtcicecandidatepair has been nominated to be used as the configuration for the webrtc connection. syntax nominated = rtcicecandidatepairstats.nominated; value a boolean value which is set to true by the ice layer if the controlling user agent has indicated that the candidate pair should be used to configure the webrtc connection between the two peers. note: if more than one candidate pair are nominated at the same time, the one whose priority is higher will be selected for use. ...
...ecandidatepairstats.nominated; value a boolean value which is set to true by the ice layer if the controlling user agent has indicated that the candidate pair should be used to configure the webrtc connection between the two peers. note: if more than one candidate pair are nominated at the same time, the one whose priority is higher will be selected for use. once a candidate pair has been nominated and the two peers have each reconfigured themselves to use the specified configuration, the ice negotiation process can potentially end (or it can continue, to allow the connection to adapt to changing conditions). ...
...e pair has been nominated and the two peers have each reconfigured themselves to use the specified configuration, the ice negotiation process can potentially end (or it can continue, to allow the connection to adapt to changing conditions). specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcicecandidatepairstats.nominated' in that specification. candidate recommendation initial specification. ...
HTML attribute: minlength - HTML: Hypertext Markup Language
the minlength attribute defines the minimum number of characters (as utf-16 code units) the user can enter into an <input> or <textarea>. this must be an integer value 0 or higher. if no minlength is specified, or an invalid value is specified, the input has no minimum length. this value must be less than or equal to the value of maxlength, otherwise the value will never be valid, as it is impossible to meet both criteria. the input will fail constraint validation if the length of the text value of the field is less than minlength utf-16 code units long, with validitystate.tooshort returning true. constraint validation is only applied when the value is changed by the user. ...
...ll never be valid, as it is impossible to meet both criteria. the input will fail constraint validation if the length of the text value of the field is less than minlength utf-16 code units long, with validitystate.tooshort returning true. constraint validation is only applied when the value is changed by the user. once submission fails, some browsers will display an error message indicating the minimum length required and the current length. examples by adding minlength="5", the value must either be empty or five characters or longer to be valid. <label for="fruit">enter a fruit name that is at least 5 letters long</label> <input type="text" minlength="5" id="fruit"> we can use pseudoclasses to style the element based on whether the value is valid. the value will be valid as long as it ...
... the value will be valid as long as it is either null (empty) or five or more characters long. lime is invalid, lemon is valid. input { border: 2px solid currentcolor; } input:invalid { border: 2px dashed red; } input:invalid:focus { background-image: linear-gradient(pink, lightgreen); } specifications specification status html living standardthe definition of 'minlength attribute' in that specification. living standard html 5.1the definition of 'minlength attribute' in that specification. recommendation ...
Number.MIN_SAFE_INTEGER - JavaScript
the number.min_safe_integer constant represents the minimum safe integer in javascript (-(253 - 1)). to represent integers smaller than this, consider using bigint. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. property attributes of number.min_safe_integer writable no enumerable no configurable no description the min_safe_integer constant has a value of -9007199254740991 (-9,007,199,254,740,991 or about -9 quadrillion). the reasoning behind that number is that javascript uses double-precision floating-point format ...
... no description the min_safe_integer constant has a value of -9007199254740991 (-9,007,199,254,740,991 or about -9 quadrillion). the reasoning behind that number is that javascript uses double-precision floating-point format numbers as specified in ieee 754 and can only safely represent numbers between -(253 - 1) and 253 - 1. see number.issafeinteger() for more information. because min_safe_integer is a static property of number, you always use it as number.min_safe_integer, rather than as a property of a number object you created. ...
...mber is that javascript uses double-precision floating-point format numbers as specified in ieee 754 and can only safely represent numbers between -(253 - 1) and 253 - 1. see number.issafeinteger() for more information. because min_safe_integer is a static property of number, you always use it as number.min_safe_integer, rather than as a property of a number object you created. 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. ...
Number.MIN_VALUE - JavaScript
the number.min_value property represents the smallest positive numeric value representable in javascript. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. property attributes of number.min_value writable no enumerable no configurable no description the min_value property is the number closest to 0, not the most negative number, that javascript can represent. min_value has a value of approximately 5e-324. values smaller than min_value ("underflow values") are converted to 0. ...
...es of number.min_value writable no enumerable no configurable no description the min_value property is the number closest to 0, not the most negative number, that javascript can represent. min_value has a value of approximately 5e-324. values smaller than min_value ("underflow values") are converted to 0. because min_value is a static property of number, you always use it as number.min_value, rather than as a property of a number object you created. examples using min_value the following code divides two numeric values. if the result is greater than or equal to min_value, the func1 function is called; otherwise, the func2 function is called. ...
...ues") are converted to 0. because min_value is a static property of number, you always use it as number.min_value, rather than as a property of a number object you created. examples using min_value the following code divides two numeric values. if the result is greater than or equal to min_value, the func1 function is called; otherwise, the func2 function is called. if (num1 / num2 >= number.min_value) { func1(); } else { func2(); } specifications specification ecmascript (ecma-262)the definition of 'number.min_value' in that specification. ...
performInstall - Archive of obsolete content
summary performs the actual installation of the software. moves all components to their final locations, launches any pending executions, and registers the package and all of its subcomponents in the client version registry. method of install syntax int performinstall(); parameters none. returns an integer error code. for a list of possible values, see return codes. in some situations the method may return other errors. in a few cases you may get a registry error. ...
...st of possible values, see return codes. ...
minresultsforpopup - Archive of obsolete content
the default value is 1. new in thunderbird 3requires seamonkey 2.0 a zero value will always open the popup. ...
...the default value is 1. new in thunderbird 3requires seamonkey 2.0 a zero value will always open the popup. ...
min - Archive of obsolete content
Archive › Mozilla › XUL › Property › min
...
... ...
minHeight - Archive of obsolete content
...
... ...
minWidth - Archive of obsolete content
...
... ...
minuteLeadingZero - Archive of obsolete content
...
... ...
Dynamic programming language - MDN Web Docs Glossary: Definitions of Web-related terms
a dynamic programming language is a programming language in which operations otherwise done at compile-time can be done at run-time. for example, in javascript it is possible to change the type of a variable or add new properties or methods to an object while the program is running. this is opposed to so-called static programming languages, in which such changes are normally not possible. note that while there is indeed a connection between this dynamic/static property of programming languages and dynamic/static-typing, the two are far from synonymous. ...
...dd new properties or methods to an object while the program is running. this is opposed to so-called static programming languages, in which such changes are normally not possible. ...
Prototype-based programming - MDN Web Docs Glossary: Definitions of Web-related terms
prototype-based programming is a style of object-oriented programming in which classes are not explicitly defined, but rather derived by adding properties and methods to an instance of another class or, less frequently, adding them to an empty object. in simple words: this type of style allows the creation of an object without first defining its class. ...
... programming is a style of object-oriented programming in which classes are not explicitly defined, but rather derived by adding properties and methods to an instance of another class or, less frequently, adding them to an empty object. in simple words: this type of style allows the creation of an object without first defining its class. ...
FC_GetMechanismInfo
name fc_getmechanisminfo - get information on a particular mechanism. syntax ck_rv fc_getmechanisminfo( ck_slot_id slotid, ck_mechanism_type type, ck_mechanism_info_ptr pinfo ); parameters fc_getmechanisminfo takes three parameters: slotid [input] type [input] . pinfo [output] . description fc_getmechanisminfo obtains information about a particular mechanism possibly supported by a token. a user may call fc_getmechanisminfo without logging into the token (to assume the nss user role). ...
..._info_ptr pinfo ); parameters fc_getmechanisminfo takes three parameters: slotid [input] type [input] . pinfo [output] . description fc_getmechanisminfo obtains information about a particular mechanism possibly supported by a token. a user may call fc_getmechanisminfo without logging into the token (to assume the nss user role). ...
Examine, modify, and watch variables - Firefox Developer Tools
this feature isn't yet supported in the new debugger. if you need to use it, you can, for now, switch back to the old debugger by visiting about:config and setting the "devtools.debugger.new-debugger-frontend" preference to false. to see the docs for the old debugger, please visit debugger (before firefox 52). examine variables when the code has stopped at a breakpoint, you can examine its state in the variables pane of the debugger: variables are grouped by scope: in function scope you'll see the built-in arguments and this variables as well as local variables defined by the function like user and greeting. similarly, in global scope you'll see global variables you've defined, like greetme, as well as built-in globals like localstorage and console. each object can be expande...
...able. in the screenshot below the variable upvar has been optimized away: modify variables when the code has stopped at a breakpoint, you can modify variables in the variables pane of the debugger. just click on the variable's current value and you'll be able to type there: watch an expression watch expressions are expressions that are evaluated each time execution pauses. you can then examine the results of these expressions. these are useful in that they let you inspect invariants in your code that you know are there but aren't necessarily in the code ready for inspection. to add a watch expression, click in the box that says "add watch expression" and enter a javascript expression whose output you'd like to monitor as you step through code. then start running your code. the watch ...
Pretty-print a minified file - Firefox Developer Tools
note: if you want to prettify some inline javascript code, just double click the code in the inspector pane. ...
... note: if you want to prettify some inline javascript code, just double click the code in the inspector pane. ...
CSS Flexbox Inspector: Examine Flexbox layouts - Firefox Developer Tools
discovering flex containers when an html element on your page has display: flex applied to it, a number of features are made available in the devtools to provide easy access to flexbox layout features. in the html pane in the html pane, an element laid out with flexbox has the word flex next to it as shown in the following image: click the word flex in the html pane to keep the overlay visible when you move the mouse away from the container. ...
...view shows information about the calculations for the size of the selected flex item: a diagram visualizing the sizing of the flex item content size - the size of the component without any restraints imposed on it by its parent flexibility - how much a flex item grew or shrunk based on its flex-grow value when there is extra free space or its flex-shrink value when there is not enough space minimum size (only appears when an item is clamped to its minimum size) - the minimum content size of a flex item when there is no more free space in the flex container final size - the size of the flex item after all sizing constraints imposed on it have been applied (based on the values of flex-grow, flex-shrink and flex-basis) at the top of the section is a drop-down list of all the items in th...
AmbientLightSensor.illuminance - Web APIs
the illuminance property of the ambientlightsensor interface returns the current light level in lux of the ambient light level around the hosting device. if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation insfructions. syntax var level = ambientlightsensor.illuminance value a number indicating the current light level in lux. ...
...ver. this is not something that would ever be shown to a user. see feature-policy for implementation insfructions. syntax var level = ambientlightsensor.illuminance value a number indicating the current light level in lux. example if ( 'ambientlightsensor' in window ) { const sensor = new ambientlightsensor(); sensor.onreading = () => { console.log('current light level:', sensor.illuminance); }; sensor.onerror = (event) => { console.log(event.error.name, event.error.message); }; sensor.start(); } specifications specification status comment generic sensor api candidate recommendation defines sensors in general. ambient light sensorthe definition of 'illuminance' in that specification. candidate recommendation ...
CSSNumericValue.min() - Web APIs
the min() method of the cssnumericvalue interface returns the lowest value from among those values passed. the passed values must be of the same type. syntax var cssunitvalue = cssnumericvalue.min(number1 ... numbern); parameters number either a number or a cssnumericvalue. return value a cssunitvalue. exceptions typeerror indicates that an invalid type was passed to the method. examples as stated earlier, all passed values must be of the same type and value. some of the following examples illustrate what happens when they are not. ...
...n(number1 ... numbern); parameters number either a number or a cssnumericvalue. return value a cssunitvalue. exceptions typeerror indicates that an invalid type was passed to the method. examples as stated earlier, all passed values must be of the same type and value. some of the following examples illustrate what happens when they are not. // prints "1cm" console.log(css.cm("1").min(css.cm("2")).tostring()); // prints "max(1cm, 0.393701in)" console.log(css.cm("1").max(css.in("0.393701")).tostring()); specifications specification status comment css typed om level 1the definition of 'min' in that specification. working draft initial definition. ...
EffectTiming.direction - Web APIs
the direction property of the web animations api dictionary effecttiming indicates an animation's playback direction along its timeline, as well as its behavior when it reaches the end of an iteration element.animate(), keyframeeffectreadonly(), and keyframeeffect() all accept an object of timing properties including direction. the value of direction corresponds directly to animationeffecttimingreadonly.direction in timing objects returned by animationeffectreadonly, keyframeeffectreadonly, and keyframeeffect. ...
...e, as well as its behavior when it reaches the end of an iteration element.animate(), keyframeeffectreadonly(), and keyframeeffect() all accept an object of timing properties including direction. the value of direction corresponds directly to animationeffecttimingreadonly.direction in timing objects returned by animationeffectreadonly, keyframeeffectreadonly, and keyframeeffect. syntax var timingproperties = { direction: "normal" | "reverse" | "alternate" | "alternate-reverse" }; timingproperties.direction = "normal" | "reverse" | "alternate" | "alternate-reverse"; value a domstring which specifies the direction in which the animation should play as well as what to do when the playback reaches the end of the animation sequence in the current direction. it can take one of the follow...
EffectTiming.iterations - Web APIs
the web animations api dictionary effecttiming's iterations property specifies the number of times the animation should repeat. the default value is 1, indicating that it should only play once, but you can set it to any floating-point value (including positive infinity defaults to 1, and can also take a value of infinity to make it loop infinitely. element.animate(), keyframeeffectreadonly(), and keyframeeffect() all accept an object of timing properties including iterations. the value of iterations corresponds directly to animationeffecttimingreadonly.iterations in timing objects returned by animationeffectreadonly, keyframeeffectreadonly, and keyframeeffect. ...
... can also take a value of infinity to make it loop infinitely. element.animate(), keyframeeffectreadonly(), and keyframeeffect() all accept an object of timing properties including iterations. the value of iterations corresponds directly to animationeffecttimingreadonly.iterations in timing objects returned by animationeffectreadonly, keyframeeffectreadonly, and keyframeeffect. syntax var timingproperties = { iterations: numberofiterations }; timingproperties.iterations = numberofiterations; value a floating-point value specifying the number of times the animation sequence will play through. any value from 0 (don't play the animation at all) to positive infinity (run the animation indefinitely) is supported. defaults to 1, meaning the animation sequence plays through once then sto...
Frame Timing API - Web APIs
a frame represents the amount of work a browser does in one event loop iteration such as processing dom events, resizing, scrolling, rendering, css animations, etc. a frame rate of 60 fps (frames per second) for a 60 hz refresh rate is a common target for a good responsive user experience. this means the browser should process a frame in about 16.7 ms. an application can register a performanceobserver for "frame" performance entry types. the observer (callback) will be notified when new "frame" events are added to the browser's performance timeline and the frame's duration (length of time) will be available. ...
...r "frame" performance entry types. the observer (callback) will be notified when new "frame" events are added to the browser's performance timeline and the frame's duration (length of time) will be available. this data can be used to help identify areas that take too long to provide a good user experience. example code of the interfaces described in this document is included in using the frame timing api. performance frames the performanceframetiming interface extends the following performanceentry properties (for "frame" performance entry types) by qualifying and constrainting the properties as follows: performanceentry.entrytype set to "frame". performanceentry.name set to the document's address. performanceentry.starttime set to the domhighrestimestamp when the frame was started...
Performance.onresourcetimingbufferfull - Web APIs
the onresourcetimingbufferfull property is an event handler that will be called when the resourcetimingbufferfull event is fired. this event is fired when the browser's resource timing performance buffer is full. note: this feature is available in web workers. syntax callback = performance.onresourcetimingbufferfull = buffer_full_cb; return value callback an eventhandler that is invoked when the resourcetimingbufferfull event is fired. examples the following example sets a callback function on the onresourcetimingbufferfull property. ...
...: this feature is available in web workers. syntax callback = performance.onresourcetimingbufferfull = buffer_full_cb; return value callback an eventhandler that is invoked when the resourcetimingbufferfull event is fired. examples the following example sets a callback function on the onresourcetimingbufferfull property. 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()"> specifications specification status comment resource timing level 1the definition of 'onresourcetimingbufferfull' in that specification. candi...
PerformanceNavigationTiming.domComplete - Web APIs
tely before the user agent sets the current document readiness of the current document to complete. syntax perfentry.domcomplete; return value a timestamp representing a time value equal to the time immediately before the user agent sets the current document readiness of the current document to complete. example the following example illustrates this property's usage. ...
... working draft initial definition. ...
PerformanceNavigationTiming.domContentLoadedEventStart - Web APIs
time immediately before the user agent fires the domcontentloaded event at the current document. syntax perfentry.domcontentloadedeventstart; return value a timestamp representing the time value equal to the time immediately before the user agent fires the domcontentloaded event at the current document. example the following example illustrates this property's usage. ...
... working draft initial definition. ...
PerformanceNavigationTiming.loadEventStart - Web APIs
y returns a timestamp representing the time value equal to the time immediately before the load event of the current document is fired. syntax perfentry.loadeventstart; return value a timestamp representing a time value equal to the time immediately before the load event of the current document is fired. example the following example illustrates this property's usage. ...
... working draft initial definition. ...
PerformanceNavigationTiming.redirectCount - Web APIs
presenting the number of redirects since the last non-redirect navigation under the current browsing context. this property is read only . syntax perfentry.redirectcount; return value a number representing the number of redirects since the last non-redirect navigation under the current browsing context. example the following example illustrates this property's usage. ...
... working draft initial definition. ...
PerformanceNavigationTiming.toJSON() - Web APIs
the tojson() method is a serializer - it returns a json representation of the performancenavigationtiming object. syntax json = resourceperfentry.tojson(); arguments none return value json a json object that is the serialization of the performancenavigationtiming object as a map with entries from the closest inherited interface and with entries for each of the serializable attributes. ...
...enavigationtiming object as a map with entries from the closest inherited interface and with entries for each of the serializable attributes. example // get a resource performance entry var perfentries = performance.getentriesbytype("navigation"); var entry = perfentries[0]; // get the json and log it var json = entry.tojson(); var s = json.stringify(json); console.log("performancenavigationtiming.tojson() = " + s); specifications specification status comment navigation timing level 2the definition of 'tojson()' in that specification. working draft initial definition. ...
PerformanceNavigationTiming.type - Web APIs
he browser's reload operation or location.reload(). back_forward navigation is through the browser's history traversal operation. prerender navigation is initiated by a prerender hint. this property is read only . syntax perfentry.type; return value a string which is one of the values listed above. example the following example illustrates this property's usage. ...
... working draft initial definition. ...
PerformanceNavigationTiming.unloadEventEnd - Web APIs
agent finishes the unload event of the previous document. if there is no previous document, this property value is 0. syntax perfentry.unloadeventend; return value a timestamp representing a time value equal to the time immediately after the user agent finishes the unload event of the previous document. example the following example illustrates this property's usage. ...
... working draft initial definition. ...
PerformanceNavigationTiming.unloadEventStart - Web APIs
agent starts the unload event of the previous document. if there is no previous document, this property returns 0. syntax perfentry.unloadeventstart; return value a timestamp representing the time value equal to the time immediately before the user agent starts the unload event of the previous document. example the following example illustrates this property's usage. ...
... working draft initial definition. ...
PerformanceResourceTiming.initiatorType - Web APIs
string that represents the type of resource that initiated the performance event. the value of this string is as follows: if the initiator is a element, the property returns the element's localname. if the initiator is a css resource, the property returns "css". if the initiator is a xmlhttprequest object, the property returns "xmlhttprequest". if the initiator is a performancenavigationtiming object, the property returns an empty string (""). note: this feature is available in web workers. syntax resource.initiatortype; return value a string representing the type of resource that initiated the performance event, as specified above. example function print_performanceentries() { // use getentriesbytype() to just get the "resource" events var p = performance.getentriesbytyp...
... candidate recommendation initial definition. ...
PerformanceResourceTiming.redirectEnd - Web APIs
the redirectend read-only property returns a timestamp immediately after receiving the last byte of the response of the last redirect. when fetching a resource, if there are multiple http redirects, and any of the redirects have an origin that is different from the current document, and the timing allow check algorithm passes for each redirected resource, this property returns the time immediately after receiving the last byte of the response of the last redirect; otherwise, zero is returned. note: this feature is available in web workers. syntax resource.redirectend; return value a timestamp immediately after receiving the last byte of the response of the last redirect. example in the following example, the value of the *start and *end properties of all "resource" type events are l...
... candidate recommendation initial definition. ...
PerformanceResourceTiming.redirectStart - Web APIs
note: this feature is available in web workers. ...
... candidate recommendation initial definition. ...
PerformanceResourceTiming.toJSON() - Web APIs
the tojson() method is a serializer that returns a json representation of the performanceresourcetiming object. syntax json = resourceperfentry.tojson(); arguments none return value json a json object that is the serialization of the performanceresourcetiming object as a map with entries from the closest inherited interface and with entries for each of the serializable attributes. ...
...h entries for each of the serializable attributes. example // get a resource performance entry var perfentries = performance.getentriesbytype("resource"); var entry = perfentries[0]; // get the json and log it var json = entry.tojson(); var s = json.stringify(json); console.log("performanceentry.tojson = " + s); specifications specification status comment resource timing level 2the definition of 'tojson' in that specification. working draft ...
PerformanceResourceTiming.workerStart - Web APIs
if the resource is not intercepted by a service worker the property will always return 0. note: this feature is available in web workers. syntax resource.workerstart; value a domhighrestimestamp. example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
... working draft initial definition. ...
PerformanceTiming.connectEnd - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.connectend read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, where the connection is opened network. if the transport layer reports an error and the connection establishment is started again, the last connection establisment end time is given. if a persistent connection is used, the value will be the same as performancetiming.fetchstart. a connection is considered as opened when all secure connection handshake, or socks authentication, is terminated. ...
... opened network. if the transport layer reports an error and the connection establishment is started again, the last connection establisment end time is given. if a persistent connection is used, the value will be the same as performancetiming.fetchstart. a connection is considered as opened when all secure connection handshake, or socks authentication, is terminated. syntax time = performancetiming.connectend; specifications specification status comment navigation timingthe definition of 'performancetiming.connectend' in that specification. recommendation initial definition. ...
PerformanceTiming.connectStart - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.connectstart read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, where the request to open a connection is sent to the network. if the transport layer reports an error and the connection establishment is started again, the last connection establisment start time is given. if a persistent connection is used, the value will be the same as performancetiming.fetchstart. ...
...long representing the moment, in miliseconds since the unix epoch, where the request to open a connection is sent to the network. if the transport layer reports an error and the connection establishment is started again, the last connection establisment start time is given. if a persistent connection is used, the value will be the same as performancetiming.fetchstart. syntax time = performancetiming.connectstart; specifications specification status comment navigation timingthe definition of 'performancetiming.connectstart' in that specification. recommendation initial definition. ...
WebGL2RenderingContext.getUniformIndices() - Web APIs
the webgl2renderingcontext.getuniformindices() method of the webgl 2 api retrieves the indices of a number of uniforms within a webglprogram. syntax sequence<gluint> gl.getuniformindices(program, uniformnames); parameters program a webglprogram containing uniforms whose indices to query. uniformnames an array of domstring specifying the names of the uniforms to query. return value an array of gluint containing the uniform indices. examples var uniformindices = gl.getuniformindices(program, ['ubored', 'ubogreen', 'uboblue']); specifications specification status comment webgl 2.0the definition of 'getuniformindices' in that specification. editor's draft initial definition for webgl. ...
...value an array of gluint containing the uniform indices. examples var uniformindices = gl.getuniformindices(program, ['ubored', 'ubogreen', 'uboblue']); specifications specification status comment webgl 2.0the definition of 'getuniformindices' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'glgetuniformindices' in that specification. standard man page of the (similar) opengl api. ...
WebGLRenderingContext.getProgramInfoLog() - Web APIs
the webglrenderingcontext.getprograminfolog returns the information log for the specified webglprogram object. it contains errors that occurred during failed linking or validation of webglprogram objects. syntax gl.getprograminfolog(program); parameters program the webglprogram to query. return value a domstring that contains diagnostic messages, warning messages, and other information about the last linking or validation operation. when a webglprogram object is initially created, its information log will be a string of length 0. ...
...ssages, and other information about the last linking or validation operation. when a webglprogram object is initially created, its information log will be a string of length 0. examples checking program errors var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); gl.getprograminfolog(program); specifications specification status comment webgl 1.0the definition of 'getprograminfolog' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glgetprograminfolog' in that specification. standard man page of the opengl api. ...
Window.minimize() - Web APIs
Web › API › Window › minimize
the window.minimize() method sets the window to a minimized state. a way to undo this method programatically is by calling window.moveto(). browser compatibility the compatibility table in this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
... window.moveto(). browser compatibility the compatibility table in this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
min-zoom - CSS: Cascading Style Sheets
the min-zoom css descriptor sets the minimum zoom factor of a document defined by the @viewport at-rule. the browser will not zoom out any further than this, whether automatically or at the user's request. a zoom factor of 1.0 or 100% corresponds to no zooming. larger values are zoomed in. smaller values are zoomed out. syntax /* keyword value */ min-zoom: auto; /* <number> values */ min-zoom: 0.8; min-zoom: 2.0; /* <percentage> value */ min-zoom: 150%; values auto the user agent will set the document's lower zoom factor limit. <number> a non-negative number limiting the minimum value of the zoom factor. <percentage> a non-negative percentage limiting the minimum value of the zoom factor. formal definition related at-rule@viewportinitial valueautopercentagesthe zoom factor ...
...<number> a non-negative number limiting the minimum value of the zoom factor. <percentage> a non-negative percentage limiting the minimum value of the zoom factor. formal definition related at-rule@viewportinitial valueautopercentagesthe zoom factor itselfcomputed valueauto, or a non-negative number or percentage as specified formal syntax auto | <number> | <percentage> examples setting min zoom factor @viewport { min-zoom: 2.0; } specifications specification status comment css device adaptationthe definition of '"min-zoom" descriptor' in that specification. working draft initial definition ...
Timing-Allow-Origin - HTTP
the timing-allow-origin response header specifies origins that are allowed to see values of attributes retrieved via features of the resource timing api, which would otherwise be reported as zero due to cross-origin restrictions. header type response header forbidden header name no syntax timing-allow-origin: * timing-allow-origin: <origin>[, <origin>]* directives * the server may specify "*" as a wildcard, thereby allowing any origin to see timing resources. <origin> specifies a uri that may see the timing resources. you can specify multiple origins, separated by commas. ...
... header forbidden header name no syntax timing-allow-origin: * timing-allow-origin: <origin>[, <origin>]* directives * the server may specify "*" as a wildcard, thereby allowing any origin to see timing resources. <origin> specifies a uri that may see the timing resources. you can specify multiple origins, separated by commas. examples to allow any resource to see timing resources: timing-allow-origin: * to allow https://developer.mozilla.org to see timing resources, you can specify: timing-allow-origin: https://developer.mozilla.org specifications specification status comment resource timing level 3the definition of 'timing-allow-origin' in that specification. editor's draft initial definition. ...
customindex - Archive of obsolete content
« xul reference home customindex not in seamonkey 1.x type: integer this value is the index of the toolbar in the list of the custom toolbars. the value is updated automatically by the toolbar customization dialog. ...
min - Archive of obsolete content
Archive › Mozilla › XUL › Attribute › min
« xul reference home min type: integer the minimum value the control's value may take. the default value is 0. ...
minheight - Archive of obsolete content
« xul reference home minheight type: string (representing an integer) the minimum height of the element. this corresponds to the min-height css property. ...
minwidth - Archive of obsolete content
« xul reference home minwidth type: string (representing an integer) the minimum width of the element. this corresponds to the min-width css property. ...
textbox.min - Archive of obsolete content
« xul reference home min type: integer the minimum value the textbox's value may take. the default value is 0. ...
textbox.minResultsForPopup - Archive of obsolete content
the default value is 1. a zero value will always open the popup unless the textbox is empty. this can be used to display additional items that are not autocomplete results. ...
DOMMenuItemInactive - Archive of obsolete content
general info specification xul interface event bubbles yes cancelable yes target element default action none properties property type description target read only eventtarget the event target (the topmost target in the dom tree). type read only domstring the type of event. bubbles read only boolean whether the event normally bubbles or not. cancelable read only boolean whether the event is cancellable or not. ...
amIndicator - Archive of obsolete content
« xul reference amindicator type: string the string value displayed for hours between midnight and noon, defaulting to am. this value is determined from the user's locale. ...
minResultsForPopup - Archive of obsolete content
« xul reference minresultsforpopup type: integer gets and sets the value of the minresultsforpopup (or minresultsforpopup) attribute. ...
minute - Archive of obsolete content
« xul reference minute type: integer the currently selected minute from 0 to 59. set this property to change the selected minute. ...
pmIndicator - Archive of obsolete content
« xul reference pmindicator type: string the string value displayed for hours between noon and midnight, defaulting to pm. this value is determined from the user's locale. ...
-ms-content-zoom-limit-min - Archive of obsolete content
the -ms-content-zoom-limit-min css property is a microsoft extension that specifies the minimum zoom factor. initial value100%applies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednopercentagesthe smallest allowed zoom factor. a zoom factor of 100% corresponds to no zooming. larger values zoom in. smaller values zoom out.computed valueas specifiedanimation typediscrete syntax values <percentage> the minimum zoom factor. formal syntax <percentage> specifications not part of any specification. remarks this property constrains the limit for touch zooming as well as values of the mscontentzoomfactor property. this property has no effect on non-zoomable elements. see -ms-content-zooming for details on zoomable elements. starting with w...
-ms-content-zooming - Archive of obsolete content
initial valuezoom for the top level element, none for all other elementsapplies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas specifiedanimation typediscrete syntax values none the initial value of all elements except the top-level element. the element is not zoomable. zoom the initial value of the top-level element. the element is zoomable. formal syntax none | zoom specifications not part of any specification. remarks this property has no effect unless overflow is permitted on both the x- and y-axes. by default, zoom-enabled elements can be zoomed by the user via pinch-zoom. ...
-ms-scroll-limit-x-min - Archive of obsolete content
the -ms-scroll-limit-x-min css property is a microsoft extension that specifies the minimum value for the element.scrollleft property. initial value0applies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas specifiedanimation typediscrete syntax values <length> the minimum value for the scrollleft property. if the value is negative, then 0 is used. formal syntax <length> specifications not part of any specification. remarks this property has no effect on non-scrollable elements. the specified behavior of the -ms-scroll-limit-x-min property is only applicable at a mscontentzoomfactor of 1; the behavior of this property is undefined at other zoom factors. this property requires windows 8 or later. ...
-ms-scroll-limit-y-min - Archive of obsolete content
the -ms-scroll-limit-y-min css property is a microsoft extension that specifies the minimum value for the element.scrolltop property. initial value0applies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas specifiedanimation typediscrete syntax values <length> the minimum value for the scrolltop property. if the value is negative, then 0 is used. formal syntax <length> specifications not part of any specification. remarks this property has no effect on non-scrollable elements. the specified behavior of the -ms-scroll-limit-y-min property is only applicable at a mscontentzoomfactor of 1; the behavior of this property is undefined at other zoom factors. this property requires windows 8 or later. ...
High-level programming language - MDN Web Docs Glossary: Definitions of Web-related terms
a high-level programming language has a significant abstraction from the details of computer operation. it is designed to be easily understood by humans and for this reason they must be translated by another software. unlike low-level programming languages, it may use natural language elements, or may automate (or even entirely hide) significant areas of computing systems, making the process of developing simpler and more understandable relative to a lower-level language. the amount of abstraction provided defines how "high-level" a programming language is. the idea of a language automatically translatable into machine code, but nearer to human logic, was introduced in computer science in the 1950s, especially thanks to the work of john backus (ibm), to whom it owes the first high-le...
RTSP: Real-time streaming protocol - MDN Web Docs Glossary: Definitions of Web-related terms
real-time streaming protocol (rtsp) is a network protocol that controls how the streaming of a media should occur between a server and a client. basically, rtsp is the protocol that describes what happens when you click "pause"/"play" when streaming a video. if your computer were a remote control and the streaming server a television, rtsp would describe how the instruction of the remote control affects the tv. learn more general knowledge rtsp on wikipedia rfc 7826 (one of the documents that specifies precisely how the protocol works) ...
Resource Timing - MDN Web Docs Glossary: Definitions of Web-related terms
diagnosing performance issues requires performance data at the granularity of the resource. the resource timing api is a javascript api that is able to capture timing information for each individual resource that is fetched when a page is loaded. ...
minification - MDN Web Docs Glossary: Definitions of Web-related terms
minification is the process of removing unnecessary or redundant data without affecting how a resource is processed by the browser. minification can include the removal of code comments, white space, and unused code, as well as the shortening of variable and function names. minification is used to improve web performance by reducing file size. it is generally an automated step that occurs at build time. as minification makes code less legible to humans, developer tools have 'prettification' features that can add white space back into the code to make it a bit more legible. ...
How Mozilla determines MIME Types
mozilla uses the unknown decoder to find a mime type. file uris for file: uris, mozilla will ask the externalhelperappservice for a mime type. ftp like http uris without a mime type, ftp uris go through the unknown decoder. unknown decoder located at netwerk/streamconv/converters/nsunknowndecoder.cpp, the interesting part starts at line 287, the ssnifferentries array together with the determinecontenttype function. it does the following: checks the start of the file for "magic numbers"; this can currently detect pdf and postscript. if the file starts with <?xml, asks the externalhelperappservice for a mime type for the uri. this is done because the generic text/xml mime type does not work for xul files, and xhtml files get a different dom when interpreted as text/xml. the image li...
Renaming With Pork
source code. most refactoring toolchains are ui-based. typically they require loading the entire project into an ide. usually, ides require one to use their build system. pork does not yet have a ui, but it is also build-system agnostic and scales to large codebases. these notes are based on tools pork refactoring toolchain [required]. see installing pork. filterdiff from patchutils renaming a class 1. make two copies of the source(analysis and test). this isn't strictly required, but will save time. 2. the first copy will be an analysis copy. convince gcc to create annotated .ii files while compiling the analysis copy. typically, make cxxflags="-wp,-k,-w0 -save-temps" will work. note the -k,-w0 options are passed down to the mcpp preprocessor such that it can annotate files with ...
nsIDiskCacheStreamInternal
1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void closeinternal(); methods closeinternal() we use this method internally to close nsdiskcacheoutputstream under the cache service lock. ...
heapMinimize
...
nsIProgrammingLanguage
constant value description unknown 0 cplusplus 1 c++ javascript 2 javascript python 3 python perl 4 perl java 5 java zx81_basic 6 zx81 basic javascript2 7 javascript 2 ruby 8 ruby php 9 php tcl 10 tcl max 10 this will be kept at the largest index. ...
Filter Incoming Mail
the, you've got components.interfaces.nsimsgdbhdr from where you can modify the mail. by example, to modify the mail subject : var newmaillistener = { msgadded: function(amsghdr) { if( !amsghdr.isread ) { // here we are, a new mail has popped // let get a javascript string object from the subject property // querying mime conversion interface var mimeconvert = components.classes["@mozilla.org/messenger/mimeconverter;1"] .getservice(components.interfaces.nsimimeconverter); var subject = mimeconvert.decodemimeheader(amsghdr.subject, null, false, true); // here with have a string to modify with javascript. ...
Examine and edit HTML - Firefox Developer Tools
navigating the html html breadcrumbs at the bottom on the html pane is a breadcrumbs toolbar. this shows the complete hierarchy through the document for the branch containing the selected element: hovering over a breadcrumb highlights that element in the page. the breadcrumbs bar has its own keyboard shortcuts. searching the page inspector's search box matches all markup in the current document and in any frames. to start searching the markup, click in the search box to expand it or press ctrl + f , or cmd + f on a mac. there are three types of searches that are performed automatically depending on what you enter, a full text search, a css selector search, and an xpath search. ...
AnimationEffect.getTiming() - Web APIs
the animationeffect.gettiming() method of the animationeffect interface returns an effecttiming object containing the timing properties for the animation effect. syntax animationtiming = animation.gettiming(); returns an effecttiming object. specifications specification status comment web animationsthe definition of 'animationeffect.gettiming()' in that specification. working draft editor's draft. ...
AnimationEffect.updateTiming() - Web APIs
the updatetiming() method of the animationeffect interface updates the specified timing properties for an animation effect. syntax animation.updatetiming(timing); parameters timing an optionaleffecttiming object containing the timing properties to update. return value none. specifications specification status comment web animationsthe definition of 'animationeffect.updatetiming()' in that specification. working draft editor's draft. ...
AudioParam.minValue - Web APIs
the minvalue read-only property of the audioparam interface represents the minimum possible value for the parameter's nominal (effective) range. syntax var minval = audioparam.minvalue; value a floating-point number indicating the minimum value permitted for the parameter's nominal range. the default value of minvalue is the minimum negative single-precision floating-point value (-340,282,346,638,528,859,811,704,183,484,516,925,440). example const audioctx = new audiocontext(); const gainnode = audioctx.creategain(); console.log(gainnode.gain.minvalue); // -3.4028234663852886e38 specifications specification status comment web audio apithe definition of 'minvalue' in that specification. working draft ...
DeviceProximityEvent.min - Web APIs
the min property provides the minimum distance the sensor can report, in centimeters. syntax var value = instanceofdeviceproximityevent.min; value a positive number indicating the minimum distance, in centimeters (cm), the device's proximity sensor can report. ...
Performance.timing - Web APIs
this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performance.timing read-only property returns a performancetiming object containing latency-related performance information. this property is not available in workers. syntax timinginfo = performance.timing; specifications specification status comment navigation timing level 2 working draft initial definition. ...
PerformanceLongTaskTiming.attribution - Web APIs
specifications specification status comment long tasks api 1the definition of 'attribution' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
PerformanceResourceTiming.connectEnd - Web APIs
candidate recommendation initial definition. ...
PerformanceResourceTiming.connectStart - Web APIs
candidate recommendation initial definition. ...
PerformanceResourceTiming.decodedBodySize - Web APIs
working draft initial definition. ...
PerformanceResourceTiming.domainLookupEnd - Web APIs
candidate recommendation initial definition. ...
PerformanceResourceTiming.domainLookupStart - Web APIs
candidate recommendation initial definition. ...
PerformanceResourceTiming.encodedBodySize - Web APIs
working draft initial definition. ...
PerformanceResourceTiming.fetchStart - Web APIs
candidate recommendation initial definition. ...
PerformanceResourceTiming.nextHopProtocol - Web APIs
working draft initial definition. ...
PerformanceResourceTiming.requestStart - Web APIs
candidate recommendation initial definition. ...
PerformanceResourceTiming.responseEnd - Web APIs
candidate recommendation initial definition. ...
PerformanceResourceTiming.responseStart - Web APIs
candidate recommendation initial definition. ...
PerformanceResourceTiming.secureConnectionStart - Web APIs
candidate recommendation initial definition. ...
PerformanceResourceTiming.transferSize - Web APIs
working draft initial definition. ...
PerformanceServerTiming.description - Web APIs
the description read-only property returns a domstring value of the server-specified metric description, or an empty string. syntax servertiming.description; specifications specification status comment server timingthe definition of 'description' in that specification. working draft initial definition. ...
PerformanceServerTiming.duration - Web APIs
the duration read-only property returns a double that contains the server-specified metric duration, or value 0.0. syntax servertiming.duration; specifications specification status comment server timingthe definition of 'duration' in that specification. working draft initial definition. ...
PerformanceServerTiming.name - Web APIs
the name read-only property returns a domstring value of the server-specified metric name. syntax servertiming.name; specifications specification status comment server timingthe definition of 'name' in that specification. working draft initial definition. ...
PerformanceServerTiming.toJSON - Web APIs
the tojson() method of the performanceservertiming interface returns a domstring that is the json representation of the performanceservertiming object. syntax var json = performanceservertiming.tojson() parameters none. return value a domstring containing json. exceptions none. specifications specification status comment server timingthe definition of 'tojson' in that specification. working draft initial definition. ...
PerformanceTiming.domComplete - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.domcomplete read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, when the parser finished its work on the main document, that is when its document.readystate changes to 'complete' and the corresponding readystatechange event is thrown. syntax time = performancetiming.domcomplete; specifications specification status comment navigation timingthe definition of 'performancetiming.domcomplete' in that specification. recommendation initial definition. ...
PerformanceTiming.domContentLoadedEventEnd - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.domcontentloadedeventend read-only property returns an unsigned long long representing the moment, in milliseconds since the unix epoch, right after all the scripts that need to be executed as soon as possible, in order or not, has been executed. syntax time = performancetiming.domcontentloadedeventend; specifications specification status comment navigation timingthe definition of 'performancetiming.domcontentloadedeventend' in that specification. recommendation initial definition. ...
PerformanceTiming.domContentLoadedEventStart - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.domcontentloadedeventstart read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, right before the parser sent the domcontentloaded event, that is right after all the scripts that need to be executed right after parsing has been executed. syntax time = performancetiming.domcontentloadedeventstart; specifications specification status comment navigation timingthe definition of 'performancetiming.domcontentloadedeventstart' in that specification. recommendation initial definition. ...
PerformanceTiming.domLoading - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.domloading read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, when the parser started its work, that is when its document.readystate changes to 'loading' and the corresponding readystatechange event is thrown. syntax time = performancetiming.domloading; specifications specification status comment navigation timingthe definition of 'performancetiming.domloading' in that specification. recommendation initial definition. ...
PerformanceTiming.domainLookupEnd - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.domainlookupend read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, where the domain lookup is finished. if a persistent connection is used, or the information is stored in a cache or a local resource, the value will be the same as performancetiming.fetchstart. syntax time = performancetiming.domainlookupend; specifications specification status comment navigation timingthe definition of 'performancetiming.domainlookupend' in that specification. recommendation initial definition. ...
PerformanceTiming.domainLookupStart - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.domainlookupstart read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, where the domain lookup starts. if a persistent connection is used, or the information is stored in a cache or a local resource, the value will be the same as performancetiming.fetchstart. syntax time = performancetiming.domainlookupstart; specifications specification status comment navigation timingthe definition of 'performancetiming.domainlookupstart' in that specification. recommendation initial definition. ...
PerformanceTiming.fetchStart - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. 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. this moment is before the check to any application cache. syntax time = performance.timing.fetchstart; specifications specification status comment navigation timingthe definition of 'performancetiming.fetchstart' in that specification. recommendation initial definition. ...
PerformanceTiming.loadEventEnd - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface's performancenavigationtiming.loadeventend read-only property instead. the legacy performancetiming.loadeventend read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, when the load event handler terminated, that is when the load event is completed. if this event has not yet been sent, or is not yet completed, it returns 0. syntax time = performancetiming.loadeventend; specifications specification status comment navigation timingthe definition of 'performancetiming.loadeventend' in that specification. recommendation initial definition. ...
PerformanceTiming.loadEventStart - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface's performancenavigationtiming.loadeventstart read-only property instead.. the legacy performancetiming.loadeventstart read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, when the load event was sent for the current document. if this event has not yet been sent, it returns 0. syntax time = performancetiming.loadeventstart; specifications specification status comment navigation timingthe definition of 'performancetiming.loadeventstart' in that specification. recommendation initial definition. ...
PerformanceTiming.navigationStart - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.navigationstart read-only property returns an unsigned long long representing the moment, in milliseconds since the unix epoch, right after the prompt for unload terminates on the previous document in the same browsing context. if there is no previous document, this value will be the same as performancetiming.fetchstart. syntax time = performancetiming.navigationstart; specifications specification status comment navigation timingthe definition of 'performancetiming.navigationstart' in that specification. recommendation initial definition. ...
PerformanceTiming.redirectEnd - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.redirectend read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, the last http redirect is completed, that is when the last byte of the http response has been received. if there is no redirect, or if one of the redirect is not of the same origin, the value returned is 0. syntax time = performancetiming.redirectend; specifications specification status comment navigation timingthe definition of 'performancetiming.redirectend' in that specification. recommendation initial definition. ...
PerformanceTiming.redirectStart - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.redirectstart read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, the first http redirect starts. if there is no redirect, or if one of the redirect is not of the same origin, the value returned is 0. syntax time = performancetiming.redirectstart; specifications specification status comment navigation timingthe definition of 'performancetiming.redirectstart' in that specification. recommendation initial definition. ...
PerformanceTiming.requestStart - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.requeststart read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, when the browser sent the request to obtain the actual document, from the server or from a cache. if the transport layer fails after the start of the request and the connection is reopened, this property will be set to the time corresponding to the new request. syntax time = performancetiming.requeststart; specifications specification status comment navigation timingthe definition of 'performancetiming.requeststart' in that specification. recommendation ...
PerformanceTiming.responseEnd - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.responseend read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, when the browser received the last byte of the response, or when the connection is closed if this happened first, from the server from a cache or from a local resource. syntax time = performancetiming.responseend; specifications specification status comment navigation timingthe definition of 'performancetiming.responseend' in that specification. recommendation initial definition. ...
PerformanceTiming.responseStart - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.responsestart read-only property returns an unsigned long long representing the moment in time (in milliseconds since the unix epoch) when the browser received the first byte of the response from the server, cache, or local resource. syntax time = performancetiming.responsestart; specifications specification status comment navigation timingthe definition of 'performancetiming.responsestart' in that specification. recommendation initial definition. ...
PerformanceTiming.secureConnectionStart - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.secureconnectionstart read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, where the secure connection handshake starts. if no such connection is requested, it returns 0. syntax time = performancetiming.secureconnectionstart; specifications specification status comment navigation timingthe definition of 'performancetiming.secureconnectionstart' in that specification. recommendation initial definition. ...
PerformanceTiming.unloadEventEnd - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.unloadeventend read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, the unload event handler finishes. if there is no previous document, or if the previous document, or one of the needed redirects, is not of the same origin, the value returned is 0. syntax time = performancetiming.unloadeventend; specifications specification status comment navigation timingthe definition of 'performancetiming.unloadeventend' in that specification. recommendation initial definition. ...
PerformanceTiming.unloadEventStart - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.unloadeventstart read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, the unload event has been thrown. if there is no previous document, or if the previous document, or one of the needed redirects, is not of the same origin, the value returned is 0. syntax time = performancetiming.unloadeventstart; specifications specification status comment navigation timingthe definition of 'performancetiming.unloadeventstart' in that specification. recommendation initial definition. ...
TaskAttributionTiming.containerId - Web APIs
specifications specification status comment long tasks api 1the definition of 'containerid' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. ...
TaskAttributionTiming.containerName - Web APIs
the containername readonly property of the taskattributiontiming interface returns the container's name attribute. a container is the iframe, embed or object etc. that is being implicated, on the whole, for a long task. syntax var containername = taskattributiontiming.containername; value a domstring containing the container's name attribute. specifications specification status comment long tasks api 1the definition of 'containername' in that specification. working draft initial definition. ...
TaskAttributionTiming.containerSrc - Web APIs
the containersrc readonly property of the taskattributiontiming interface returns the container's src attribute. a container is the iframe, embed or object etc. that is being implicated, on the whole, for a long task. syntax var containersrc = taskattributiontiming.containersrc; value a domstring containing the container's src attribute. specifications specification status comment long tasks api 1the definition of 'containersrc' in that specification. working draft initial definition. ...
TaskAttributionTiming.containerType - Web APIs
specifications specification status comment long tasks api 1the definition of 'containertype' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
USBDevice.claimInterface() - Web APIs
the claiminterface() method of the usbdevice interface returns a promise that resolves when the requested interface is claimed for exclusive access. syntax var promise = usbdevice.claiminterface(interfacenumber) parameters interfacenumber the index of one of the interfaces supported by the device. interfaces are device-specific. return value a promise. example the following example shows claiminterface() in the context of connecting to a usb device. async function connectdevice(usbdevice) { await usbdevice.open(); if (usbdevice.configuration === null) await usbdevice.selectconfiguration(1); await usbdevice.claiminterface(0); } specifications specification status comment webusbthe definition of 'claiminterface()' in that specification. dra...
USBDevice.deviceVersionMinor - Web APIs
the deviceversionminor read only property of the usbdevice interface the minor version number of the device in a semantic versioning scheme. syntax var serialnumber = usbdevice.deviceversionminor value a number. specifications specification status comment webusbthe definition of 'deviceversionminor' in that specification. draft initial definition. ...
USBDevice.deviceVersionSubminor - Web APIs
the deviceversionsubminor read only property of the usbdevice interface the patch version number of the device in a semantic versioning scheme. syntax var serialnumber = usbdevice.deviceversionsubminor value a number. specifications specification status comment webusbthe definition of 'deviceversionsubminor' in that specification. draft initial definition. ...
USBDevice.usbVersionMinor - Web APIs
the usbversionminor read only property of the usbdevice interface is one of three properties that declare the usb protocol version supported by the device. the other two properties are usbdevice.usbversionmajor and usbdevice.usbversionsubminor. syntax var serialnumber = usbdevice.usbversionminor value the second of three properties that declare the usb protocol version supported by the device. specifications specification status comment webusbthe definition of 'usbversionminor' in that specification. draft initial definition. ...
USBDevice.usbVersionSubminor - Web APIs
the usbversionsubminor read only property of the usbdevice interface is one of three properties that declare the usb protocol version supported by the device. the other two properties are usbdevice.usbversionmajor and usbdevice.usbversionminor. syntax var serialnumber = usbdevice.usbversionsubminor value the first of three properties that declare the usb protocol version supported by the device. specifications specification status comment webusbthe definition of 'usbversionsubminor' in that specification. draft initial definition. ...
WebGLShaderPrecisionFormat.rangeMin - Web APIs
the read-only webglshaderprecisionformat.rangemin property returns the base 2 log of the absolute value of the minimum value that can be represented. examples var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.getshaderprecisionformat(gl.vertex_shader, gl.medium_float).rangemin; // 127 gl.getshaderprecisionformat(gl.fragment_shader, gl.low_int).rangemin; // 24 specifications specification status comment webgl 1.0the definition of 'webglshaderprecisionformat.rangemin' in that specification. recommendation initial definition. ...
Worker.terminate() - Web APIs
Web › API › Worker › terminate
the terminate() method of the worker interface immediately terminates the worker. this does not offer the worker an opportunity to finish its operations; it is simply stopped at once. syntax myworker.terminate(); parameters none. returns void. example the following code snippet shows creation of a worker object using the worker() constructor, which is then immediately terminated. var myworker = new worker('worker.js'); myworker.terminate(); specifications specification status comment html living standardthe definition of 'worker.terminate()' in that specification. living standard ...
math:min() - EXSLT
Web › EXSLT › math › min
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes math:min() returns the minimum value of a node-set. 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. the minimum value is then the first node in the sorted list, converted into a number. note: syntax math:min(nodeset) parameters nodeset the node-set whose lowest value is to be returned. returns a result tree fragment representing the lowest valued node's numeric value as a string. specifications exslt - math:min browser compatibility supported in gecko 1.9 and later. ...
Meta programming - JavaScript
: 42 } } let p = new proxy({}, handler) p.a = 1 console.log(p.a, p.b) // 1, 42 the proxy object defines a target (an empty object here) and a handler object, in which a get trap is implemented. here, an object that is proxied will not return undefined when getting undefined properties, but will instead return the number 42. additional examples are available on the proxy reference page. terminology the following terms are used when talking about the functionality of proxies. handler placeholder object which contains traps. traps the methods that provide property access. (this is analogous to the concept of traps in operating systems.) target object which the proxy virtualizes. it is often used as storage backend for the proxy. invariants (semantics that remain unchanged) regar...
Date.prototype.getMinutes() - JavaScript
the getminutes() method returns the minutes in the specified date according to local time. syntax dateobj.getminutes() return value an integer number, between 0 and 59, representing the minutes in the given date according to local time. examples using getminutes() the second statement below assigns the value 15 to the variable minutes, based on the value of the date object xmas95. var xmas95 = new date('december 25, 1995 23:15:30'); var minutes = xmas95.getminutes(); console.log(minutes); // 15 specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getminutes' in that specification. ...
Date.prototype.getUTCMinutes() - JavaScript
the getutcminutes() method returns the minutes in the specified date according to universal time. syntax dateobj.getutcminutes() return value an integer number, between 0 and 59, representing the minutes in the given date according to universal time. examples using getutcminutes() the following example assigns the minutes portion of the current time to the variable minutes. var today = new date(); var minutes = today.getutcminutes(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcminutes' in that specification. ...
Transforming XML with XSLT - XSLT: Extensible Stylesheet Language Transformations
s, see eric meyer's css pages. our focus here is on the second type of stylesheet that gecko supports: the xslt stylesheet. xslt stands for extensible stylesheet language/transform and the name is apt. xslt allows a stylesheet author to transform a primary xml document in two significant ways: manipulating and sorting the content, including a wholesale reordering of it if so desired, and transforming the content into a different format (and in the case of firefox, the focus is on converting it on the fly into html which can then be displayed by the browser). xslt/xpath reference elements xsl:apply-imports (supported) xsl:apply-templates (supported) xsl:attribute (supported) xsl:attribute-set (supported) xsl:call-template (supported) xsl:choose (supported) xsl:comment (supported) ...
Index - Web APIs
Web › API › Index
property. the returned string explains the error and should offer suggestions for how to correct it. 32 addresserrors.country api, addresserrors, error, payment request, payment request api, property, reference, validation, country, payment an object based on addresserrors includes a country property if during validation of the address the specified value of country was determined to be invalid. the value is a string describing the error and should offer suggestions for how to correct it. 33 addresserrors.dependentlocality api, addresserrors, error, locality, payment request, payment request api, property, read-only, reference, dependentlocality, payment an object based on addresserrors includes a dependentlocality property when the address's depende...
... 50 ambientlightsen...
...ghtsensor interface of the the sensor apis returns the current light level or illuminance of the ambient light around the hosting device. 49 ambientlightsensor.ambientlightsensor() api, ambient light sensor api, ambientlightsensor, constructor, reference the ambinentlightsensor() constructor creates a new ambientlightsensor object, which returns the current light level or illuminance of the ambient light around the hosting device. 50 ambientlightsensor.illuminance api, ambient light level api, generic sensor api, property, reference, sensor, sensor apis, sensors, illuminance the illuminance property of the ambientlightsensor interface returns the current light level in lux of the ambient light level around the hosting device. 51 analysernod...
...And 320 more matches
Index - Archive of obsolete content
and periodic timers. 63 ui add-on sdk, add-ons, extensions, reference provides access to button, toolbar, and sidebar ui objects. 64 url add-on sdk construct, validate, and parse urls. 66 widget add-on sdk create a simple user interface for an add-on in firefox's add-on bar. 67 windows add-on sdk enumerate and examine open browser windows, open new windows, and listen for window events. 68 low-level apis no summary! 69 /loader create commonjs module loaders. 70 chrome the chrome module gives an add-on sdk add-on access to the components object, which in turn gives it access to a large set of privileged low-level firefox apis. 71 cons...
...use content scripts to interact with web content. 78 core/heritage helper functions for inheritance. 79 core/namespace provides an api for creating namespaces for objects, which effectively may be used for creating fields that are not part of objects public api. 80 core/promise implementation of promises to make asynchronous programming easier. 81 dev/panel enables you to extend the firefox developer tools. 82 event/core the event/core module allows the creation of apis to broadcast and subscribe to events. 83 event/target create objects that broadcast events. 84 frame/hidden-frame creates firefox frames (i.e. xul <iframe> elements) that are...
...ndow add-ons, extensions, needscontent no summary! 203 preferences add-ons, code snippets, extensions, guide, mozilla, preferences no summary! 204 progress listeners add-ons, extensions no summary! 205 queryselector dom no summary! 206 rosetta c, dom, html, htmlscriptelement, javascript, non-javascript, programming languages no summary! 207 running applications add-ons, code snippets, extensions no summary! 208 svg animation needscontent no summary! 209 svg general code snippets no summary! 210 scrollbar code snippets no summary! 211 sidebar add-ons, code snippets, extensions no summary! 21...
...And 78 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
this glossary provides definitions of words and abbreviations you need to know to successfully understand and build for the web. ...
...n http error code meaning "bad gateway". 4 alpn alpn, draft, glossary, needscontent, tls application-layer protocol negotiation (alpn) is a tls extension which indicates what application layer protocol is negotiating the encryped connection without requiring additional round trips. 5 api codingscripting, glossary, infrastructure an api (application programming interface) is a set of features and rules that exist inside a software program (the application) enabling interaction with it through software - as opposed to a human user interface. the api can be seen as a simple contract (the interface) between the application offering it and other items, such as third party software or hardware. 6 aria accessibility, glossary aria (acces...
...l codes into digital form. since 2007, utf-8 superseded it on the web. 9 atag atag, accessibility, authoring tool accessibility guidelines, glossary atag (authoring tool accessibility guidelines) is a w3c recommendation for building accessible-authoring tools that produce accessible contents. 10 abstraction abstraction, coding, codingscripting, glossary, programming language abstraction in computer programming is a way to reduce complexity and allow efficient design and implementation in complex software systems. it hides the technical complexity of systems behind simpler apis. 11 accessibility accessibility, glossary web accessibility (a11y) refers to best practices for keeping a website usable despite physical and technical rest...
...And 63 more matches
Index
api, intermediate, intro, nss, tools a high-level overview to the internals of network security services (nss) software developed by the mozilla.org projects traditionally used its own implementation of security protocols and cryptographic algorithms, originally called netscape security services, nowadays called network security services (nss). ...
... nss offers lots of functionality; we'll walk through the list of modules, design principles, and important relevant standards. ...
... nss offers lots of functionality; we'll walk through the list of modules, design principles, and important relevant standards. ...
...And 50 more matches
Command line crash course - Learn web development
previous overview: understanding client-side tools next in your development process you'll undoubtedly be required to run some command in the terminal (or on the "command line" — these are effectively the same thing). this article provides an introduction to the terminal, the essential commands you'll need to enter into it, how to chain commands together, and how to add your own command line interface (cli) tools. prerequisites: familiarity with the core html, css, and javascript languages. objective: to understand what the terminal/command line is, what basic commands you should learn, and how to install new command line tools. welcome to the terminal the terminal is a text interface for executing text-based programs. if you're running any tooling...
...ls later on in this chapter, and we’ll learn more about package registries in the next chapter. one of the biggest criticisms of the command line is that it lacks hugely in user experience. viewing the command line for the first time can be a daunting experience: a blank screen and a blinking cursor, with very little obvious help available on what to do. ...
...ine for the first time can be a daunting experience: a blank screen and a blinking cursor, with very little obvious help available on what to do. 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! ...
...And 47 more matches
Index
Mozilla › Tech › XPCOM › Index
imple javascript or c++ component (implementing the nsisimple interface). here is how to make the same component in python using pyxpcom. 7 fun with xbl and xpconnect xbl, xpcom, xpcom:language bindings, xpconnect no summary! 8 generating guids add-ons, developing mozilla, developing_mozilla:tools, extensions, tools, xpcom guids 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. add-ons can (and should) be identified with ids of the form extensionname@organization.tld since firefox 1.5. 9 generic factory xpcom most xpcom factories can be ...
... xpcom:language bindings, xpconnect components.interfaces is a read-only object whose properties are interfaces indexed by their names. 23 components.interfacesbyid xpcom:language bindings, xpconnect components.interfacesbyid is a read-only array of classes indexed by iid. 24 components.issuccesscode xpcom, xpcom:language bindings, xpconnect determines whether a given xpcom return code (that is, an nsresult value) indicates the success or failure of an operation, returning true or false respectively. 25 components.lastresult xpcom:language bindings, xpconnect no summary! 26 components.manager xpcom:language bindings, xpconnect components.manager is a convenience reflection of the global native compone...
...nternal knowledge of javascript objects referencing large (trees of) xpcom objects and know when they are no longer reachable. in this case it can be important to be able to force a garbage collection cycle from javascript. 38 components.utils.getglobalforobject add-ons, developing mozilla, extensions, javascript, xpcom:language bindings, xpconnect this method is used to determine the global object with which an object is associated. this is the global object in place at the time the object was created, which is to say the global object used when executing the script that created the object. 39 components.utils.getweakreference xpcom, xpcom:language bindings, xpconnect this method was introduced in firefox 3 and is used for obtaining a weak reference ...
...And 39 more matches
Index - Learn web development
shing, theory it's a lot of work to create a professional website, so if you're new to web development, we encourage you to start small. you won't build another facebook right away, but it's not hard to get your own simple website online, so we'll start there. 37 css basics beginner, css, codingscripting, learn, styling, web, l10n:priority like html, css is not a programming language. it's not a markup language either. css is a style sheet language. css is what you use to selectively style html elements. for example, this css selects paragraph text, setting the color to red: 38 dealing with files beginner, codingscripting, files, guide, html, l10n:priority, theory, website when you are working on a website locally on your computer, you should ke...
...he related files in a single folder that mirrors the published website's file structure on the server. this folder can live anywhere you like, but you should put it somewhere where you can easily find it, maybe on your desktop, in your home folder, or at the root of your hard drive. 39 html basics beginner, codingscripting, html, learn, web, l10n:priority html is not a programming language; it is a markup language that defines the structure of your content. html consists of a series of elements, which you use to enclose, or wrap, different parts of the content to make it appear a certain way, or act a certain way. the enclosing tags can make a word or image hyperlink to somewhere else, can italicize words, can make the font bigger or smaller, and so on. for example, take...
...you'll really start to benefit from understanding what's happening in the background. 41 installing basic software beginner, browser, learn, setup, tools, webmechanics, l10n:priority, text editor that looks like a scary list, but fortunately, you can get started in web development without knowing anything about most of these. in this article, we'll just set you up with a bare minimum — a text editor and some modern web browsers. 42 javascript basics beginner, codingscripting, javascript, learn, web, l10n:priority javascript ("js" for short) is a full-fledged dynamic programming language that can add interactivity to a website. it was invented by brendan eich (co-founder of the mozilla project), the mozilla foundation, and the mozilla corporation. ...
...And 32 more matches
Index
y js::deflatestringtoutf8buffer 18 boolean_to_jsval jsapi reference, obsolete, spidermonkey boolean_to_jsval converts a bool argument, b, to a boolean jsval. 19 double_to_jsval jsapi reference, obsolete, spidermonkey double_to_jsval is the inverse of js::tonumber. 20 int_fits_in_jsval jsapi reference, obsolete, spidermonkey determines if a specified c integer value, i, lies within the range allowed for integer jsvals. if so, int_fits_in_jsval returns true, and i can be cast to jsval by calling int_to_jsval(i). otherwise, int_fits_in_jsval returns false. in this case, the application can still convert i to a jsval using js_newnumbervalue. 21 int_to_jsval jsapi reference, obsolete, spidermonkey int_to_jsva...
...chain. 38 js::deflatestringtoutf8buffer jsapi reference, refere, spidermonkey js::deflatestringtoutf8buffer encodes src as utf8. the caller must either ensure dst has enough space to encode the entire string, or pass the length of the buffer as dstlenp. in which case, the function will encode characters from the string until the buffer is exhausted. does not write the null terminator. 39 js::doublenanvalue jsapi reference, reference, référence(2), spidermonkey js::doublenanvalue returns a value of type js::value that represents an ieee floating-point quiet not-a-number (nan). 40 js::doublevalue jsapi reference, reference, référence(2), spidermonkey js::doublevalue converts a c floating-point number of type double to js::value,...
...nce(2), spidermonkey js::float32value converts a c floating-point number of type float to js::value, the type of javascript values. 44 js::getdeflatedutf8stringlength jsapi reference, reference, référence(2), spidermonkey js::getdeflatedutf8stringlength returns the length of the char buffer required to encode s as utf8. the returned length does not include the null-terminator. 45 js::getfirstargumentastypehint jsapi reference, reference, référence(2), spidermonkey js::getfirstargumentastypehint converts first argument of @@toprimitive method to jstype. 46 js::getselfhostedfunction jsapi reference, reference, référence(2), spidermonkey js::getselfhostedfunction creates a new javascript function implemented in self-hoste...
...And 30 more matches
Using CSS transitions - CSS: Cascading Style Sheets
between two states are often called implicit transitions as the states in between the start and final states are implicitly defined by the browser. css transitions let you decide which properties to animate (by listing them explicitly), when the animation will start (by setting a delay), how long the transition will last (by setting a duration), and how the transition will run (by defining a timing function, e.g. linearly or quick at the beginning, slow at the end). which css properties can be transitioned? the web author can define which property has to be animated and in which way. this allows the creation of complex transitions. as it doesn't make sense to animate some properties, the list of animatable properties is limited to a finite set. note: the set of properties that can be an...
...class="box">lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position:absolute; -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color; -webkit-transition-duration: 0.5s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration: 0.5s; transition-timing-function: ease-in-out; } .box1{ transform: rotate(270deg); -webkit-transform: rotate(270deg); width: 50px; height: 50px; background-color: blue; color: yellow; font-size: 18px; left...
...orm: rotate(270deg); -webkit-transform: rotate(270deg); width: 50px; height: 50px; background-color: blue; color: yellow; font-size: 18px; left: 150px; top: 25px; position: absolute; -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color; -webkit-transition-duration: 0.5s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transformv color; transition-duration: 0.5s; transition-timing-function: ease-in-out; } function updatetransition() { var el = document.queryselector("div.box"); if (el) { el.classname = "box1"; } else { el = document.queryselector("div.box1"); el.class...
...And 29 more matches
sslfnc.html
s the function returns one of these values: if successful, secsuccess. if unsuccessful, secfailure. use pr_geterror to retrieve the error code. description nss_init opens the certn.db, keyn.db, and secmod.db files (wheren is a numeric digit) in the specified directory. nss_init isnot idempotent, so call it only once. nss_init opens the database files read-only. if you are performing operations that require write permission, for example s/mime operations such as adding a certificate, use nss_initreadwrite instead. before calling nss_init, your program must call pr_init. the policy flags for all cipher suites are turned off by default, disallowing all cipher suites. therefore, an application cannot use nss to perform any cryptographic operations until after it enables app...
...if successful, secsuccess. if unsuccessful, secfailure. use pr_geterror to retrieve the error code. description nss_initreadwrite opens the certn.db, keyn.db, and secmod.db files (wheren is a numeric digit) with both read and write permission in the specified directory. nss_initreadwrite isnot idempotent, so call it only once. use nss_initreadwrite rather than nss_init if you are performing operations that require write permission, such as some s/mime operations. before calling nss_initreadwrite, your program must call pr_init. the policy flags for all cipher suites are turned off by default, disallowing all cipher suites. therefore, an application cannot use nss to perform any cryptographic operations until after it enables appropriate cipher suites by calling one of the ssl e...
...ion and will not have certificate-based authentication, tamper detection, or encryption. ssl_request_certificate is a server option that requests a client to authenticate itself. ssl_require_certificate is a server option that requires a client to authenticate itself (only if ssl_request_certificate is also on). if client does not provide certificate, the connection terminates. default state is a third state similar to on, that provides backward compatibility with older netscape server products. ssl_handshake_as_client controls the behavior of pr_accept,. if this option is off, the pr_accept configures the ssl socket to handshake as a server. if it is on, then pr_accept configures the ssl socket to handshake as a client, even though it accepted the con...
...And 28 more matches
<input type="time"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › time
<input> elements of type time create input fields designed to let the user easily enter a time (hours and minutes, and optionally seconds). the control's user interface will vary from browser to browser. support is good in modern browsers, with safari being the sole major browser not yet implementing it; in safari, and any other browsers that don't support <time>, it degrades gracefully to <input type="text">. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...on't support <time>, it degrades gracefully to <input type="text">. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. appearance chrome and opera in chrome/opera the time control is simple, with slots to enter hours and minutes in 12 or 24-hour format depending on operating system locale, and up and down arrows to increment and decrement the currently selected component. in some versions, an "x" button is provided to clear the control's value. 12-hour 24-hour chrome 83 in chrome 83, the ui controls have been updated with a new look and feel. the new element is functionally identical to the old one, but has a s...
...d one, but has a similar ui to edge. 24-hour firefox firefox's time control is very similar to chrome's, except that it doesn't have the up and down arrows. it also uses a 12- or 24-hour format for inputting times, based on system locale. an "x" button is provided to clear the control's value. 12-hour 24-hour edge the edge time control is somewhat more elaborate, opening up an hour and minute picker with sliding reels. it, like chrome, uses a 12- or 24-hour format for inputting times, based on system locale: 12-hour 24-hour value a domstring representing a time, or empty. events change and input supported common attributes autocomplete, list, readonly, and step idl attributes value, valueasdate, valueasnumber, and list. ...
...And 27 more matches
WindowOrWorkerGlobalScope.setInterval() - Web APIs
heets.push(new sheet(aitems[nitem])); /* uncomment the following line if you have previously hidden your elements via css: */ // aitems[nitem].style.visibility = "visible"; } bstart = false; } nintervid = setinterval(typewrite, this.rate); btyping = true; }; this.pause = function () { clearinterval(nintervid); btyping = false; }; this.terminate = function () { ocurrent.nodevalue += spart; spart = ""; for (nidx; nidx < asheets.length; scroll(asheets[nidx++], 0, false)); clean(); }; } /* usage: */ var otwexample1 = new typewriter(/* elements: */ '#article, h1, #info, #copyleft', /* frame rate (optional): */ 15); /* default frame rate is 100: */ var otwexample2 = new typewriter('#controls'); /* you can also change t...
...proin ac ante a felis ornare vehicula. fusce pellentesque lacus vitae eros convallis ut mollis magna pellentesque. pellentesque placerat enim at lacus ultricies vitae facilisis nisi fringilla. in tincidunt tincidunt tincidunt. </div> <h1>javascript typewriter</h1> <div id="arti...
...proin ac ante a felis ornare vehicula. fusce pellentesque lacus vitae eros convallis ut mollis magna pellentesque. pellentesque placerat enim at lacus ultricies vitae facilisis nisi fringilla. in tincidunt tincidunt tincidunt. </div> <h1>javascript typewriter</h1> <div id="article"> <p>lorem...
...And 26 more matches
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
Web › HTML › Element › input
e. <input type="password" name="password"/> radio a radio button, allowing a single value to be selected out of multiple choices with the same name value. <input type="radio" name="radio"/> range a control for entering a number whose exact value is not important. displays as a range widget defaulting to the middle value. used in conjunction min and max to define the range of acceptable values. <input type="range" name="range" min="0" max="25"/> html5 reset a button that resets the contents of the form to default values. not recommended. <input type="reset" name="reset"/> search a single-line text field for entering search strings. line-breaks are automatically removed from the inpu...
...and relevant keyboard in supporting browsers and devices with dynamic keyboards. <input type="url" name="url"/> html5 week a control for entering a date consisting of a week-year number and a week number with no time zone. <input type="week" name="week"/> html5 obsolete values datetime a control for entering a date and time (hour, minute, second, and fraction of a second) based on utc time zone. <input type="datetime" name="datetime"/> html5 attributes the <input> element is so powerful because of its attributes; the type attribute, described with examples above, being the most important. since every <input> element, regardless of type, is based on the htmlinputelement interface, they technically share t...
...whether to allow multiple values name all name of the form control. submitted with the form as part of a name/value pair. pattern password, text, tel pattern the value must match to be ...
...And 26 more matches
Web audio codec guide - Web media technologies
the processing of audio data to encode and decode it is handled by an audio codec (coder/decoder). in this article, we look at audio codecs used on the web to compress and decompress audio, what their capabilities and use cases are, and offer guidance when choosing audio codecs to use for your content. ...
... encoded audio there are two general categories of factors that affect the encoded audio which is output by an audio codec's encoder: details about the source audio's format and contents, and the codec and its configuration during the encoding process. for each factor that affects the encoded audio, there is a simple rule that is nearly always true: because the fidelity of digital audio is determined by the granularity and precision of the samples taken to convert it into a data stream, the more data used to represent the digital version of the audio, the more closely the sampled sound will match the source material. the effect of source audio format on encoded audio output because encoded audio inherently uses fewer bits to represent each sample, the source audio format may actually have...
...nformation out of imperfect or noisy audio. they strip away audio frequencies that aren't used much, tolerate loss of precision in the decoded output, and use other methods to lose audio content, quality, and fidelity to produce smaller encoded media. upon decoding, the output is, to varying degrees, still understandable. the specific codec used—and the compression configuration selected—determine how close to the original, uncompressed audio signal the output seems to be when heard by the human ear. because of the differences in how lossy codecs work compared to lossless ones, especially the fact that lossless ones have to be much more conservative with their compression, lossy codecs nearly always result in significantly smaller compressed audio than lossless codecs do. generally spea...
...And 24 more matches
<input type="datetime-local"> - HTML: Hypertext Markup Language
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...pera and edge on desktop and most modern versions of mobile browsers having usable implementations. in other browsers, these degrade gracefully to simple <input type="text"> controls. the control is intended to simply represent a local date and time, not necessarily the user's local date and time. in other words, an implementation should allow any valid combination of year, month, day, hour, and minute - even if such a combination is invalid in the user's local time zone (such as times within a daylight saving time spring-forward transition gap). some mobile browsers (particularly on ios) do not currently implement this correctly. because of the limited browser support for datetime-local, and the variations in how the inputs work, it may currently still be best to use a framework or library...
... one thing to note is that the displayed date and time formats differ from the actual value; the displayed date and time are formatted according to the user's locale as reported by their operating system, whereas the date/time value is always formatted yyyy-mm-ddthh:mm. when the above value submitted to the server, for example, it will look like partydate=2017-06-01t08:30. note: also bear in mind that if such data is submitted via http get, the colon character will need to be escaped for inclusion in the url parameters, e.g. partydate=2017-06-01t08%3a30. see encodeuri() for one way to do this. 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"]'); datecontro...
...And 22 more matches
Web Replay
ewinding when disabled, firefox records a page signifcantly faster. default true. devtools.recordreplay.fastlogpoints when enabled, firefox web replay evaluates logpoints consecutively. logpoints cannot have side-effects or diverge from the recording in any othe way in this mode. default false. devtools.recordreplay.logging when enabled, firefox will log web replay's internal actions to the terminal, which is helpful when debugging hangs and crashes. default false architecture there are several main components to the project: the record/replay infrastructure records enough information during recording so that the replayed process can run and produce the same observable behaviors. ipc integration allows a replaying process to communicate with the chrome process using ipdl and shared ...
...e still maintaining communication with the chrome process. debugger integration allows the js debugger to read the information it needs from a replaying process and control the process's execution (resume/rewind). the debugger is not allowed to change the replaying process's observable state. record/replay infrastructure broadly, reliable record/replay is achieved by controlling for non-determinism in the browser. this non-determinism originates from two sources: intra-thread and inter-thread. intra-thread non-deterministic behaviors are non-deterministic even in the absence of actions by other threads, and inter-thread non-deterministic behaviors are those affected by interleaving execution with other threads, and which always behave the same given the same interleaving. intra-thread...
... browser. this non-determinism originates from two sources: intra-thread and inter-thread. intra-thread non-deterministic behaviors are non-deterministic even in the absence of actions by other threads, and inter-thread non-deterministic behaviors are those affected by interleaving execution with other threads, and which always behave the same given the same interleaving. intra-thread non-determinism is recorded and later replayed for each thread. these behaviors mainly originate from system calls (i/o and such). inter-thread non-determinism is handled by first assuming the program is data race free: shared memory accesses which would otherwise race are either protected by locks or use apis that perform atomic operations. if we record and later replay the order in which threads acquire ...
...And 21 more matches
Mozilla internal string guide
uffer of characters. the 8-bit and 16-bit string classes have completely separate base classes, but share the same apis. as a result, you cannot assign a 8-bit string to a 16-bit string without some kind of conversion helper class or routine. for the purpose of this document, we will refer to the 16-bit string classes in class documentation. ...
...nsa[c]string is the base of the string classes (since it imposes fewer requirements) and ns[c]string is a class derived from it. ...
...convention for wide and narrow string classes wide narrow nsastring nsacstring nsstring nscstring nsautostring nsautocstring etc... the string classes distinguish, as part of the type hierarchy, between strings that must have a null-terminator at the end of their buffer (ns[c]string) and strings that are not required to have a null-terminator (nsa[c]string). nsa[c]string is the base of the string classes (since it imposes fewer requirements) and ns[c]string is a class derived from it. functions taking strings as parameters should generally take one of these four types. in order to avoid unnecessary copying of string data (which can have significant performance cost), the string classes support different ownership models. all stri...
...And 18 more matches
3D collision detection - Game development
this article provides an introduction to the different bounding volume techniques used to implement collision detection in 3d environments. followup articles will cover implementations in specific 3d libraries. axis-aligned bounding boxes as with 2d collision detection, axis-aligned bounding boxes (aabb) are the quickest algorithm to determine whether the two game entities are overlapping or not. this consists of wrapping game entities in a non-rotated (thus axis-aligned) box and checking the positions of these boxes in the 3d coordinate space to see if they are overlapping. the axis-aligned constraint is there because of performance reasons. the overlapping area between two non-rotated boxes can be checked with logical comparisons alone, whereas rotated boxes require additional trigo...
...t the entity contained inside. note: check out the bounding volumes with three.js article to see a practical implementation of this technique. point vs. aabb checking if a point is inside an aabb is pretty simple — we just need to check whether the point's coordinates fall inside the aabb; considering each axis separately. ...
...ntained inside. note: check out the bounding volumes with three.js article to see a practical implementation of this technique. point vs. aabb checking if a point is inside an aabb is pretty simple — we just need to check whether the point's coordinates fall inside the aabb; considering each axis separately. ...
...And 17 more matches
MathML Accessibility in Mozilla
hml windows mac linux accessfu diagonal of a regular pentagon video video video / x+2 __________ x plus 2 __________ x+2 x plus 2 x + y ab __________ a over b __________ fraction start, a over b, end of fraction fraction start. a over b. fraction end. a numerator b denominator fraction ab\frac a b ab __________ a over b __________ fraction start, a over b, end of fraction. see webkit's bug 146454 fraction without bar, start. a over b. fraction end. a numerator b denominator fraction without bar ab __________ a sub b __________ a, subscript b a. ...
... root of a __________ 3 + 4 root of a, end of root 3 plus 4 root of a. root end. a base 3+4 root index root a34 __________ the 3 over 4 root of a __________ fraction start, 3 over 4, end of fraction root of a, end of root fraction start. 3 over 4. fraction end. root of a. root end. a base 3 numerator 4 denominator root-index fraction ab __________ the the square root of b root of a __________ square root of b, end of root root of a, end of root square root of b. root end. root of a. root end. a base b square root root-index root ab __________ the square root of the quantity a over b end root __________...
... root of a, end of root square root of b. root end. root of a. root end. a base b square root root-index root ab __________ the square root of the quantity a over b end root __________ square root of fraction start, a over b, end of fraction, end of root square root of fraction start. a over b. fraction end. root end. ...
...And 17 more matches
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
fect negotiation is that the same code is used for both the caller and the callee, so there's no repetition or otherwise added levels of negotiation code to write. perfect negotiation works by assigning each of the two peers a role to play in the negotiation process that's entirely separate from the webrtc connection state: a polite peer, which uses ice rollback to prevent collisions with incoming offers. a polite peer, essentially, is one which may send out offers, but then responds if an offer arrives from the other peer with "okay, never mind, drop my offer and i'll consider yours instead." an impolite peer, which always ignores incoming offers that collide with its own offers. it never apologizes or gives up anything to the polite peer. any time a collision occurs, the impolite peer ...
...stead." an impolite peer, which always ignores incoming offers that collide with its own offers. it never apologizes or gives up anything to the polite peer. any time a collision occurs, the impolite peer wins. this way, both peers know exactly what should happen if there are collisions between offers that have been sent. responses to error conditions become far more predictable. how you determine which peer is polite and which is impolite is generally up to you. it could be as simple as assigning the polite role to the first peer to connect to the signaling server, or you could do something more elaborate like having the peers exchange random numbers and assigning the polite role to the winner. ...
...s to error conditions become far more predictable. how you determine which peer is polite and which is impolite is generally up to you. it could be as simple as assigning the polite role to the first peer to connect to the signaling server, or you could do something more elaborate like having the peers exchange random numbers and assigning the polite role to the winner. however you make the determination, once these roles are assigned to the two peers, they can then work together to manage signaling in a way that doesn't deadlock and doesn't require a lot of extra code to manage. an important thing to keep in mind is this: the roles of caller and callee can switch during perfect negotiation. if the polite peer is the caller and it sends an offer but there's a collision with the impolite pee...
...And 17 more matches
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
e scene. there are a few articles about the fundamental math, geometry, and other concepts behind webgl and webxr which may be useful to read before or while reading this one, including: explaining basic 3d theory matrix math for the web webgl model view projection geometry and reference spaces in webxr ed. note: most diagrams used in this article to show how the camera moves while performing standard movements was taken from an article on the filmmakeriq web site; namely, from this image which is found all over the web, however, and though we assume these are under a permissive license due to their frequent reuse, ownership is not certain. we hope that it's freely usable; if not, and you're the owner, please let us know and we'll find or produce new diagrams. or, if you're happy to ...
... the camera or by moving everything around the camera. and that's our solution. since we can't move the camera, we move the world around it. our renderer needs to know where we imagine the camera to be, then alter the position of every visible object to simulate that position and orientation. thus, instead of referring to an actual camera object, the term camera is used in webgl and webxr programming to refer to an object describing the position and viewing direction of a hypothetical viewer of the scene, whether there's an actual object present in 3d space or not. points of view since the camera is a virtual object which, rather than necessarily representing a physical object in the virtual world, represents a viewer's position and viewing direction, it's useful to think about the kinds o...
...nd viewing direction of a hypothetical viewer of the scene, whether there's an actual object present in 3d space or not. points of view since the camera is a virtual object which, rather than necessarily representing a physical object in the virtual world, represents a viewer's position and viewing direction, it's useful to think about the kinds of situation that call for the use of a camera. ...
...And 17 more matches
<input type="range"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › range
mdn/interactive-examples and send us a pull request. if the user's browser doesn't support type range, it will fall back and treat it as a text input. value a domstring containing the string representation of the selected numeric value; use valueasnumber to get the value as a number. ...
... list, value, and valueasnumber methods stepdown() and stepup() validation there is no pattern validation available; however, the following forms of automatic validation are performed: if the value is set to something which can't be converted into a valid floating-point number, validation fails because the input is suffering from a bad input. the value won't be less than min. ...
...uffering from a bad input. the value won't be less than min. the default is 0. the value won't be greater than max. the default is 100. the value will be a multiple of step. the default is 1. value the value attribute contains a domstring which contains a string representation of the selected number. the value is never an empty string (""). the default value is halfway between the specified minimum and maximum—unless the maximum is actually less than the minimum, in which case the default is set to the value of the min attribute. ...
...And 17 more matches
Introduction to SSL - Archive of obsolete content
dshake the new internet engineering task force (ietf) standard protocol called transport layer security (tls) is based on ssl. the details of the protocol are available in request for comments (rfc): 2246,the tls protocol version 1.0. some red hat products already support tls. most other red hat products plan to support the protocol in future versions. this document is primarily intended for administrators of red hat server products, but the information it contains may also be useful for developers of applications that support ssl. the document assumes that you are familiar with the basic concepts of public-key cryptography, as summarized in "introduction to public-key cryptography." the ssl protocol the transmission control protocol/internet protocol (tcp/ip) governs the transport and r...
...ll information sent between a client and a server to be encrypted by the sending software and decrypted by the receiving software, thus providing a high degree of confidentiality. confidentiality is important for both parties to any private transaction. in addition, all data sent over an encrypted ssl connection is protected with a mechanism for detecting tampering-that is, for automatically determining whether the data has been altered in transit. the ssl protocol includes two sub-protocols: the ssl record protocol and the ssl handshake protocol. the ssl record protocol defines the format used to transmit data. 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 ...
...client to each other, transmitting certificates, and establishing session keys. clients and servers may support different cipher suites, or sets of ciphers, depending on factors such as the version of ssl they support, company policies regarding acceptable encryption strength, and government restrictions on export of ssl-enabled software. among its other functions, the ssl handshake protocol determines how the server and client negotiate which cipher suites they will use to authenticate each other, to transmit certificates, and to establish session keys. key-exchange algorithms like kea and rsa key exchange govern the way in which the server and client determine the symmetric keys they will both use during an ssl session. the most commonly used ssl cipher suites use rsa key exchange. the ss...
...And 16 more matches
UI pseudo-classes - Learn web development
n-range and :out-of-range: target form controls that are valid/invalid according to form validation constraints set on them, or in-range/out-of-range. :enabled and :disabled, and :read-only and :read-write: target enabled or disabled form controls (e.g. with the disabled html attribute set), and read-write or read-only form controls (e.g. with the readonly html attribute set). :checked, :indeterminate, and :default: respectively target checkboxes and radio buttons that are checked, in an indeterminate state (neither checked or not checked), and the default selected option when the page loads (e.g. an <input type="checkbox"> with the checked attribute set, or an <option> element with the selected attribute set). there are many others too, but the ones listed above are the most obviously us...
...really important, fundamental concept in form validation is whether a form control's data is valid or not (in the case of numerical data, we can also talk about in-range and out-of-range data). form controls with constraint limitations can be targeted based on these states. :valid and :invalid you can target from control using the :valid and :invalid pseudo-classes. some points worth bearing in mind: controls with no constraint validation will always be valid, and therefore matched with :valid. controls with required set on them that have no value are counted as invalid — they will be matched with :invalid and :required. controls with built-in validation, such as <input type="email"> or <input type="url"> are (matched with) :invalid when the data entered into them does not match the ...
... that have no value are counted as invalid — they will be matched with :invalid and :required. controls with built-in validation, such as <input type="email"> or <input type="url"> are (matched with) :invalid when the data entered into them does not match the pattern they are looking for (but they are valid when empty). controls whose current value is outside the range limits specified by the min and max attributes are (matched with) :invalid, but also matched by :out-of-range, as you'll see later on. there are some other ways to make an element matched by :valid/:invalid, as you'll see in the client-side form validation article. but we'll keep things simple for now. let's go in and look at a simple example of :valid/:invalid (see valid-invalid.html for the live version, and also check...
...And 16 more matches
Inputs and input sources - Web APIs
t just about showing the user a wholly virtual scene or augmenting reality by adding to or altering the world around them. in order to make an experience that's fulfilling and engaging, the user needs to be able to interact with it. to that end, webxr provides support for a variety of kinds of input devices. in this guide, we'll look at how to use webxr's input device management features to determine what input sources are available and how to then monitor those sources for inputs in order to handle user interactivity with your virtual or augmented environment. inputs in webxr fundamentally, inputs in webxr fall into two basic categories: targeting and actions. targeting is the specification of a point in space by the user's input. this may involve the user simply tapping on a spot on the ...
...o be set to none if the controller isn't hand-held, or if it's unknown which hand the controller is in. handedness can be used for various things, including selecting an appropriate mesh to use to represent the controller in the view and to help present it in the correct hand if drawing hands on the display. ...
... your app uses the notion of "main hand" and "off hand" for determining the functionality of a controller; in a game, for example, the main hand controller may be the player's weapon while the off hand controller might be used to control the positioning of a shield. targeting ray mode the targeting ray mode is a string found in the targetraymode property. it describes the technique used to determine the targeting ray and how it should be shown to the user if presented visually. when the targeting ray mode is gaze, the ray's origin is at the viewer and simply aims in the direction the user is facing. ...
...And 16 more matches
Index - Archive of obsolete content
Archive › Mozilla › XUL › Index
76 control xul attributes, xul reference no summary! 77 crop xul attributes, xul reference no summary! 78 curpos xul attributes, xul reference no summary! 79 current xul attributes, xul reference no summary! 80 currentset needshelp, xul attributes, xul reference no summary! 81 customindex xul attributes, xul reference no summary! 82 customizable xul attributes, xul reference no summary! 83 cycler xul attributes, xul reference no summary! 84 datasources xul attributes, xul reference no summary! 85 datepicker.type xul attributes, xul reference no summary! 86 datepicker.value ...
... summary! 190 menuactive xul attributes, xul reference no summary! 191 menuitem.key xul attributes, xul reference no summary! 192 menuitem.name xul attributes, xul reference no summary! 193 menuitem.type xul attributes, xul reference more information on adding checkmarks to menus in the xul tutorial 194 min xul attributes, xul reference no summary! 195 minheight xul attributes, xul reference no summary! 196 minresultsforpopup xul attributes, xul reference no summary! 197 minwidth xul attributes, xul reference no summary! 198 mode no summary! 199 modifiers xul attributes, xul reference ...
... 367 textbox.disablehistory xul attributes, xul reference no summary! 368 textbox.empty xul attributes, xul reference no summary! 369 textbox.forcecomplete no summary! 370 textbox.ignoreblurwhilesearching no summary! 371 textbox.label xul attributes, xul reference no summary! 372 textbox.min xul, xul attribute, xul reference no summary! 373 textbox.minresultsforpopup no summary! 374 textbox.onblur xul, xul attributes, xul reference no summary! 375 textbox.onchange xul attributes, xul reference no summary! 376 textbox.onfocus xul, xul attributes, xul reference no summary! 377 text...
...And 15 more matches
Introduction to Public-Key Cryptography - Archive of obsolete content
crypts, or unscrambles, the information after receiving it. while in transit, the encrypted information is unintelligible to an intruder. tamper detection allows the recipient of information to verify that it has not been modified in transit. any attempt to modify data or substitute a false message for a legitimate one will be detected. authentication allows the recipient of information to determine its origin-that is, to confirm the sender's identity. nonrepudiation prevents the sender of information from claiming at a later date that the information was never sent. the sections that follow introduce the concepts of public-key cryptography that underlie these capabilities. certificates and authentication managing certificates certificates and authentication a certificate identi...
... digital signature of the issuing ca. the ca's digital signature allows the certificate to function as a "letter of introduction" for users who know and trust the ca but don't know the entity identified by the certificate. for more information about the role of cas, see "how ca certificates are used to establish trust". authentication confirms an identity authentication is the process of confirming an identity. in the context of network interactions, authentication involves the confident identification of one party by another party. authentication over networks can take many forms. certificates are one way of supporting authentication. network interactions typically take place between a client, such as browser software running on a personal computer, and a server, such as the software and...
...r must supply a name and password separately for each new server the user wishes to use during a work session. the client sends the name and password across the network, either in the clear or over an encrypted ssl connection. the server looks up the name and password in its local password database and, if they match, accepts them as evidence authenticating the user's identity. the server determines whether the identified user is permitted to access the requested resource, and if so allows the client to access it. with this arrangement, the user must supply a new password for each server, and the administrator must keep track of the name and password for each user, typically on separate servers. proper implementation does not store passwords in plaintext. instead it concatenates the pas...
...And 15 more matches
Working with data
pe is an array type of unspecified length, the following steps are taken: if the value is a size value, a new array of that length is created, with its cells ready to accept values of the same type as those in the specified array. this is the same as new arraytype(type.elementtype, value). if the type represents a javascript string (that is, an array of jschar characters followed by a null terminator), a copy of that string is created and returned. if the type is an array of 8-bit characters and value is a utf-16 string, the new cdata object is the result of converting the utf-16 string to utf-8, with a null terminator. if the value is a javascript array object and it has a non-negative length, a new array is created and the contents of the array specified by value are converted to cdat...
...see wrong ways of casting, and explanation on why this is the right way to cast an array (explained by matching constructor's) see here: githubgist :: _ff-addon-tutorial-jsctypes_castingarrays data and pointers a cdata object represents a c value in memory. you can always get a pointer to the c value using the cdata object's address() method. objects can share memory it's important to keep in mind that two (or more) cdata objects can share the same memory block for their contents. this will happen, for example, when type casting. this is called aliasing. the shared memory can be whole or in part. for example: const point = new ctypes.structtype("point", [{x: ctypes.int32_t}, {y: ctypes.int32_t}]); const rect = new ctypes.structtype("rect", [{topleft: point}, {bottomright: point}]); var...
... in particular, comparing two different objects that are represented under-the-hood as javascript objects using the == or === operators will always return false. this affects comparisons of pointers, integers that are the same size as pointers, and 64-bit integers. you can work around this by serializing these values using the tostring() method and comparing using the resulting string. see determining if two pointers are equal for an example of how this works when comparing pointers. example: checking the value of an integer if, for example, you need to see if the value of an integer is 5, you can do so like this: var t = ctypes.int32_t(5); if (t.tostring() == "ctypes.int32_t(5)") { // it's 5 } working with strings c functions expect strings to be arrays of characters, with the end...
...And 15 more matches
Index - Firefox Developer Tools
found 158 pages: # page tags and summary 1 firefox developer tools developing mozilla, guide, tools, web development, web development:tools, l10n:priority firefox developer tools is a set of web developer tools built into firefox. you can use them to examine, edit, and debug html, css, and javascript. 2 3d view html, tools, web development, web development:tools when you click on the 3d view button, the page goes into 3d view mode; in this mode, you can see your page presented in a 3d view in which nested blocks of html are increasingly "tall," projecting outward from the bottom of the page. this view makes it easy to visualize the nesting of your content. 3 accessibility inspector accessibility, accessibility in...
...iew:": 39 basic operations before firefox 50, the memory tool is not enabled by default. to enable it, open the developer tool settings, and check the "memory" box under "default firefox developer tools": 40 dom allocation example this article describes a very simple web page that we'll use to illustrate some features of the memory tool. ...
...this is useful for understanding the "retained size" of objects allocated by your site: that is, the size of the objects themselves plus the size of the objects that they keep alive through references. ...
...And 15 more matches
Box-shadow generator - CSS: Cascading Style Sheets
<div class="ui-checkbox" data-topic='inset'></div> </div> <div class="slidergroup"> <div class="ui-slider-name"> position x </div> <div class="ui-slider-btn-set" data-topic="posx" data-type="sub"></div> <div class="ui-slider" data-topic="posx" data-min="-500" data-max="500" data-step="1"> </div> <div class="ui-slider-btn-set" data-topic="posx" data-type="add"></div> <div class="ui-slider-input" data-topic="posx" data-unit="px"></div> </div> <div class="slidergroup"> <div class="ui-slider-name"> position y </div> ...
...ass="ui-slider-input" data-topic="posx" data-unit="px"></div> </div> <div class="slidergroup"> <div class="ui-slider-name"> position y </div> <div class="ui-slider-btn-set" data-topic="posy" data-type="sub"></div> <div class="ui-slider" data-topic="posy" data-min="-500" data-max="500" data-step="1"> </div> <div class="ui-slider-btn-set" data-topic="posy" data-type="add"></div> <div class="ui-slider-input" data-topic="posy" data-unit="px"></div> </div> <div class="slidergroup"> <div class="ui-slider-name"> blur </div> <div...
...div class="ui-slider-input" data-topic="posy" data-unit="px"></div> </div> <div class="slidergroup"> <div class="ui-slider-name"> blur </div> <div class="ui-slider-btn-set" data-topic="blur" data-type="sub"></div> <div class="ui-slider" data-topic="blur" data-min="0" data-max="200" data-step="1"> </div> <div class="ui-slider-btn-set" data-topic="blur" data-type="add"></div> <div class="ui-slider-input" data-topic="blur" data-unit="px"></div> </div> <div class="slidergroup"> <div class="ui-slider-name"> spread </div> <div ...
...And 15 more matches
Numbers and dates - JavaScript
x123456789abcdef // 81985529216486900 0xa // 10 exponentiation 1e3 // 1000 2e6 // 2000000 0.1e2 // 10 number object the built-in number object has properties for numerical constants, such as maximum value, not-a-number, and infinity. you cannot change the values of these properties and you use them as follows: var biggestnum = number.max_value; var smallestnum = number.min_value; var infinitenum = number.positive_infinity; var neginfinitenum = number.negative_infinity; var notanum = number.nan; you always refer to a property of the predefined number object as shown above, and not as a property of a number object you create yourself. the following table summarizes the number object's properties. properties of number property description ...
... var notanum = number.nan; you always refer to a property of the predefined number object as shown above, and not as a property of a number object you create yourself. the following table summarizes the number object's properties. ...
... same as the global parsefloat() function. ...
...And 15 more matches
SVG documentation index - SVG: Scalable Vector Graphics
Web › SVG › Index
e direction angle for the light source on the xy plane (clockwise), in degrees from the x axis. 30 basefrequency filters, svg, svg attribute the basefrequency attribute represents the base frequency parameter for the noise function of the <feturbulence> filter primitive. ...
...the shifted object might be a sub- or superscript. 33 bbox deprecated, svg, svg attribute the bbox attribute defines the maximal bounding box of a font. ...
...the shifted object might be a sub- or superscript. 33 bbox deprecated, svg, svg attribute the bbox attribute defines the maximal bounding box of a font. ...
...And 15 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
worse this time , as even after applying those compilation options mentioned above, i now get the following error message while stating thunderbird with autoconfig (autoconf.js having pref('general.config.filename','thunderbird.cfg'); ) and thunderbird.cfg calling getldap* functions to retrieve cn and mail address of the current user. netscape.cfg/autoconfig failed. please contact your system administrator. error: getldapattibutes failed: [exception... "component returned failure code: 0xc1f30001 (ns_error_not_initialized) [nsildapurl.spec]" nsresult: "0xc1f30001 (ns_error_not_initialized)" location: "js frame :: file:////usr/lib/thunderbird-3.0b2/defaults/autoconfig/prefcalls.js :: getldapattributes :: line 174" data: no] bug 295329 had been re-opened . autoconfig option and ldap ...
...hunderbird 2.x beta 2 recently (2007/03/21) i've tested with thunderbird 2 beta 2 (2007/01/16) to check if autoconfig + ldap is still supported . apprently it's ok . autonfig api is there, ldap call works fine, good !. my tests were on windows vista, and i noticed at least one difference, it is that paths changed; now the profile is in (for my procacci user sample): c:\users\procacci\appdata\roaming\thunderbird\profiles\v6we4uku.default start in debug mode in comand line interface: debug with displayerror() here's the result, i used the displayerror() method ( not the best way :-( see bug 206294 ) to show environment and ldap variables in order to check that it worked fine. just setting mozilla_debug=1 (see js code in thunderbird.cfg) allow that message to appear , it's very usef...
...inally call processldapvalues , "2)" just above. // 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);} if ldap call are uncommented in the preference file above, then i get a popup with: netscape.cfg/autoconfig failed. please contact your system administrator. error: getldapattibutes failed: [exception... "could not convert javascript argument arg 0 [nsisupports.queryinterface]" nsresult: "0x80570009 (ns_error_xpc_bad_convert_js)" location: "js frame :: prefcalls.js :: getldapattributes :: line 177" data: no] autoconfig (pref) and ldap support in packages add ldap support in firefox 1.5 a least from firefox 1.5, autoconfig is compiled ...
...And 14 more matches
Mozilla Crypto FAQ - Archive of obsolete content
ublic domain and a full open source crypto implementation is being added to the mozilla code base. information in the faq also reflects the new u.s. encryption export regulations published on january 14, 2000, the release on february 11, 2000, of source code for ssl, s/mime, and general pki functionality for use in the mozilla project, and the "bernstein advisory" issued by the bureau of export administration on february 17, 2000. the questions in this faq address mozilla's support for encryption and related security functionality, information important to mozilla contributors relating to encryption functionality in mozilla, and general questions on u.s. regulation of encryption technology. cryptographic functionality in mozilla have all the issues with mozilla and crypto now been resolved...
...related security functionality, information important to mozilla contributors relating to encryption functionality in mozilla, and general questions on u.s. regulation of encryption technology. cryptographic functionality in mozilla have all the issues with mozilla and crypto now been resolved? almost. now that the rsa patent is in the public domain, mozilla crypto development can proceed with minimal restrictions. in the near future the mozilla code base will include a complete open source cryptographic library, and mozilla will include ssl support as a standard feature. after the u.s. government relaxed u.s. export regulations in january 2000 to allow export of source code for open source software implementing encryption, the major remaining legal obstacle to mozilla crypto development ...
... key and certificate database (with which the psm key and certificate database format is compatible). information for mozilla contributors i want to mirror the mozilla ftp site. do i need to do anything with regard to u.s. encryption export controls? no, you do not. as long as you are simply mirroring the mozilla site as is, you do not need to provide any notification to the bureau of export administration or nsa. if you are outside the u.s. you do not need to provide such notification in any case, but you may need to take other actions to comply with laws and regulations in your own country concerning encryption technologies. as a mirror of the mozilla ftp site you will automatically be distributing open source encryption code as well. if you are a u.s. resident and/or your mirror site i...
...And 14 more matches
Browser Detection and Cross Browser Support - Archive of obsolete content
informations. improper browser detection can lead to web maintenance nightmares. rethinking the basics of when and how to detect user agents is crucial to creating maintainable, cross browser web content. this article reviews several approaches to browser detection, their usefulness in specific circumstances to arrive at a common sense approach to browser detection. 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. note that some other browsers such as safari are reporting (like gecko) in their user agent strings and can confuse simple tests. introduction in an ideal world, we could author html, xml, css and javascript and only worry about the w3c and ecma st...
...owsers such as safari are reporting (like gecko) in their user agent strings and can confuse simple tests. introduction in an ideal world, we could author html, xml, css and javascript and only worry about the w3c and ecma standards. however, we don't quite live in such a world yet. 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. although browser detection is perhaps the most common scripting task that every web developer faces, it seems that the variety of different strategies in use for detecting browsers is unlimited. as a member of the netscape evangelism team who has spent over a year investigating existing web content, i ...
... gecko was designed from the ground up to be compliant with the w3c html, w3c css, w3c xml, w3c dom, and ecmascript (javascript) standards. it also includes compatibility features which allow it to reasonably handle legacy content which was developed for earlier generations of browsers such as netscape navigator 4 as well as features which provide compatibility with inte...
...And 14 more matches
Introduction to the server side - Learn web development
overview: first steps next welcome to the mdn beginner's server-side programming course! in this first article, we look at server-side programming from a high level, answering questions such as "what is it?", "how does it differ from client-side programming?", and "why it is so useful?". after reading this article you'll understand the additional power available to websites through server-side coding. prerequisites: basic computer literacy. a basic understanding of what a web server is. objective: to gain familiarity with what server-side programming is, what it can do, and how it differs from client-side programming. most large-scale websites use server-side code to dynamically display different data when needed, generally pulled out of a database sto...
...sing stored credit card details to streamline subsequent payments. it can even allow interaction with users of the site, sending notifications and updates via email or through other channels. all of these capabilities enable much deeper engagement with users. in the modern world of web development, learning about server-side development is highly recommended. what is server-side website programming? web browsers communicate with web servers using the hypertext transfer protocol (http). when you click a link on a web page, submit a form, or run a search, an http request is sent from your browser to the target server. the request includes a url identifying the affected resource, a method that defines the required action (for example to get, delete, or post the resource), and may include ad...
... of storing large amounts of content than using static websites). a dynamic site can return different data for a url based on information provided by the user or stored preferences and can perform other operations as part of returning a response (e.g. sending notifications). most of the code to support a dynamic website must run on the server. creating this code is known as "server-side programming" (or sometimes "back-end scripting"). the diagram below shows a simple architecture for a dynamic website. as in the previous diagram, browsers send http requests to the server, then the server processes the requests and returns appropriate http responses. requests for static resources are handled in the same way as for static sites (static resources are any files that don't change —typicall...
...And 14 more matches
Bytecode Descriptions
uint24_t immediate operand as an int32value. double operands: (double val) stack: ⇒ val push the 64-bit floating-point immediate operand as a doublevalue. if the operand is a nan, it must be the canonical nan (see js::detail::canonicalizenan). bigint operands: (uint32_t bigintindex) stack: ⇒ bigint push the bigint constant script->getbigint(bigintindex). string operands: (uint32_t atomindex) stack: ⇒ string push the string constant script->getatom(atomindex). format: jof_atom symbol operands: (uint8_t symbol (the js::symbolcode of the symbol to use)) stack: ⇒ symbol push a well-known symbol. symbol must be in range for js::symbolcode. expressions unary operators void stack: val ⇒ undefined pop the top value on the stack, discard it, and push undefined. implements: t...
...ue on the top of the stack. implements: import calls. importmeta stack: ⇒ import.meta push the import.meta object. this must be used only in module code. objects creating objects newinit stack: ⇒ obj create and push a new object with no properties. format: jof_ic newobject, newobjectwithgroup operands: (uint32_t baseobjindex) stack: ⇒ obj create and push a new object of a predetermined shape. the new object has the shape of the template object script->getobject(baseobjindex). subsequent initprop instructions must fill in all slots of the new object before it is used in any other way. for jsop::newobject, the new object has a group based on the allocation site (or a new group if the template's group is a singleton). for jsop::newobjectwithgroup, the new object has the same gro...
...h value val. val may be magicvalue(js_elements_hole). if it is, this does nothing. this never calls setters or proxy traps. array must be an array object created by jsop::newarray with length > index, and never used except by jsop::initelemarray. implements: arrayaccumulation, the third algorithm, step 4, in the common case where nextindex is known. format: jof_elem, jof_propinit, jof_ic initeleminc stack: array, index, val ⇒ array, (index + 1) initialize an array element array[index++] with value val. val may be magicvalue(js_elements_hole). if it is, no element is defined, but the array length and the stack value index are still incremented. this never calls setters or proxy traps. array must be an array object created by jsop::newarray and never used except by jsop::initelemarray and ...
...And 14 more matches
Using the Multiple Accounts API
ties structure the account system consists of: the account manager (nsimsgaccountmanager): there is a single account manager in the the client, which maintains the list of accounts, servers, etc. it is also responsible for the creation of any new account-related objects. the account manager maintains the main list of accounts. accounts (nsimsgaccount): an account consists of a single incoming server, and one or more identities. an account is merely a container to bind incoming servers and identities together. incoming servers (nsimsgincomingserver): an incoming server represents a remote message store such as a pop, imap, or nntp server. it holds all the information necessary to retrieve mail from the remote server, such as hostname, user login name, and biff settings. identities (...
...ins all the information necessary to compose and outgoing mail message. it includes a user's full name and e-mail address. smtp servers (nsismtpserver): an smtp server is not tied to any of the above and can be retrieved from the smtp service (nsismtpservice). here's an example of a common setup. ...
...(nsismtpserver): an smtp server is not tied to any of the above and can be retrieved from the smtp service (nsismtpservice). here's an example of a common setup. ...
...And 14 more matches
Plug-in Basics - Plugins
er than disk space when it is not loaded. the next section, understanding the runtime model, describes these stages in more detail. understanding the runtime model plug-ins are dynamic code modules that are associated with one or more mime types. when the browser starts, it enumerates the available plug-ins (this step varies according to platform), reads resources from each plug-in file to determine the mime types for that plug-in, and registers each plug-in library for its mime types. the following stages outline the life of a plug-in from loading to deletion: when gecko encounters data of a mime type registered for a plug-in (either embedded in an html page or in a separate file), it dynamically loads the plug-in code into memory, if it hasn't been loaded already, and it creates a new...
...ins, where profile directory is the directory of the current user profile. ~/.mozilla/plugins. /usr/lib/mozilla/plugins (the 64-bit firefox checks /usr/lib64/mozilla/plugins as well). /usr/lib64/firefox/plugins (for 64-bit firefox) note: firefox nightly checks a subset of these locations. also some linux distributions provide a system browser configured differently. advanced: you can determine which directories a gecko program checks with the linux strace command, for example: strace -e open /usr/bin/firefox 2>&1 | grep plugin but with version firefox-41.0.2 we can not check. i found other way how check which paths support firefox : $ strace -y /usr/bin/firefox 2>&1 | grep acces | grep -v search | grep plugins access("/home/user_name/.mozilla/firefox/dqh2nb5k.default-1441864569209/...
...ied by the plug-in. on windows, installed plug-ins are automatically configured to handle the mime types that they support. if multiple plug-ins handle the same mime type, the first plug-in registered handles the mime type. for information about the way mime types are assigned, see registering plug-ins. checking plug-ins by mime type the enabledplugin property in javascript can be used to determine which plug-in is configured for a specific mime type. though plug-ins may support multiple mime types and each mime type may be supported by multiple plug-ins, only one plug-in can be configured for a mime type. the enabledplugin property is a reference to a plugin object that represents the plug-in that is configured for the specified mime type. you might need to know which plug-in is configur...
...And 14 more matches
Background Tasks API - Web APIs
concepts and usage the main thread of a web browser is centered around its event loop. ...
...ction which runs the callback passed into our implementation of requestidlecallback(). the callback is passed an object which conforms to idledeadline, with didtimeout set to false and a timeremaining() method which is implemented to give the callback 50 milliseconds of time to begin with. each time timeremaining() is called, it subtracts the elapsed time from the original 50 milliseconds to determine the amount of time left. as a result, while our shim doesn't constrain itself to the amount of idle time left in the current event loop pass like the true requestidlecallback(), it does at least limit the callback to no more than 50 milliseconds of run time per pass. the implementation of our shim for cancelidlecallback() is much simpler: window.cancelidlecallback = window.cancelidlecallback ...
...callback to provide an estimate of how long the idle period is expected to last, as well as whether or not the callback is running because its timeout period has expired. the window interface is also augmented by this api to offer the new requestidlecallback() and cancelidlecallback() methods. example in this example, we'll take a look at how you can use requestidlecallback() to run time-consuming, low-priority tasks during time the browser would otherwise be idle. in addition, this example demonstrates how to schedule updates to the document content using requestanimationframe(). below you'll find only the html and javascript for this example. the css is not shown, since it's not particularly crucial to understanding this functionality. html content in order to be oriented about what ...
...And 14 more matches
Lighting a WebXR setting - Web APIs
because the webxr device api relies on other technologies—namely, webgl and frameworks based upon it—to perform all rendering, texturing, and lighting of a scene, the same general lighting concepts apply to webxr settings or scenes as to any other webgl-generated display. however, there are issues and details to keep in mind while creating your lighting code, especially for augmented reality (ar) applications. this guide discusses these topics. ...
... upon it—to perform all rendering, texturing, and lighting of a scene, the same general lighting concepts apply to webxr settings or scenes as to any other webgl-generated display. however, there are issues and details to keep in mind while creating your lighting code, especially for augmented reality (ar) applications. this guide discusses these topics. and while this article provides brief reminders as to how lighting works in general, it is not by any means a tutorial in lighting or a guide to how to create a properly-lit 3d scene. flashback: simulating lighting in 3d although this article isn't a comprehensive guide to lighting a 3d scene, it's useful to provide a brief reminder as to how lighting works in general. fundamentally, simulating lighting in a virtual scene involves comput...
...ulating lighting in a virtual scene involves computing how much light from each light source is received by the eye after interacting with and reflecting off of each object in the scene. reflection of light a diagram showing how the angle of reflection corresponds to the angle of incidence. every object we see, we see because the object either emits or reflects light (or both). the incoming light ray—the incident ray—arrives at an angle known as the angle of incidence. the angle of incidence, Θi, is the angle between the incident ray and the surface's normal vector. for rough surfaces, light is reflected equally in every direction. however, glossy, mirror-like surfaces reflect most of the light in a direction whose angle of reflection, Θr, is equal to the angle of incidence,...
...And 14 more matches
Digital audio concepts - Web media technologies
sampling audio audio is an inherently analog feature of the natural world. as an object vibrates, it causes the molecules surrounding it to vibrate as well. ...
...g into digital form. the audio bandwidth is also affected by the codec, if it chooses to discard any frequency bands while encoding the sound. sound enters the computer through a microphone or other input in the form of a stream of electrons whose voltage varies to represent the amplitude of the sound wave. this analog signal is then converted into digital form by a circuit that captures the incoming wave's amplitude at regular intervals, converting that data into a number in a form that is understood by the audio recording system. each of these captured moments is a sample. by chaining all the samples together, you can approximately represent the original wave, as seen in the diagram below. in this example, the blue line represents the samples taken from the audio waveform, which is blac...
... the majority of day-to-day audio in use today. for 16-bit stereo audio, each sample taken from the analog signal is recorded as two 16-bit integers, one for the left channel and one for the right. that means each sample requires 32 bits of memory. at the common sample rate of 48 khz (48,000 samples per second), this means each second of audio occupies 192 kb of memory. therefore, a typical three-minute song requires about 34.5 mb of memory. that's a lot of storage, but worse, it's an insane amount of network bandwidth to use for a relatively short piece of audio. that's why most digital audio is compressed. the process of compressing and decompressing audio is performed by encoding and decoding it using an audio codec (coder/decoder). over the years, a large variety of codecs have been deve...
...And 14 more matches
Client-side form validation - Learn web development
uld always perform security checks on any form-submitted data on the server-side as well as the client-side, because client-side validation is too easy to bypass, so malicious users can still easily send bad data through to your server. read website security for an idea of what could happen; implementing server-side validation is somewhat beyond the scope of this module, but you should bear it in mind. what is form validation? go to any popular site with a registration form, and you will notice that they provide feedback when you don't enter your data in the format they are expecting. you'll get messages such as: "this field is required" (you can't leave this field blank). "please enter your phone number in the format xxx-xxxx" (a specific data format is required for it to be considered...
...brary). using built-in form validation one of the most significant features of html5 form controls is the ability to validate most user data without relying on javascript. this is done by using validation attributes on form elements. we've seen many of these earlier in the course, but to recap: required: specifies whether a form field needs to be filled in before the form can be submitted. minlength and maxlength: specifies the minimum and maximum length of textual data (strings) min and max: specifies the minimum and maximum values of numerical input types type: specifies whether the data needs to be a number, an email address, or some other specific preset type. pattern: specifies a regular expression that defines a pattern the entered data needs to follow. if the data entered ...
...for example, validates the inputs value against a well-formed email address pattern or a pattern matching a comma-separated list of email addresses if it has the multiple attribute. note: the <textarea> element doesn't support the pattern attribute. constraining the length of your entries you can constrain the character length of all text fields created by <input> or <textarea> by using the minlength and maxlength attributes. a field is invalid if it has a value and that value has fewer characters than the minlength value or more than the maxlength value. browsers often don't let the user type a longer value than expected into text fields. a better user experience than just using maxlength is to also provide character count feedback in an accessible manner and let them edit their conte...
...And 13 more matches
Video and Audio APIs - Learn web development
seful for video playback, but it does have advantages. one big issue with the native browser controls is that they are different in each browser — not very good for cross-browser support! another big issue is that the native controls in most browsers aren't very keyboard-accessible. you can solve both these problems by hiding the native controls (by removing the controls attribute), and programming your own with html, css, and javascript. in the next section we'll look at the basic tools we have available to do this. the htmlmediaelement api part of the html5 spec, the htmlmediaelement api provides features to allow you to control video and audio players programmatically — for example htmlmediaelement.play(), htmlmediaelement.pause(), etc. this interface is available to both <audio> an...
...download our media-player-start.zip and unzip it into a new directory on your hard drive. if you downloaded our examples repo, you'll find it in javascript/apis/video-audio/start/ at this point, if you load the html you should see a perfectly normal html5 video player, with the native controls rendered. exploring the html open the html index file. ...
... each button, since we're not providing a human-readable label inside the tags. the contents of aria-label attributes are read out by screenreaders when their users focus on the elements that contain them. there is also a timer <div>, which will report the elapsed time when the video is playing. just for fun, we are providing two reporting mechanisms — a <span> containing the elapsed time in minutes and seconds, and an extra <div> that we will use to create a horizontal indicator bar that gets longer as the time elapses. to get an idea of what the finished product will look like, check out our finished version. exploring the css now open the css file and have a look inside. the css for the example is not too complicated, but we'll highlight the most interesting bits here. first o...
...And 13 more matches
Places utilities for JavaScript
, string type, nsinavhistoryresultnode container, int index, boolean copy); nsinavhistoryresult getfoldercontents(int afolderid, boolean aexcludeitems, boolean aexpandqueries); boolean showaddbookmarkui(nsiuri auri, string atitle, string adescription, int adefaultinsertionpoint, boolean ashowpicker, boolean aloadinsidebar, string akeyword, string apostdata); boolean showminimaladdbookmarkui(nsiuri auri, string atitle, string adescription, int adefaultinsertionpoint, boolean ashowpicker, boolean aloadinsidebar, string akeyword, string apostdata); boolean showaddlivemarkui(nsiuri afeeduri, nsiuri asiteuri, string atitle, string adescription, int adefaultinsertionpoint, boolean ashowpicker); boolean showminimaladdlivemarkui(nsiuri afeeduri, nsiuri asi...
..., boolean aloadinsidebar, string akeyword, string apostdata); boolean showaddlivemarkui(nsiuri afeeduri, nsiuri asiteuri, string atitle, string adescription, int adefaultinsertionpoint, boolean ashowpicker); boolean showminimaladdlivemarkui(nsiuri afeeduri, nsiuri asiteuri, string atitle, string adescription, int adefaultinsertionpoint, boolean ashowpicker); boolean showminimaladdmultibookmarkui(array nsiuri aurilist); boolean showbookmarkproperties(int aid); boolean showfolderproperties(int aid); boolean showaddfolderui(string atitle, int adefaultinsertionpoint, boolean ashowpicker); array object getannotationsforuri(nsiuri auri); array object getannotationsforitem(int aitemid); void setannotationsforuri(nsiuri ...
...ring(string key) parameters key the name of the string to get. return type returns a string from the default places stringbundle. nodeis() there are a ton of nodeis(something) functions in here to check properties of a bookmark node. ...
...And 13 more matches
Signaling and video calling - Web APIs
n different networks to locate one another. this process is called signaling and involves both devices connecting to a third, mutually agreed-upon server. through this third server, the two devices can locate one another, and exchange negotiation messages. in this article, we will further enhance the websocket chat first created as part of our websocket documentation (this article link is forthcoming; it isn't actually online yet) to support opening a two-way video call between users. you can try out this example on glitch, and you can remix the example to experiment with it as well. you can also look at the full project on github. note: if you try out the example on glitch, please note that any changes made to the code will immediately reset any connections. in addition, there is a short ...
... connections. in addition, there is a short timeout period; the glitch instance is for quick experiments and testing only. the signaling server establishing a webrtc connection between two devices requires the use of a signaling server to resolve how to connect them over the internet. a signaling server's job is to serve as an intermediary to let two peers find and establish a connection while minimizing exposure of potentially private information as much as possible. how do we create this server and how does the signaling process actually work? first we need the signaling server itself. webrtc doesn't specify a transport mechanism for the signaling information. you can use anything you like, from websocket to xmlhttprequest to carrier pigeons to exchange the signaling information between...
...ablishment (ice) comes in. exchanging ice candidates two peers need to exchange ice candidates to negotiate the actual connection between them. every ice candidate describes a method that the sending peer is able to use to communicate. each peer sends candidates in the order they're discovered, and keeps sending candidates until it runs out of suggestions, even if media has already started streaming. an icecandidate event is sent to the rtcpeerconnection to complete the process of adding a local description using pc.setlocaldescription(offer). once the two peers agree upon a mutually-compatible candidate, that candidate's sdp is used by each peer to construct and open a connection, through which media then begins to flow. if they later agree on a better (usually higher-performance) candid...
...And 13 more matches
splitter - Archive of obsolete content
state style classes tree-splitter examples <!-- this bar has some styling associated with it. the vbox is used to hold the .png image that a user clicks on to resize the search bar.--> <splitter tooltiptext="resize the search box" oncommand="alert('the splitter was dragged')"> <vbox id="example_vbox" /> </splitter> attributes collapse type: one of the values below determines which side of the splitter is collapsed when its grippy is clicked. if this attribute is not specified, the splitter will not cause a collapse. you should put a grippy element inside the splitter when it is used for collapsing. none no collapsing occurs. before when the grippy is clicked, the element immediately before the splitter in the same parent is collapsed so that its width o...
...the splitter in the same parent is collapsed so that its width or height is 0. after when the grippy is clicked, the element immediately after the splitter in the same parent is collapsed so that its width or height is 0. both either the element immediately before the splitter, or the element immediately after the splitter can be collapsed, if the size of that element would fall below the minimum size due to the position of the splitter. resizeafter type: one of the values below this attribute indicates which element to the right or below the splitter should be resized when the splitter is repositioned. closest the element immediately to the right or below the splitter resizes. farthest the element that is the farthest away from the splitter to the right or be...
...ding on the value of the collapsed attribute, is currently displayed. collapsed the content either before or after the splitter is collapsed and is not visible. dragging the user is current adjusting the position of the splitter, typically by dragging it with the mouse. substate type: one of the values below on splitters which have state="collapsed" and collapse="both", determines which direction the splitter is actually collapsed in. since collapse="both" is a gecko 1.9+ feature, this will have no effect on earlier versions. before the element immediately before the splitter is collapsed. after the element immediately after the splitter is collapsed. properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , ,...
...And 12 more matches
Anatomy of a video game - Game development
to it when it is called. that callback function will be executed at a suitable time before the next repaint. here is an example of a simple main loop: window.main = function () { window.requestanimationframe( main ); // whatever your main loop needs to do }; main(); // start the cycle note: in each of the main() methods discussed here, we schedule a new requestanimationframe before performing our loop contents. that is not by accident and it is considered best practice. calling the next requestanimationframe early ensures the browser receives it on time to plan accordingly even if your current frame misses its vsync window. the above chunk of code has two statements. the first statement creates a function as a global variable called main(). this function does some work and also tel...
...dow.requestanimationframe(). the second statement calls the main() function, defined in the first statement. because main() is called once in the second statement and every call of it places itself in the queue of things to do next frame, main() is synchronized to your framerate. of course this loop is not perfect. before we discuss ways to change it, let us discuss what it already does well. timing the main loop to when the browser paints to the display allows you to run your loop as frequently as the browser wants to paint. you are given control over each frame of animation. it is also very simple because main() is the only function getting looped. a first person shooter (or a similar game) presents a new scene once every frame. you cannot really get more smooth and responsive than that. ...
...ou could create it as an immediately-invoked function expression (iife). /* * starting with the semicolon is in case whatever line of code above this example * relied on automatic semicolon insertion (asi). the browser could accidentally * think this whole example continues from the previous line. the leading semicolon * marks the beginning of our new line if the previous one was not empty or terminated. */ ;(function () { function main() { window.requestanimationframe( main ); // your main loop contents } main(); // start the cycle })(); when the browser comes across this iife, it will define your main loop and immediately queue it for the next frame. it will not be attached to any object and main (or main() for methods) will be a valid unused name in the rest of the appli...
...And 12 more matches
Localization and Plurals
can have different rules. plural form: for a particular plural rule, there can be multiple forms of a word, such as "page" and "pages". in this case, there are 2 forms, but other languages can have 1 or many more. if you're here for pluralrule in the chrome/global/intl.properties file, you'll need to figure out what plural rule to choose for your localization. this plural rule is used to determine how many plural forms are needed for each word that needs to be localized, with plurals in mind. for all other properties files that link to this page, you'll need to provide enough plural forms of the desired word, and separate them with semi-colons (;). if you don't know how many plural forms you need, check the pluralrule number in chrome/global/intl.properties, and look up the corresponding...
...60, 65, 66, 67, 68, 69, 70, 75, 76, 77, …, 112, 113, ..., 212, 213, ... examples the following are some examples for various languages and a brief thought processes. french some french speaking places treat 0 as plural while others treat it as singular. the only other singular is 1 while everything else is plural. so pick either plural rule #1 or #2. pluralrule=2 seconds=seconde;secondes minutes=minute;minutes hours=heure;heures days=jour;jours like many other times when localizing words, gender agreement might force you to rearrange words in a way that the gender is always the same. (seconde vs jour) chinese a word doesn't change if there is a different number in front of it, so all numbers use the same plural form. with just one plural form, it has to be plural rule #0. for e...
...nt might force you to rearrange words in a way that the gender is always the same. (seconde vs jour) chinese a word doesn't change if there is a different number in front of it, so all numbers use the same plural form. with just one plural form, it has to be plural rule #0. for each word to localize, it's just like localizing a single word with no semi-colons needed. ...
...And 12 more matches
JSAPI User Guide
s to other libraries and programs that can make life easier when using spidermonkey and jsapi. what spidermonkey does the javascript engine compiles and executes scripts containing javascript statements and functions. the engine handles memory allocation for the objects needed to execute scripts, and it cleans up—garbage collects—objects it no longer needs. the word javascript may bring to mind features such as event handlers (like onclick), dom objects, window.open, and xmlhttprequest. but in mozilla, all of these features are actually provided by other components, not the spidermonkey engine itself. spidermonkey provides a few core javascript data types—numbers, strings, arrays, objects, and so on—and a few methods, such as array.push. it also makes it easy for each application t...
...and variables (like window) the application wants to provide; see custom objects below. each time the application runs a js script (using, for example, js_evaluatescript), it provides the global object for that script to use. as the script runs, it can create global functions and variables of its own. all of these functions, classes, and variables are stored as properties of the global object. a minimal example each of the three key elements described in the previous section requires a few jsapi calls: the runtime: use js_newruntime to create it and js_destroyruntime to clean it up when you're done. when your application is done with spidermonkey altogether, use js_shutdown to free any remaining cached resources. (this is a mere nicety if the process is about to exit anyway. but as th...
...s. this may seem like a lot of pieces for a simple application. it amounts to about 80 lines of code, as shown below. but the jsapi is designed to scale to applications that need many global objects. it is a fine-grained api, supporting many different combinations of the parts, and giving applications precise control over how spidermonkey behaves. here is the boilerplate code necessary for a minimal jsapi application. it contains everything described above. #include "jsapi.h" using namespace js; // the class of the global object. static jsclass globalclass = { "global", jsclass_global_flags, js_propertystub, js_deletepropertystub, js_propertystub, js_strictpropertystub, js_enumeratestub, js_resolvestub, js_convertstub, nullptr, nullptr, nullptr,...
...And 12 more matches
Shell global objects
if the property is omitted or v is null, don't attribute the source to any dom element. elementattributename if present and not undefined, t...
...if the property is omitted or v is null, don't attribute the source to any dom element. elementattributename if present and not undefined, the name of property of elemen...
... info linenumber starting line number for error messages and debug info columnnumber starting column number for error messages and debug info global global in which to execute the code newcontext if true, create and use a new cx (default: false) catchtermination if true, catch termination (failure without an exception value, as for slow scripts or out-of-memory) and return 'terminated' element if present with value v, convert v to an object o and mark the source as being attached to the dom element o. if the property is omitted or v is null, don't attribute the source to any dom element. elementattributename if present and not undefined, the name of property of element that holds this code. this is what debugger.source.prototype.elementattributename returns. sour...
...And 12 more matches
Performance API - Web APIs
p whose value that depends on the navigation start and scope. if the scope is a window, the value is the time the browser context was created and if the scope is a worker, the value is the time the worker was created. the tojson() method returns a serialization of the performance object, for those attributes that can be serialized. properties the performance interface has two properties. the timing property returns a performancetiming object containing latency-related performance information such as the start of navigation time, start and end times for redirects, start and end times for responses, etc. the navigation property returns a performancenavigation object representing the type of navigation that occurs in the given browsing context, such as the page was navigated to from history,...
...on time, start and end times for redirects, start and end times for responses, etc. the navigation property returns a performancenavigation object representing the type of navigation that occurs in the given browsing context, such as the page was navigated to from history, the page was navigated to by following a link, etc. interfaces performance provides methods and properties containing timing-related performance information for the given page. performanceentry provides methods and properties the encapsulate a single performance metric that is part of the performance timeline. performanceframetiming provides methods and properties containing frame timing data about the browser's event loop. performancemark an abstract interface for performance entries with an entry type of "mark...
... performance.mark() to add a named domhighrestimestamp (the mark) to the browser's performance timeline. performancemeasure an abstract interface for performance entries with an entry type of "measure". entries of this type are created by calling performance.measure() to add a nameddomhighrestimestamp (the measure) between two marks to the browser's performance timeline. ...
...And 12 more matches
WebGL constants - Web APIs
h, rbg and alpha, or separately). constant name value description zero 0 passed to blendfunc or blendfuncseparate to turn off a component. one 1 passed to blendfunc or blendfuncseparate to turn on a component. src_color 0x0300 passed to blendfunc or blendfuncseparate to multiply a component by the source elements color. one_minus_src_color 0x0301 passed to blendfunc or blendfuncseparate to multiply a component by one minus the source elements color. src_alpha 0x0302 passed to blendfunc or blendfuncseparate to multiply a component by the source's alpha. one_minus_src_alpha 0x0303 passed to blendfunc or blendfuncseparate to multiply a component by one minus the source's alpha. ...
.... src_alpha 0x0302 passed to blendfunc or blendfuncseparate to multiply a component by the source's alpha. one_minus_src_alpha 0x0303 passed to blendfunc or blendfuncseparate to multiply a component by one minus the source's alpha. dst_alpha 0x0304 passed to blendfunc or blendfuncseparate to multiply a component by the destination's alpha. one_minus_dst_alpha 0x0305 passed to blendfunc or blendfuncseparate to multiply a component by one minus the destination's alpha. dst_color 0x0306 passed to blendfunc or blendfuncseparate to multiply a component by the destination's color. one_minus_dst_color 0x0307 passed to blendfunc or blendfuncseparate to multiply a component by one minus the destination's color. ...
...ination's alpha. dst_color 0x0306 passed to blendfunc or blendfuncseparate to multiply a component by the destination's color. one_minus_dst_color 0x0307 passed to blendfunc or blendfuncseparate to multiply a component by one minus the destination's color. src_alpha_saturate 0x0308 passed to blendfunc or blendfuncseparate to multiply a component by the minimum of source's alpha or one minus the destination's alpha. constant_color 0x8001 passed to blendfunc or blendfuncseparate to specify a constant color blend function. one_minus_constant_color 0x8002 passed to blendfunc or blendfuncseparate to specify one minus a constant color blend function. constant_alpha 0x8003 passed to blendfunc or blendfuncsepara...
...And 12 more matches
WebGL best practices - Web APIs
complicated api, and it's often not obvious what the recommended ways to use it are. this page tackles recommendations across the spectrum of expertise, and not only highlights dos and don'ts, but also details why. you can rely on this document to guide your choice of approach, and ensure you're on the right track no matter what browser or hardware your users run. general topics address and eliminate webgl errors your application should run without generating any webgl errors (as returned by geterror). every webgl error is reported in the web console as a javascript warning with a descriptive message. after too many errors (32 in firefox), webgl stops generating descriptive messages, which really hinders debugging. the only errors a well-formed page generates are out_of_memory and contex...
...nal by gracefully adapting to the case there they are not supported. ...
... angle_instanced_arrays ext_blend_minmax oes_element_index_uint oes_standard_derivatives oes_vertex_array_object webgl_debug_renderer_info webgl_lose_context (see also: https://jdashg.github.io/misc/webgl/webgl-feature-levels.html) consider polyfilling these into webglrenderingcontext, like: https://github.com/jdashg/misc/blob/master/webgl/webgl-v1.1.js universally supported limits the minimum requirements for webgl are quite low. in practice, effectively all systems support at least the following: max_cube_map_texture_size: 4096 max_renderbuffer_size: 4096 max_texture_size: 4096 max_viewport_dims: [4096,4096] max_vertex_texture_image_units: 4 max_texture_image_units: 8 max_combined_texture_image_units: 8 max_vertex_attribs: 16 max_varying_vecto...
...And 12 more matches
Using the Web Animations API - Web APIs
0.3. currently, there should be at least two keyframes specified (representing the starting and ending states of the animation sequence). if your keyframe list has only one entry, element.animate() may throw a notsupportederror exception in some browsers until they are updated. so to recap, the keys are equally spaced by default unless you specify an offset on a key. ...
...cified (representing the starting and ending states of the animation sequence). if your keyframe list has only one entry, element.animate() may throw a notsupportederror exception in some browsers until they are updated. so to recap, the keys are equally spaced by default unless you specify an offset on a key. handy, no? representing timing properties we’ll also need to create an object of timing properties (an animationeffecttimingproperties object) corresponding to the values in alice’s animation: var alicetiming = { duration: 3000, iterations: infinity } you’ll notice a few differences here from how equivalent values are represented in css: for one, the duration is in milliseconds as opposed to seconds — 3000 not 3s. like windowtimers.settimeout() and window.requestanim...
...rences here from how equivalent values are represented in css: for one, the duration is in milliseconds as opposed to seconds — 3000 not 3s. like windowtimers.settimeout() and window.requestanimationframe(), the web animations api only takes milliseconds. the other thing you’ll notice is that it’s iterations, not iteration-count. ...
...And 12 more matches
Web video codec guide - Web media technologies
ressed video data, it's necessary to compress it significantly in order to store it, let alone transmit it over a network. imagine the amount of data needed to store uncompressed video: a single frame of high definition (1920x1080) video in full color (4 bytes per pixel) is 8,294,400 bytes. at a typical 30 frames per second, each second of hd video would occupy 248,832,000 bytes (~249 mb). a minute of hd video would need 14.93 gb of storage. a fairly typical 30 minute video conference would need about 447.9 gb of storage, and a 2-hour movie would take almost 1.79 tb (that is, 1790 gb). not only is the required storage space enormous, but the network bandwidth needed to transmit an uncompressed video like that would be enormous, at 249 mb/sec—not including audio and overhead. this is...
...video. additionally, in saturated portions of the image (that is, where colors are pure and intense, such as a bright, pure red [rgba(255, 0, 0, 1)]), color depths below 10 bits per component (10-bit color) allow banding, where gradients cannot be represented without visible stepping of the colors. depending on the codec, higher color depths may result in larger compressed file sizes. ...
...lors. depending on the codec, higher color depths may result in larger compressed file sizes. the determining factor is what internal storage format is used for the compressed data. frame rate primarily affects the perceived smoothness of the motion in the image. to a point, the higher the frame rate, the smoother and more realistic the motion will appear. eventually the point of diminishing returns is reached. see frame rate below for details. assuming the frame rate is not reduced during encoding, higher frame rates cause larger compressed video sizes. motion compression of video typically works by comparing frames, finding where they differ, and constructing records containing enough information to update the previous frame to approximate the appearance of the...
...And 12 more matches
preserveAspectRatio - SVG: Scalable Vector Graphics
" xmlns="http://www.w3.org/2000/svg"> <defs> <path id="smiley" d="m50,10 a40,40,1,1,1,50,90 a40,40,1,1,1,50,10 m30,40 q36,35,42,40 m58,40 q64,35,70,40 m30,60 q50,75,70,60 q50,75,30,60" /> </defs> <!-- (width>height) meet --> <svg preserveaspectratio="xmidymid meet" x="0" y="0" viewbox="0 0 100 100" width="20" height="10"><use href="#smiley" /></svg> <svg preserveaspectratio="xminymid meet" x="25" y="0" viewbox="0 0 100 100" width="20" height="10"><use href="#smiley" /></svg> <svg preserveaspectratio="xmaxymid meet" x="50" y="0" viewbox="0 0 100 100" width="20" height="10"><use href="#smiley" /></svg> <!-- (width>height) slice --> <svg preserveaspectratio="xmidymin slice" x="0" y="15" viewbox="0 0 100 100" width="20" height="10"><use href="#smiley" /></sv...
..."0 0 100 100" width="20" height="10"><use href="#smiley" /></svg> <svg preserveaspectratio="xmidymid slice" x="25" y="15" viewbox="0 0 100 100" width="20" height="10"><use href="#smiley" /></svg> <svg preserveaspectratio="xmidymax slice" x="50" y="15" viewbox="0 0 100 100" width="20" height="10"><use href="#smiley" /></svg> <!-- (width<height) meet --> <svg preserveaspectratio="xmidymin meet" x="75" y="0" viewbox="0 0 100 100" width="10" height="25"><use href="#smiley" /></svg> <svg preserveaspectratio="xmidymid meet" x="90" y="0" viewbox="0 0 100 100" width="10" height="25"><use href="#smiley" /></svg> <svg preserveaspectratio="xmidymax meet" x="105" y="0" viewbox="0 0 100 100" width="10" height="25"><use href="#smiley" /></svg> <!-- (width<height) slice --> ...
...ox="0 0 100 100" width="10" height="25"><use href="#smiley" /></svg> <svg preserveaspectratio="xmidymid meet" x="90" y="0" viewbox="0 0 100 100" width="10" height="25"><use href="#smiley" /></svg> <svg preserveaspectratio="xmidymax meet" x="105" y="0" viewbox="0 0 100 100" width="10" height="25"><use href="#smiley" /></svg> <!-- (width<height) slice --> <svg preserveaspectratio="xminymid slice" x="120" y="0" viewbox="0 0 100 100" width="10" height="25"><use href="#smiley" /></svg> <svg preserveaspectratio="xmidymid slice" x="135" y="0" viewbox="0 0 100 100" width="10" height="25"><use href="#smiley" /></svg> <svg preserveaspectratio="xmaxymid slice" x="150" y="0" viewbox="0 0 100 100" width="10" height="25"><use href="#smiley" /></svg> <!-- none --> <svg preser...
...And 12 more matches
NSS API Guidelines
ng/decoding, error types and numbers, oid handling, and secure random number generation. utility for any layer lib/util base64.h, ciferfam.h, nssb64.h, nssb64t.h, nsslocks.h, nssrwlk.h, nssrwlkt.h, portreg.h, pqgutil.h, secasn1.h, secasn1t.h, seccomon.h, secder.h, secdert.h, secdig.h, secdigt.h, secitem.h, secoid.h, secoidt.h, secport.h, secrng.h, secrngt.h, secerr.h, watcomfx.h naming conventions this section describes the rules that (ideally) should be followed for naming and identifying new files, functions, and data types. cvs id each file should include a cvs id string for identification. the preferred format is: "@(#) $rcsfile: nss-guidelines.html, v $ $revision: 48936 $ $date: 2009-08-11 07:45:57 -0700 (tue, 11 aug 2009) $ $name$" you can pu...
... 11 aug 2009) $ $name$" you can put the string in a comment or in a static char array. use #ifdef debug to include the array in debug builds only. the advantage of using an array is that you can use strings(1) to pull the id tags out of a (debug) compiled library. you can even put them in header files; the header files are protected from double inclusion. the only catch is that you have to determine the name of the array. here is an example from lib/base/baset.h: #ifdef debug static const char baset_cvs_id[] = "@(#) $rcsfile: nss-guidelines.html, v $ $revision: 48936 $ $date: 2009-08-11 07:45:57 -0700 (tue, 11 aug 2009) $ $name$"; #endif /* debug */ the difference, between this and id, is that id has some useless information (every file is "experimental"), and do...
...ence, between this and id, is that id has some useless information (every file is "experimental"), and doesn't have name. name is the tag (if any) from which this file was pulled. if you're good with tagging your releases, and then checking out (or exporting!) from the tag for your build, this saves you from messing around with specific files revision numbers. header files we have a preferred naming system for include files. we had been moving towards one, for some time, but for the nss 3.0 project we finally wrote it down. data types function prototypes public nss____t.h nss____.h friend (only if required) nss____tf.h nss____f.h nss-private ____t.h ____.h module-private ____tm.h ____m.h the files on the ...
...And 11 more matches
grid-auto-columns - CSS: Cascading Style Sheets
.com/mdn/interactive-examples and send us a pull request. if a grid item is positioned into a column that is not explicitly sized by grid-template-columns, implicit grid tracks are created to hold it. this can happen either by explicitly positioning into a column that is out of range, or by the auto-placement algorithm creating additional columns. ...
...reating additional columns. ...
...* keyword values */ grid-auto-columns: min-content; grid-auto-columns: max-content; grid-auto-columns: auto; /* <length> values */ grid-auto-columns: 100px; grid-auto-columns: 20cm; grid-auto-columns: 50vmax; /* <percentage> values */ grid-auto-columns: 10%; grid-auto-columns: 33.3%; /* <flex> values */ grid-auto-columns: 0.5fr; grid-auto-columns: 3fr; /* minmax() values */ grid-auto-columns: minmax(100px, auto); grid-auto-columns: minmax(max-content, 2fr); grid-auto-columns: minmax(20%, 80vmax); /* fit-content() values */ grid-auto-columns: fit-content(400px); grid-auto-columns: fit-content(5cm); grid-auto-columns: fit-content(20%); /* multiple track-size values */ grid-auto-columns: min-content max-content auto; grid-auto-columns: 100px 150px 390px; grid-auto-columns: 10% 33.3%; grid-...
...And 11 more matches
<input type="number"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › number
id="number" type="number" value="42"> additional attributes in addition to the attributes commonly supported by all <input> types, inputs of type number support these attributes: attribute description list the id of the <datalist> element 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 <da...
...e suggestions, not requirements: users can select from this predefined list or provide a different value. max the maximum value to accept for this input. if the value entered into the element exceeds this, the element fails constraint validation. if the value of the max attribute isn't a number, then the element has no maximum value. this value must be greater than or equal to the value of the min attribute. min the minimum value to accept for this input. if the value of the element is less than this, the element fails constraint validation. if a value is specified for min that isn't a valid number, the input has no minimum value. this value must be less than or equal to the value of the max attribute. placeholder the placeholder attribute is a string that provides a brief hint to the...
...ly setting the htmlinputelement.value property. note: because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified. step the step attribute is a number that specifies the granularity that the value must adhere to, or the special value any, which is described below. only values which are equal to the basis for stepping (min if specified, value otherwise, and an appropriate default value if neither of those is provided) are valid. a string value of any means that no stepping is implied, and any value is allowed (barring other constraints, such as min and max). note: when the data entered by the user doesn't adhere to the stepping configuration, the user agent may round to the nearest valid value, preferring number...
...And 11 more matches
HTML documentation index - HTML: Hypertext Markup Language
Web › HTML › Index
lements beginner, development, guide, html, html5, web html (hypertext markup language) elements historically were categorized as either "block-level" elements or "inline-level" elements. by default, a block-level element occupies the entire space of its parent element (container), thereby creating a "block." this article helps to explain what this means. 5 dash adaptive streaming for html 5 video guide, html, html5 dynamic adaptive streaming over http (dash) is an adaptive streaming protocol. 6 date and time formats used in html date, element, format, html, iso 8601, input, reference, string, time, week, datetime, datetime-local, del, ins, month, month-year, week-year certain html elements use date and/or time values. the formats of the str...
..., x-ms-acceleratorkey the x-ms-acceleratorkey attribute accessibly declares that an accelerator key has been assigned to an element: the element is activated via javascript when the key(s) are pressed on a keyboard. 35 x-ms-format-detection attribute, html, html:microsoft extensions, non-standard, reference, x-ms-format-detection the x-ms-format-detection attribute determines whether data formats within the element’s text, like phone numbers, are automatically converted to followable links. 36 html attribute reference attribute, attributes, beginner, configuring, element attributes, elements, html, reference, settings, web elements in html have attributes; these are additional values that configure the elements or adjust their behavior in vari...
...e a cors settings attribute. 40 html attribute: max attribute, attributes, constraint validation, html, reference the max attribute defines the maximum value that is acceptable and valid for the input containing the attribute. if the value of the element is greater than this, the element fails constraint validation. this value must be greater than or equal to the value of the min attribute. if the max attribute is present by is not specified or is invalid, no max value is applied. if the max attribute is valid and a non-empty value is greater than the maximum allowed by the max attribute, constraint validation will prevent form submission. 41 html attribute: maxlength attribute, attributes, constraint validation the maxlength attribute defines the max...
...And 11 more matches
Server-side web frameworks - Learn web development
to get files or data from the server may encode what data is required in url parameters or within the url structure. an http post request to update a resource on the server will instead include the update information as "post data" within the body of the request. the http request may also include information about the current session or user in a client-side cookie. web frameworks provide programming-language-appropriate mechanisms to access this information. for example, the httprequest object that django passes to every view function contains methods and properties for accessing the target url, the type of request (e.g. an http get), get or post parameters, cookie and session data, etc. django can also pass information encoded in the structure of the url by defining "capture patterns" in t...
...name value in a list item. #best/templates/best/index.html <!doctype html> <html lang="en"> <body> {% if youngest_teams %} <ul> {% for team in youngest_teams %} <li>{{ team.team_name }}</li> {% endfor %} </ul> {% else %} <p>no teams are available.</p> {% endif %} </body> </html> how to select a web framework numerous web frameworks exist for almost every programming language you might want to use (we list a few of the more popular frameworks in the following section). with so many choices, it can become difficult to work out what framework provides the best starting point for your new web application. some of the factors that may affect your decision are: effort to learn: the effort to learn a web framework depends on how familiar you are with the unde...
... might want to use (we list a few of the more popular frameworks in the following section). with so many choices, it can become difficult to work out what framework provides the best starting point for your new web application. ...
...And 10 more matches
Handling common JavaScript problems - Learn web development
snippet in how to make an http request) so developers only have to write one simple bit of code (see jquery.ajax()). jquery (or whatever library you are using) will then handle the differences in the background, so you don't have to. things have improved significantly since then; modern browsers do a good job of supporting "classic javascript features", and the requirement to use such code has diminished as the requirement to support older browsers has lessened (although bear in mind that they have not gone away altogether). these days, most cross-browser javascript problems are seen: when poor-quality browser-sniffing code, feature-detection code, and vendor prefix usage block browsers from running code they could otherwise use just fine. when developers make use of new/nascent javascr...
... fixing general javascript problems as we said in the previous article on html/css, you should make sure your code is working generally, before going on to concentrate on the cross-browser issues. if you are not already familiar with the basics of troubleshooting javascript, you should study that article before moving on. there are a number of common javascript problems that you will want to be mindful of, such as: basic syntax and logic problems (again, check out troubleshooting javascript). making sure variables, etc. are defined in the correct scope, and you are not running into conflicts between items declared in different places (see function scope and conflicts). confusion about this, in terms of what scope it applies to, and therefore if its value is what you intended. you can r...
... homepage provides an online linter, which allows you to enter your javascript code on the left and provides an output on the right, including metrics, warnings, and errors. code editor plugins it is not very convenient to have to copy and paste your code over to a web page to check its validity several times. what you really want is a linter that will fit into your standard workflow with the minimum of hassle. many code editors have linter plugins, for example github's atom code editor has a jshint plugin available. to install it: install atom (if you haven't got an up-to-date version already installed) — download it from the atom page linked above. go to atom's preferences... dialog (e.g. by choosing atom > preferences... on mac, or file > preferences... on windows/linux) and cho...
...And 10 more matches
Linear-gradient Generator - CSS: Cascading Style Sheets
ml content <div id="container"> <div id="gradient-container" data-alpha="true"> </div> <div id="controls"> <div class="section"> <div class="title"> active point </div> <div class="property"> <div class="ui-input-slider" data-topic="point-position" data-info="position" data-unit="px" data-min="-1000" data-value="0" data-max="1000" data-sensivity="5"></div> <div id="delete-point" class="button"> delete point </div> </div> <div class="ui-color-picker" data-topic="picker"></div> </div> <div class="section"> <div class="title"> active axis </div> <div class="property"> ...
... <div data-value='px'> pixels (px) </div> <div data-value='%'> percentage (%) </div> </div> <div id="delete-axis" class="button"> delete line </div> </div> <div class="property"> <div class="ui-slider" data-topic="axis-rotation" data-info="rotation" data-min="-180" data-value="0" data-max="180"></div> </div> </div> <div id="tool-section" class="section"> <div class="title"> tool settings </div> <div class="property"> <div class="name"> alpha background </div> <div id="canvas-bg"></div> <div id="add-axis" class="button">...
... position: absolute; bottom: 0; right: 0; } [data-resize='both']:hover { cursor: nw-resize !important; } [data-resize='width']:hover { cursor: w-resize !important; } [data-resize='height']:hover { cursor: n-resize !important; } /** * main container */ #container { width: 1000px; height: 100%; display: table; margin: 0 auto; } #gradient-container { width: 450px; height: 250px; min-width: 8px; min-height: 8px; margin: 100px auto; border: 1px solid #ddd; position: relative; } #gradient-container[data-alpha="true"]:after { content: ""; width: 100%; height: 100%; background: url('images/canvas-pattern.png'); position: absolute; z-index: -1; } /** * gradient axis */ .gradient-axis { width: 125%; height: 4px; margin: -3px 0 0 0; border: 1px solid #ccc; posit...
...And 10 more matches
HTTP Index - HTTP
Web › HTTP › Index
s not match any of the origins permitted by the access-control-allow-origin header. 24 reason: cors header 'access-control-allow-origin' missing cors, corsmissingalloworigin, cross-origin, error, http, https, messages, reasons, security, console, troubleshooting the response to the cors request is missing the required access-control-allow-origin header, which is used to determine whether or not the resource can be accessed by content operating within the current origin. 25 reason: cors header ‘origin’ cannot be added cors, corsoriginheadernotadded, cross-origin, error, http, https, messages, reasons, security, console, troubleshooting the user agent was unable to add the required origin header to the http request. all cors requests must have an o...
... http conditional requests conditional requests, guide, http http has a concept of conditional requests, where the result, and even the success of a request, can be changed by comparing the affected resources with the value of a validator. such requests can be useful to validate the content of a cache, and sparing a useless control, to verify the integrity of a document, like when resuming a download, or when preventing to lose updates when uploading or modifying a document on the server. 45 http cookies advertising, browser, cookies, cookies article, guide, http, history, javascript, privacy, protocols, server, storage, web development, data, request, tracking an http cookie (web cookie, browser cookie) is a small piece of data that a server sends to the user...
...lient of its choice with the content-encoding response header. 52 accept-language accept-language, content negotiation, http, http header, reference, request header the accept-language request http header advertises which languages the client is able to understand, and which locale variant is preferred. (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. browsers set adequate values for this header according to their user interface language and even if a user can change it, this happens rarely (and is frowned upon as it leads to fingerprinting). 53 accept-patch ...
...And 10 more matches
Using Promises - JavaScript
you might see this ...
...ok down the chain for .catch() handlers or onrejected. this is very much modeled after how synchronous code works: try { const result = syncdosomething(); const newresult = syncdosomethingelse(result); const finalresult = syncdothirdthing(newresult); console.log(`got the final result: ${finalresult}`); } catch(error) { failurecallback(error); } this symmetry with asynchronous code culminates in the async/await syntactic sugar in ecmascript 2017: async function foo() { try { const result = await dosomething(); const newresult = await dosomethingelse(result); const finalresult = await dothirdthing(newresult); console.log(`got the final result: ${finalresult}`); } catch(error) { failurecallback(error); } } it builds on promises, e.g. dosomething() is the...
...finalresult = await dothirdthing(newresult); console.log(`got the final result: ${finalresult}`); } catch(error) { failurecallback(error); } } it builds on promises, e.g. dosomething() is the same function as before. you can read more about the syntax here. promises solve a fundamental flaw with the callback pyramid of doom, by catching all errors, even thrown exceptions and programming errors. this is essential for functional composition of asynchronous operations. promise rejection events whenever a promise is rejected, one of two events is sent to the global scope (generally, this is either the window or, if being used in a web worker, it's the worker or other worker-based interface). the two events are: rejectionhandled sent when a promise is rejected, after that reje...
...And 10 more matches
Web Performance
clickable? are pop-ups quick to load and display, and do they animate smoothly as they do so? web performance includes both objective measurements like time to load, frames per second, and time to become interactive, and subjective experiences of how long it felt like it took the content to load. the longer it takes for a site to respond, the more users will abandon the site. it is important to minimize the loading and response times and add additional features to conceal latency by making the experience as available and interactive as possible, as soon as possible, while asynchronously loading in the longer tail parts of the experience. there are tools, apis, and best practices that help us measure and improve web performance. we cover them in this section: key performance guides a...
...sitions/animations where possible. if your animations are really complex, you may have to rely on javascript-based animations instead.lazy loadinglazy loading is a strategy to identify resources as non-blocking (non-critical) and load these only when needed. it is a way of shorten the critical rendering path length, what would translate into improved page load times. navigation and resource timingsnavigation timings are metrics measuring a browser's document navigation events. resource timings are detailed network timing measurements regarding the loading of an application's resources.optimizing startup performanceregardless of platform, it's always a good idea to start up as quickly as possible. since that's a universal issue, we won't be focusing on it too much here. instead, we're goin...
...um) are two approaches for monitoring and providing insight into web performance. in this article we define and compare these two performance monitoring approaches.populating the page: how browsers worka developer should strive to achieve these two goals. ...
...And 10 more matches
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
e, type about:config into firefox’s location bar and open the preferences window; find the preferences listed in table 1 and double-click on them to set them accordingly. some of these preferences do not exist—to create them, right-click, select “new>boolean”, and type in the name and set the value accordingly. install the dom inspector the dom inspector is an extension that lets you examine html and xul dom tree structures, javascript objects and css properties, etc. this is not required for developing extensions, but it is handy to have around. install extensions for firefox from the mozilla add-ons website. optional - install firebug and chromebug chromebug is used by the firebug development team to develop firebug. you can use it to help debug firefox extensions as well as t...
...he target xul document overlays it with another xul document cross-package overlay: adding a cross manifest permits one xul file to overlay another without any xul-overlay instruction. figure 2: invoking a cross-package overlay (fixme: not really explicit and not a figure) conclusion this has been a brief introduction to chrome that probably leaves a lot of unanswered questions. if you keep in mind the following three points at the very least, the next section, developing a simple extension, should help flesh out your understanding. an extension’s gui, or chrome, can consist of three kinds of package: content, locale, and skin. use a cross-package overlay on top of browser.xul to add a button or menu item to the firefox browser window. the chrome manifest plays two important roles: ...
...r window. the chrome manifest plays two important roles: it registers the contents of the chrome packages, and invokes the cross-package overlay. developing a simple extension: hello world in this section, we will write an extremely simple “hello world” extension that only displays the time.3 phase 1: test install our first step will be to perform a test installation consisting of the minimum code needed to add a new menu item to the tools menu (figure 3). fixme: figure 3: menu after phase 1 complete source file structure first set up the work folders you’ll use to organize your extension’s source files. the folder can be wherever you want, but for the purposes of this guide, we’ll assume it’s at c:\extensions\helloworld . create folders and files in your work folder as...
...And 9 more matches
jspage - Archive of obsolete content
ilter($defined); },indexof:function(c,d){var a=this.length;for(var b=(d<0)?math.max(0,a+d):d||0;b<a;b++){if(this[b]===c){return b;}}return -1;},map:function(d,e){var c=[]; for(var b=0,a=this.length;b<a;b++){c[b]=d.call(e,this[b],b,this);}return c;},some:function(c,d){for(var b=0,a=this.length;b<a;b++){if(c.call(d,this[b],b,this)){return true; }}return false;},associate:function(c){var d={},b=math.min(this.length,c.length);for(var a=0;a<b;a++){d[c[a]]=this[a];}return d;},link:function(c){var a={}; for(var e=0,b=this.length;e<b;e++){for(var d in c){if(c[d](this[e])){a[d]=this[e];delete c[d];break;}}}return a;},contains:function(a,b){return this.indexof(a,b)!=-1; },extend:function(c){for(var b=0,a=c.length;b<a;b++){this.push(c[b]);}return this;},getlast:function(){return(this.length)?this[this.l...
...bind:b,arguments:a}); },bindwithevent:function(b,a){return this.create({bind:b,arguments:a,event:true});},attempt:function(a,b){return this.create({bind:b,arguments:a,attempt:true})(); },delay:function(b,c,a){return this.create({bind:c,arguments:a,delay:b})();},periodical:function(c,b,a){return this.create({bind:b,arguments:a,periodical:c})(); }});number.implement({limit:function(b,a){return math.min(a,math.max(b,this));},round:function(a){a=math.pow(10,a||0);return math.round(this*a)/a;},times:function(b,c){for(var a=0; a<this;a++){b.call(c,a,this);}},tofloat:function(){return parsefloat(this);},toint:function(a){return parseint(this,a||10);}});number.alias("times","each"); (function(b){var a={};b.each(function(c){if(!number[c]){a[c]=function(){return math[c].apply(null,[this].concat($a(argu...
...var a=0; a<this;a++){b.call(c,a,this);}},tofloat:function(){return parsefloat(this);},toint:function(a){return parseint(this,a||10);}});number.alias("times","each"); (function(b){var a={};b.each(function(c){if(!number[c]){a[c]=function(){return math[c].apply(null,[this].concat($a(arguments)));};}});number.implement(a); })(["abs","acos","asin","atan","atan2","ceil","cos","exp","floor","log","max","min","pow","sin","sqrt","tan"]);string.implement({test:function(a,b){return((typeof a=="string")?new regexp(a,b):a).test(this); },contains:function(a,b){return(b)?(b+this+b).indexof(b+a+b)>-1:this.indexof(a)>-1;},trim:function(){return this.replace(/^\s+|\s+$/g,"");},clean:function(){return this.replace(/\s+/g," ").trim(); },camelcase:function(){return this.replace(/-\d/g,function(a){return a.charat(...
...And 9 more matches
Table Layout Strategy - Archive of obsolete content
sictablelayoutstrategy::initialize). later the column widths are balanced by basictablelayoutstrategy::balancecolumnwidths or the fixed layout counter part. in the following the basic table layout strategy is discussed. the functionality is distributed over a large number of subroutines as shown in the chart below. the words the table layout is width oriented and knows the following widths: minimum content width - min the minimum width that is required to layout the content, all linebreak possibilities will be used percent width - pct the cell width specified in percent, fixed width - fix the cell width specified as px, mm etc., proportional width - prop the cell width specified via 1*, 2* etc. and the desired width - des the width the content could fill without any linebreaks.
...d as px, mm etc., proportional width - prop the cell width specified via 1*, 2* etc. and the desired width - des the width the content could fill without any linebreaks. cells can be members of colspans. these colspans have to distribute their space to the columns they include. this information is hold in the adjusted width's. due to this there are 10 width informations for every column. ...
...ortional width - prop the cell width specified via 1*, 2* etc. and the desired width - des the width the content could fill without any linebreaks. cells can be members of colspans. these colspans have to distribute their space to the columns they include. this information is hold in the adjusted width's. due to this there are 10 width informations for every column. ...
...And 9 more matches
Learn XPI Installer Scripting by Example - Archive of obsolete content
e written in javascript using xpinstall engine syntax defined in the xpinstall api reference. most installation scripts, including the one discussed here, take the following basic form (in pseudo-code and with links to the sections in which these installation steps are documented): initinstall(); if (verify_space()) { err = add_dirs_and_files; register_files; if (err==success) { performinstall() }; else { cancelinstall() }; } as you can see in the code listing, the verification process at the top is on lines 1 to 18; the file addition process, here part of the main installation block, is on lines 24 to 41; the registration part of the main installation block is on lines 42-58; and the execution at the end of the main block is on lines 59 to 71. if you choose not to register t...
...on process at the top is on lines 1 to 18; the file addition process, here part of the main installation block, is on lines 24 to 41; the registration part of the main installation block is on lines 42-58; and the execution at the end of the main block is on lines 59 to 71. ...
... end of the main block is on lines 59 to 71. if you choose not to register the installed software or do the verifications at the front end of the installation, then at a minimum, the install scripts mustinitialize, add the files to be installed, and execute. note also that when you call methods on the install--as you do so often in installation scripts (getfolder, initinstall, addfile, and performinstall are all examples of common install object methods)--the install object is implicit; like the window object in regular web page scripts, the install object does not need to be prefixed to the method. initializing the installation all installations must begin with initinstall(). the initinstall() method on the install object creates a new installation for the specified software and version. ...
...And 9 more matches
HTML text fundamentals - Learn web development
the eternal silence</h2> <p>our protagonist could not so much as a whisper out of the shadowy figure ...</p> <h3>the specter speaks</h3> <p>several more hours had passed, when all of a sudden the specter sat bolt upright and exclaimed, "please have mercy on my soul!"</p> it's really up to you what the elements involved represent, as long as the hierarchy makes sense. you just need to bear in mind a few best practices as you create such structures: preferably, you should use a single <h1> per page—this is the top level heading, and all others sit below this in the hierarchy. make sure you use the headings in the correct order in the hierarchy. don't use <h3> elements to represent subheadings, followed by <h2> elements to represent sub-subheadings—that doesn't make sense and will l...
...ucture let's jump straight in with a live example. in the example below, add elements to the raw text in the input field so that it appears as a heading and two paragraphs in the output field. if you make a mistake, you can always reset it using the reset button. if you get stuck, press the show solution button to see the answer. playable code <h2>live output</h2> <div class="output" style="min-height: 50px;"> </div> <h2>editable code</h2> <p class="a11y-label">press esc to move focus away from the code area (tab inserts a tab character).</p> <textarea id="code" class="input" style="min-height: 100px; width: 95%">my short story i am a statistician and my name is trish. my legs are made of cardboard and i am married to a fish.</textarea> <div class="playable-buttons"> <input id="re...
... all the list items: <ul> milk eggs bread hummus </ul> the last step is to wrap each list item in a <li> (list item) element: <ul> <li>milk</li> <li>eggs</li> <li>bread</li> <li>hummus</li> </ul> active learning: marking up an unordered list try editing the live sample below to create your very own html unordered list. ...
...And 9 more matches
An Overview of XPCOM
this chapter provides a quick tour of xpcom - an introduction to the basic concepts and technologies in xpcom and component development. the brief sections in this chapter introduce the concepts at a very high level, so that we can discuss and use them with more familiarity in the tutorial itself, which describes the creation of a mozilla component called weblock. ...
... be reused in different applications or that can be replaced to change the functionality of existing applications. xpcom not only supports component software development, it also provides much of the functionality that a development platform provides, such as: component management file abstraction object message passing memory management we will discuss the above items in detail in the coming chapters, but for now, it can be useful to think of xpcom as a platform for component development, in which features such as those listed above are provided. gecko although it is in some ways structurally similar to microsoft com, xpcom is designed to be used principally at the application level. the most important use of xpcom is within gecko, an open source, standards compliant, embeddable w...
...ents xpcom allows you to break up large software projects into smaller pieces known as components. they are usually contained in reusable binary libraries (a dll on windows, for example, or a dso on unix), which can include one or more components. when two or more related components are grouped together in a binary library, the library is referred to as a module. modular, component-based programming makes software easier to develop and maintain and has some well-known advantages: benefit description reuse modular code can be reused in other applications and other contexts. updates you can update components without having to recompile the whole application. performance when code is modularized, modules that are not necessary right away can be ...
...And 9 more matches
mozIStorageStatement
(firefox 3.6 / thunderbird 3.1 / fennec 1.0) for an introduction on how to use this interface, see the storage overview document. ...
...me(in unsigned long acolumnindex); unsigned long getcolumnindex(in autf8string aname); void reset(); astring escapestringforlike(in astring avalue, in wchar aescapechar); void bindparameters(in mozistoragebindingparamsarray aparameters); mozistoragebindingparamsarray newbindingparamsarray(); void bindutf8stringparameter(in unsigned long aparamindex, in autf8string avalue); void bindstringparameter(in unsigned long aparamindex, in astring avalue); void binddoubleparameter(in unsigned long aparamindex, in double avalue); void bindint32parameter(in unsigned long aparamindex, in long avalue); void bindint64parameter(in unsigned long aparamindex, in long long avalue); void bindnullparameter(in unsi...
...ring avalue); void bindstringparameter(in unsigned long aparamindex, in astring avalue); void binddoubleparameter(in unsigned long aparamindex, in double avalue); void bindint32parameter(in unsigned long aparamindex, in long avalue); void bindint64parameter(in unsigned long aparamindex, in long long avalue); void bindnullparameter(in unsigned long aparamindex); void bindblobparameter(in unsigned long aparamindex, [array,const,size_is(avaluesize)] in octet avalue, in unsigned long avaluesize); mozistoragependingstatement executeasync(mozistoragestatementcallback acallback); boolean executestep(); boolean step(); void execute(); attributes attribute type description column...
...And 9 more matches
Web Video Text Tracks Format (WebVTT) - Web APIs
vtt - this file has no cues. example 3 - common webvtt example with a header and cues webvtt - this file has cues. 14 00:01:14.815 --> 00:01:18.114 - what? - where are we now? 15 00:01:18.171 --> 00:01:20.991 - this is big bat country. 16 00:01:21.058 --> 00:01:23.868 - [ bats screeching ] - they won't get in your hair. they're after the bugs. inner structure of a webvtt file let's re-examine one of our previous examples, and look at the cue structure in a bit more detail. webvtt 00:01.000 --> 00:04.000 - never drink liquid nitrogen. 00:05.000 --> 00:09.000 - it will perforate your stomach. - you could die. in the case of each cue: the first line is started with a time, which is the starting time for showing the text that appears underneath. on the same line, we then have a ...
...start with a hyphen (-), each containing part of the text track to be shown. we can also place comments in our .vtt file, to help us remember important information about the parts of our file. these should be on separate lines, starting with the string note. you'll find more about these in the below section. it is important to not use "extra" blank lines within a cue, for example between the timings line and the cue payload. webvtt is line based; a blank line will close the cue. webvtt comments comments are an optional component that can be used to add information to a webvtt file. comments are intended for those reading the file and are not seen by users. comments may contain newlines but cannot contain a blank line, which is equivalent to two consecutive newlines. a blank line signifie...
... 00:00:04.000 --> 00:00:06.500 position:45%,line-right align:center size:35% what are you waiting for? webvtt cues a cue is a single s...
...And 9 more matches
Geometry and reference spaces in WebXR - Web APIs
provided here to cover how the physical position and orientation of the user's head, as well as potentially other parts of their body such as the hands, are mapped into the digital world, as well as how the relative positions of both physical and virtual objects are tracked as they move around, so that the scene can be properly rendered and composited. fundamentals of 3d geometry while we'll examine here the required math operations used to compute the positions, orientations, and movement of objects in virtual space—plus the need to integrate the human viewer of the scene into the mix—a thorough introduction to geometry and the use of matrices and vectors to manage 3d representations of a scene is well beyond the scope of what can be accomplished in this article. you can learn more abo...
... before discussing the details of the geometry of the 3d space used by webxr, it's first useful to understand the units of measure that are applied to the 3d world. lengths and distances webgl measures all distances and lengths in meters. webxr inherits this standard, as well as the fact that the world is a cube two meters wide, two meters tall, and two meters deep. each of the three axes has a minimum value of -1.0 and a maximum of 1.0, with the center of the cube located at (0, 0, 0). this two cubic meter space encompasses the entire universe for the purposes of your code. everything you draw must have its coordinates mapped to fit into this space, either explicitly within your code, or by using a transform to adjust the coordinates of all vertices. the most efficient way, of course, i...
...n the two units for measuring angles. ...
...And 9 more matches
Background audio processing using AudioWorklet - Web APIs
ps. implementing your audio processing algorithm using webassembly can make it perform markedly better. high level overview before we start looking at the use of audioworklet on a step-by-step basis, let's start with a brief high-level overview of what's involved. create module that defines a audio worklet processor class, based on audioworkletprocessor which takes audio from one or more incoming sources, performs its operation on the data, and outputs the resulting audio data. access the audio context's audioworklet through its audioworklet property, and call the audio worklet's domxref("worklet.addmodule", "addmodule()")}} method to install the audio worklet processor module. as needed, create audio processing nodes by passing the processor's name (which is defined by the module) to ...
...sing a javascript module that defines and installs the custom audio processor class. structure of an audio worklet processor an audio worklet processor is a javascript module which consists of the following: a javascript class which defines the audio processor. this class extends the audioworkletprocessor class. the audio processor class must implement a process() method, which receives incoming audio data and writes back out the data as manipulated by the processor. the module installs the new audio worklet processor class by calling registerprocessor(), specifying a name for the audio processor and the class that defines the processor. a single audio worklet processor module may define multiple processor classes, registering each of them with individual calls to registerprocessor()...
...r, for example) is represented as a float32array whose values are the individual audio samples. by specification, each block of audio your process() function receives contains 128 frames (that is, 128 samples for each channel), but it is planned that this value will change in the future, and may in fact vary depending on circumstances, so you should always check the array's length rather than assuming a particular size. it is, however, guaranteed that the inputs and outputs will have the same block length. each input can have a number of channels. a mono input has a single channel; stereo input has two channels. surround sound might have six or more channels. so each input is, in turn, an array of channels. that is, an array of float32array objects. then, there can be multiple inputs, so th...
...And 9 more matches
Border-image generator - CSS: Cascading Style Sheets
ass="separator"></div> <div class="property"> <div class="name">draggable</div> <div class="ui-checkbox" data-topic='drag-subject'></div> </div> <div class="property right"> <div class="name">section height</div> <div class="ui-input-slider" data-topic="preview-area-height" data-min="400" data-max="1000"> </div> </div> </div> <div id="preview_section" class="group section"> <div id="subject"> <div class="guideline" data-axis="y" data-topic="slice-top"></div> <div class="guideline" data-axis="x" data-topic="slice-right"></div> <div class="guideline" data-axis="y" data-topi...
..."> <div class="ui-input-slider" data-topic="font-size" data-info="em size" data-unit="px" data-value="12" data-sensivity="3"> </div> </div> <div class="property"> <div class="ui-input-slider" data-topic="preview-width" data-info="width" data-unit=" px" data-min="10" data-max="10000" data-sensivity="3"></div> </div> <div class="property"> <div class="ui-input-slider" data-topic="preview-height" data-info="height" data-unit=" px" data-min="10" data-max="10000" data-sensivity="3"> </div> </div> </div> <div id="output" cl...
...ckground-position: center center; } #remote-url { width: 200px; height: 23px; margin: 10px; padding: 0 5px; border: 1px solid #379b4a; border-radius: 2px; float: left; transition: width 0.5s; } #remote-url:focus { box-shadow: 0px 0px 3px -1px #379b4a; /*#68ace8; */ border-color: rgba(55, 155, 74, 0.5); width: 450px; } /* * visible area */ #preview_section { position: relative; min-height: 400px; } /* image control */ #subject { width: 300px; height: 300px; background-repeat: no-repeat; background-size: 100%; background-color: #fff; border: 1px solid #ccc; position: absolute; z-index: 10; top: 15%; left: 10%; box-shadow: 0 0 3px 0 #bababa; transition-property: width, height; transition-duration: 0.1s; } #subject .guideline { background-color: rgba(255, 25...
...And 9 more matches
Event reference
o be processed. canplay the browser can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content. canplaythrough the browser estimates it can play the media up to its end without stopping for content buffering. complete the rendering of an offlineaudiocontext is terminated. durationchange the duration attribute has been updated. emptied the media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it. ended playback has stopped because the end of the media was reached. loadeddata the first frame of the media has fin...
...een paused. play playback has begun. playing playback is ready to start after having been paused or delayed due to lack of data. ratechange the playback rate has changed. seeked a seek operation completed. seeking a seek operation began. ...
...ot forthcoming. suspend media data loading has been suspended. timeupdate the time indicated by the currenttime attribute has been updated. volumechange the volume has changed. waiting playback has stopped because of a temporary lack of data. progress events event name fired when abort progression has been terminated (not due to an error). error progression has failed. load progression has been successful. loadend progress has stopped (after "error", "abort", or "load" have been dispatched). loadstart progress has begun. progress in progress. timeout progression is terminated due to preset time expiring. storage events change ...
...And 9 more matches
HTML attribute: step - HTML: Hypertext Markup Language
Web › HTML › Attributes › step
tetime-local, number and range types, the step attribute is a number that specifies the granularity that the value must adhere to or the keyword any. the step sets the stepping interval when clicking up and down spinner buttons, moving a slider left and right on a range, and validating the different date types. if not explicitly included, step defaults to 1 for number and range, and 1 unit type (minute, week, month, day) for the date/time input types. the value can must be a positive number - integer or float -- or the special value any, which means no stepping is implied, and any value is allowed (barring other constraints, such as min and max). the default stepping value for number inputs is 1, allowing only integers to be entered, unless the stepping base is not an integer. the default s...
... can must be a positive number - integer or float -- or the special value any, which means no stepping is implied, and any value is allowed (barring other constraints, such as min and max). the default stepping value for number inputs is 1, allowing only integers to be entered, unless the stepping base is not an integer. the default stepping value for time is 1 second, with 900 being equal to 15 minutes. ...
...ue is allowed (barring other constraints, such as min and max). the default stepping value for number inputs is 1, allowing only integers to be entered, unless the stepping base is not an integer. the default stepping value for time is 1 second, with 900 being equal to 15 minutes. ...
...And 9 more matches
<input type="checkbox"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › checkbox
s checkboxes allow you to turn single values on and off. where multiple controls exist, radio buttons allow one to be selected out of them all, whereas checkboxes allow multiple values to be selected. value a domstring representing the value of the checkbox. events change and input supported common attributes checked idl attributes checked, indeterminate and value methods select() value a domstring representing the value of the checkbox. this is never seen on the client-side, but on the server this is the value given to the data submitted with the checkbox's name. take the following example: <form> <div> <input type="checkbox" id="subscribenews" name="subscribe" value="newsletter"> <label for="subscribenews">subs...
...u could include an <input type="hidden"> inside the form with the same name and value, generated by javascript perhaps. additional attributes in addition to the common attributes shared by all <input> elements, "checkbox" inputs support the following attributes: attribute description checked boolean; if present, the checkbox is toggled on by default indeterminate a boolean which, if present, indicates that the value of the checkbox is indeterminate rather than true or false value the string to use as the value of the checkbox when submitting the form, if the checkbox is currently toggled on checked a boolean attribute indicating whether or not this checkbox is checked by default (when the page loads). it does not indicate whether...
...note: unlike other input controls, a checkboxes value is only included in the submitted data if the checkbox is currently checked. if it is, then the value of the checkbox's value attribute is reported as the input's value. unlike other browsers, firefox by default persists the dynamic checked state of an <input> across page loads. use the autocomplete attribute to control this feature. indeterminate if the indeterminate attribute is present on the <input> element defining a checkbox, the checkbox's value is neither true nor false, but is instead indeterminate, meaning that it's state cannot be determined or stated in pure binary terms. this may happen, for instance, if the state of the checkbox depends on multiple other checkboxes, and those checkboxes have different values. essentially...
...And 9 more matches
<input type="date"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › date
timestamp this code finds the first <input> element whose type is date, and sets its value to 2017-06-01 (june 1st, 2017). it then reads that value back in string and number formats. additional attributes along with the attributes common to all <input> elements, date inputs have the following attributes: attribute description max the latest acceptable date min the earliest acceptable date step the stepping interval, when clicking up and down spinner buttons and validating the date max the latest date to accept. if the value entered into the element occurs afterward, the element fails constraint validation. if the value of the max attribute isn't a possible date string in the format yyyy-mm-dd, then the element has no maximum date...
...ate step the stepping interval, when clicking up and down spinner buttons and validating the date max the latest date to accept. if the value entered into the element occurs afterward, the element fails constraint validation. if the value of the max attribute isn't a possible date string in the format yyyy-mm-dd, then the element has no maximum date value. ...
...ating the date max the latest date to accept. if the value entered into the element occurs afterward, the element fails constraint validation. if the value of the max attribute isn't a possible date string in the format yyyy-mm-dd, then the element has no maximum date value. if both the max and min attributes are set, this value must be a date string later than or equal to the one in the min attribute. min the earliest date to accept. ...
...And 9 more matches
x - SVG: Scalable Vector Graphics
Web › SVG › Attribute › x
<rect x="120" y="20" width="60" height="60" /> <rect x="220" y="20" width="60" height="60" /> </svg> altglyph warning: as of svg2 <altglyph> is deprecated and shouldn't be used. for <altglyph>, x defines the x-axis coordinate of the alternate glyph. value list of <length> default value none animatable yes feblend for <feblend>, x defines the minimum x coordinate for the rendering area of the primitive. value <length> | <percentage> default value 0% animatable yes fecolormatrix for <fecolormatrix>, x defines the minimum x coordinate for the rendering area of the primitive. value <length> | <percentage> default value 0% animatable yes fecomponenttransf...
...he primitive. value <length> | <percentage> default value 0% animatable yes fecolormatrix for <fecolormatrix>, x defines the minimum x coordinate for the rendering area of the primitive. value <length> | <percentage> default value 0% animatable yes fecomponenttransfer for <fecomponenttransfer>, x defines the minimum x coordinate for the rendering area of the primitive. value <length> | <percentage> default value 0% animatable yes fecomposite for <fecomposite>, x defines the minimum x coordinate for the rendering area of the primitive. value <length> | <percentage> default value 0% animatable yes feconvolvematrix for...
... area of the primitive. value <length> | <percentage> default value 0% animatable yes fecomposite for <fecomposite>, x defines the minimum x coordinate for the rendering area of the primitive. value <length> | <percentage> default value 0% animatable yes feconvolvematrix for <feconvolvematrix>, x defines the minimum x coordinate for the rendering area of the primitive. value <length> | <percentage> default value 0% animatable yes fediffuselighting for <fediffuselighting>, x defines the minimum x coordinate for the rendering area of the primitive. value <length> | <percentage> default value 0% animatable yes fedisplac...
...And 9 more matches
y - SVG: Scalable Vector Graphics
Web › SVG › Attribute › y
<rect y="120" x="20" width="60" height="60" /> <rect y="220" x="20" width="60" height="60" /> </svg> altglyph warning: as of svg2 <altglyph> is deprecated and shouldn't be used. for <altglyph>, y defines the y-axis coordinate of the alternate glyph. value list of <length> default value none animatable yes feblend for <feblend>, y defines the minimum y coordinate for the rendering area of the primitive. value <length> | <percentage> default value 0% animatable yes fecolormatrix for <fecolormatrix>, y defines the minimum y coordinate for the rendering area of the primitive. value <length> | <percentage> default value 0% animatable yes fecomponenttransf...
...he primitive. value <length> | <percentage> default value 0% animatable yes fecolormatrix for <fecolormatrix>, y defines the minimum y coordinate for the rendering area of the primitive. value <length> | <percentage> default value 0% animatable yes fecomponenttransfer for <fecomponenttransfer>, y defines the minimum y coordinate for the rendering area of the primitive. value <length> | <percentage> default value 0% animatable yes fecomposite for <fecomposite>, y defines the minimum y coordinate for the rendering area of the primitive. value <length> | <percentage> default value 0% animatable yes feconvolvematrix for...
... area of the primitive. value <length> | <percentage> default value 0% animatable yes fecomposite for <fecomposite>, y defines the minimum y coordinate for the rendering area of the primitive. value <length> | <percentage> default value 0% animatable yes feconvolvematrix for <feconvolvematrix>, y defines the minimum y coordinate for the rendering area of the primitive. value <length> | <percentage> default value 0% animatable yes fediffuselighting for <fediffuselighting>, y defines the minimum y coordinate for the rendering area of the primitive. value <length> | <percentage> default value 0% animatable yes fedisplac...
...And 9 more matches
Advanced text formatting - Learn web development
tion lists; add elements to the raw text in the input field so that it appears as a description list in the output field. 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. if you get really stuck, press the show solution button to see the answer. playable code <h2>live output</h2> <div class="output" style="min-height: 50px;"> </div> <h2>editable code</h2> <p class="a11y-label">press esc to move focus away from the code area (tab inserts a tab character).</p> <textarea id="code" class="input" style="min-height: 100px; width: 95%"> bacon the glue that binds the world together. eggs the glue that binds the cake together. coffee the drink that gets the world running in the morning. a light brown color.</...
...d for short quotations that don't require paragraph breaks.</q> -- <a href="/docs/web/html/element/q"> <cite>mdn q page</cite></a>.</p> citations are styled in italic font by default. active learning: who said that? time for another active learning example! in this example we'd like you to: turn the middle paragraph into a blockquote, which includes a cite attribute. ...
...the need to eliminate negative self talk" in the third paragraph into an inline quote, and include a cite attribute. wrap the title of each source in <cite> tags and turn each one into a link to that source. the citation sources you need are: http://www.brainyquote.com/quotes/authors/c/confucius.html for the confucius quote http://www.affirmationsforpositivethinking.com for "the need to eliminate negative self talk". if you make a mistake, you can always reset it using the reset button. if you get really stuck, press the show solution button to see the answer. ...
...And 8 more matches
Aprender y obtener ayuda - Learn web development
ere are two main ways in which your brain learns things — focused and diffuse learning: focused learning is what you might more traditionally associate with academic subjects. you concentrate deeply on a low-level topic and solving the specific problems that it brings. you are focused on a narrow area. diffuse learning is more to do with high-level thinking around a wider area. you let your mind wander more widely, and seemingly make random connections between different things. this is more the kind of thinking you do while you are in the shower, or during a coffee break. from the studies that neuroscientists have done on brain activity, we have found out that you can't really engage in both ways of learning — or thinking — at once. so which one should you choose? you might think ...
...roblem, but then figure out the answer when you go for a coffee break (or a walk). you might: know how to fix problem a with tool a. know how to fix problem b with tool b. not know how to fix problem c. let's say you focus on problem c for a while and get frustrated because you can't think how to solve it. but then after going on a walk to get some fresh air, you may well find that as your mind wanders, you suddenly make a connection between tool a and tool b, and realize that you can use them together to fix problem c! it isn't always this simple, but it is also surprising how many times this does happen. this also highlights the importance of taking regular breaks when you are studying in front of the computer. different learning materials it is also worth looking at the different ...
...zilladeveloper, and google chromedevelopers providing many useful videos. many people prefer textual articles for more in-depth learning and reference material, and videos for quick explanations of concepts and new features, but it is really up to you what you prefer to learn from. there is no right and wrong answer here. interactive code playgrounds you might be the kind of person that prefers minimal instructions and would prefer to jump straight in and start playing with code. this is also a reasonable approach, and some learning sites tend to favor it. codecademy for example is a learning site where the tutorials mainly consist of interactive code editors where you have to directly write code and see if the desired result was achieved. many mdn web docs reference pages provide interact...
...And 8 more matches
Getting started with Ember - Learn web development
previous overview: client-side javascript frameworks next in our first ember article we will look at how ember works and what it's useful for, install the ember toolchain locally, create a sample app, and then do some initial setup to get it ready for development. prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line. a deeper understanding of modern javascript features (such as classes, modules, etc), will be extremely beneficial, as ember makes heavy use of them. objective: to learn how to install ember, and create a starter app. introducing ember ember is a component-service framework that focuses on the overall web applica...
...ember also has immense backwards and forwards compatibility to help businesses stay up to date with the latest versions of ember and latest community-driven conventions. ...
... help reduce the menial differences between apps — a common goal among all opinionated frameworks, across any language and ecosystem. developers are then more easily able to switch between projects and applications without having to completely relearn the architecture, patterns, conventions, etc. as you work through this series of tutorials, you'll notice ember's opinions — such as strict naming conventions of component files. how does ember relate to vanilla javascript? ember is built on javascript technologies and is a thin layer on top of traditional object-oriented programming, while still allowing developers to utilize functional programming techniques. ember makes use of two main syntaxes: javascript (or optionally, typescript) ember's own templating language, which is loos...
...And 8 more matches
Introduction to automated testing - Learn web development
to handle this efficiently, you should become familiar with automation tools. in this article, we look at what is available, how to use task runners, and how to use the basics of commercial browser test automation apps such as lambdatest, sauce labs, browserstack, and testingbot. prerequisites: familiarity with the core html, css, and javascript languages; an idea of the high level principles of cross-browser testing. ...
...ed at in previous articles manually can be a real pain. fortunately, there are tools to help us automate some of this pain away. there are two main ways in which we can automate the tests we've been talking about in this module: use a task runner such as grunt or gulp, or npm scripts to run tests and clean up code during your build process. this is a great way to perform tasks like linting and minifying code, adding in css prefixes or transpiling nascent javascript features for maximum cross-browser reach, and so on. use a browser automation system like selenium to run specific tests on installed browsers and return results, alerting you to failures in browsers as they crop up. commercial cross-browser testing apps like lambdatest, sauce labs, browserstack, and testingbot are based on sel...
... the ones mentioned above. note: the above two categories are not mutually exclusive. it is possible to set up a task runner to access a service like sauce labs, or lambdatest via an api, run cross browser tests, and return results. we will look at this below as well. 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. for example, this could be every time you save a file, or at some other point. inside this section we'll look at how to automate task running with node and gulp, a beginner-friendly option. setting up node and npm most tools these days are based on node.js, so you'll need ...
...And 8 more matches
An overview of NSS Internals
a high-level overview to the internals of network security services (nss) software developed by the mozilla.org projects traditionally used its own implementation of security protocols and cryptographic algorithms, originally called netscape security services, nowadays called network security services (nss). nss is a library written in the c programming language. ...
... nss offers lots of functionality; we'll walk through the list of modules, design principles, and important relevant standards. ...
... nss offers lots of functionality; we'll walk through the list of modules, design principles, and important relevant standards. ...
...And 8 more matches
Python binding for NSS
.com. additional contributors are: miloslav trmač mitr@redhat.com bohuslav kabrda slavek@redhat.com the python-nss binding is still young despite having been utilized in several major software projects. thus it's major version number is still at zero. this is primarily so the developers can make changes to the api as experiece grows with it. for example it is already known there are some naming inconsistencies. elments of the api are probably not ideally partitioned into proper namespaces via python modules. some functionality and interface have already been deprecated due to lessons learned. thus at some point in the future when it is felt the api has solidified and been further proven in the field a 1.0 release will be made. at that point in time existing users of the python-nss api ...
... allow custom include root in setup.py as command line arg. add tls chacha20 poly1305 constants. remove checks for whether a socket is open for reading. it's not possible for the binding to know in all cases, especially if the socket is created from an xternal socket passed in. the following module functions were added: ...
...y1305_sha256 release 1.0.0beta1 release date 2016-02-16 scm tag pynss_release_1_0_0beta1 source download https://ftp.mozilla.org/pub/mozilla.org/security/python-nss/releases/pynss_release_1_0_0beta1/src/ change log the primary enhancement in this version is support for python3. ...
...And 8 more matches
nsDependentCString
subclass of nststring that restricts string value to an immutable character sequence. this class does not own its data, so the creator of objects of this type must take care to ensure that a nstdependentstring continues to reference valid memory for the duration of its use. ...
... compare equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii ...
...operator+= insert cut setcapacity setlength truncate getdata getmutabledata setisvoid stripchar base classes nscstring data members no public members. methods constructors nsdependentcstring(const char*, const char*) - source parameters char* start a pointer to the start of the string. must not be null. char* end a pointer to the string's null terminator. must not be null. nsdependentcstring(const char*, pruint32) - source parameters char* data a pointer to the string. must not be null. pruint32 length the length of the string. nsdependentcstring(const char*) - source constructs an nsdependentstring when you don't know the length in advance. instead ns_strlen is used to measure the length. parameters char* data a pointer to the string. mu...
...And 8 more matches
Mail composition back end
lso have the ability to save rfc822 files to disk, should you need this data for some reason. included in this functionality is the code to copy the messages to the appropriate locations after delivery (i.e. a "sent" folder) as well as the ability to store messages for features like "drafts" and "templates". several (but not all) of these interfaces are specified in idl. this will change in the coming weeks and allow for developers to write javascript to take advantage of the back end services. also, i will talk about some features though they may not be complete as of yet. i will try to make comments for these exceptions. sending messages the primary responsibility of the back end is for the creation and sending of rfc822 messages. the interface that accomplishes this ...
...nsieditorshell *aeditor, - the editor object for the mail compose operation. if this is not null, the body will be extracted from this object and any embedded objects or links will be sent as part of the message in mhtml nsimsgidentity *auseridentity, - the user identity for the person doing the send operation. this will be needed to determine the appropriate folder for copy operations. nsimsgcompfields *fields, - the message composition fields. this will contain all of the relevant header information for message creation prbool digest_p, - this is a flag that says that most of the documents we are attaching are themselves messages, and so we should ge...
...mpfields *fields, - the message composition fields. this will contain all of the relevant header information for message creation prbool digest_p, - this is a flag that says that most of the documents we are attaching are themselves messages, and so we should generate a multipart/digest container instead of multipart/mixed. (it's a minor difference.) prbool dont_deliver_p, - if "dont_deliver_p" is false, then we actually deliver the message to the smtp and/or nntp server nsmsgdelivermode mode, - mode is the delivery mode. this can be set for the various modes of delivery. these can include nsmsgdelivernow, nsmsgqueueforlater, nsmsgsave, nsmsgsav...
...And 8 more matches
Rendering and the WebXR frame animation callback - Web APIs
by calling the xrsession method requestanimationframe(), providing a callback function, mydrawframe(), whose job is to render the frame. note that this code doesn't have a loop! instead, the frame rendering code—in this case, a function named mydrawframe()—is responsible for scheduling time to draw another frame by once again calling requestanimationframe(). refresh rate and frame rate assuming you've called the xrsession method requestanimationframe() since the last time the screen refreshed, the browser will call your frame renderer callback every time it's ready to repaint your app or site window. in this context, "repaint" simply means the process of ensuring that the screen's displayed content matches what the dom and the elements within are trying to present at the moment. harda...
...hen your callback returns, the browser transfers that backbuffer to the display or xr device, along with anything else that's changed since the last time the screen was refreshed. historically, displays have refreshed 60 times per second. 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. this figure goes by a number of different names, but they're all equivalent or nearly so: refresh rate vertical refresh rate vertical blanking rate (vbl) vertical sync rate vertical refresh rate there are other similar terms used as well, but regardless of what it's called, the unit of measurement applied is the hertz, or hz. a display that refreshes 60 times per second has a ...
...of the space horizontally), we first need to render the scene from, say, [-0.032, 2.0, 0.0] (32mm to the left of center) and then render it again at [0.032, 2.0, 0.0]. (32mm right of center) this way, we place the positions of the viewer's eyes at an average human pupillary distance of 64mm. that distance (or whatever pupillary distance the xr system is configured to use) is enouigh to allow our minds to see just enough difference due to retinal disparity (the difference in what each retina sees) and the parallax effect to allow our brains to calculate the distance to and depth of objects, thus enabling us to percieve three dimensions despite our retinas only being 2d surfaces. this is illustrated in the diagram below, in which we see how each eye perceives a die located directly in front o...
...And 8 more matches
Advanced techniques: Creating and sequencing audio - Web APIs
we're going to introduce sample loading, envelopes, filters, wavetables, and frequency modulation. if you're familiar with these terms and you're looking for an introduction to their application within with the web audio api, you've come to the right place. demo we're going to be looking at a very simple step sequencer: in practice this is easier to do with a library — the web audio api was built to be built upon. if you are about to embark on building something more complex, tone.js would be a good place to start. ...
...lding something more complex, tone.js would be a good place to start. however, we want to demonstrate how to build such a demo from first principles, as a learning exercise. note: you can find the source code on github as step-sequencer; see the step-sequencer running live also. the interface consists of master controls, which allow us to play/stop the sequencer, and adjust the bpm (beats per minute) to speed up or slow down the "music". there are four different sounds, or voices, which can be played. each voice has four buttons, which represent four beats in one bar of music. when they are enabled the note will sound. when the instrument plays, it will move across this set of beats and loop the bar. each voice also has local controls, which allow you to manipulate the effects or parame...
...is is great, but wouldn't it be nice if we had an amplitude envelope to go with it? let's create a simple one so we get used to the methods we need to create an envelope with the web audio api. let's say our envelope has attack and release. ...
...And 8 more matches
ARIA Test Cases - Accessibility
ers. for more up-to-date examples, see the openajaxalliance aria examples page. or copy-paste: http://oaa-accessibility.org/examples/ for each example we test the "expected" results with assistive technologies, for each browser that at supports wai-aria in. where a failure occurs we will test the browser for api incorrectness, using tools such as msaa inspect. this must be done in order to determine where to file a bug (browser or at). there are several purposes for providing this information: help browser vendors provide correct implementations help at vendors provide correct implementations inform authors as to what actually works reliably in general we're testing with the latest public releases. however, where things don't work we may test with nightly builds if they are availabl...
... several purposes for providing this information: help browser vendors provide correct implementations help at vendors provide correct implementations inform authors as to what actually works reliably in general we're testing with the latest public releases. however, where things don't work we may test with nightly builds if they are available, in order to show what is already fixed in upcoming releases. we can add more screen readers if people are willing to step up and provide test results for them. tested ua/at combinations: dragon 10 with firefox 3 and ie 8 beta 2 jaws 9 & 10 with firefox 3 jaws 9 & 10 with ie beta 2 nvda 0.6p2 with firefox 3 orca with firefox 3 window-eyes 7 with ie 8 beta 2 and firefox 3 voiceover (leopard) with safari 4.0.2 zoom (leopard) with safari...
...r treats any progress updates. the live region markup should not affect how the progress updates are presented. (al) if the screen reader provides a keystroke to announce the current progress, this should work with an aria progressbar as well. jaws - jaws announces the level of progress at each time interval the user selects in jaws configuration. ...
...And 8 more matches
grid-template-columns - CSS: Cascading Style Sheets
y. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...e-columns: 100px 1fr; grid-template-columns: [linename] 100px; grid-template-columns: [linename1] 100px [linename2 linename3]; grid-template-columns: minmax(100px, 1fr); grid-template-columns: fit-content(40%); grid-template-columns: repeat(3, 200px); grid-template-columns: subgrid; /* <auto-track-list> values */ grid-template-columns: 200px repeat(auto-fill, 100px) 300px; grid-template-columns: minmax(100px, max-content) repeat(auto-fill, 200px) 20%; grid-template-columns: [linename1] 100px [linename2] repeat(auto-fit, [linename3 linename4] 300px) 100px; grid-template-columns: [linename1 linename2] 100px repeat(auto-fit, [linename1] 300px) [linename3]; /* global values */ grid-template-columns: inhe...
...x) 100px; grid-template-columns: [linename1 linename2] 100px repeat(auto-fit, [linename1] 300px) [linename3]; /* global values */ grid-template-columns: inherit; grid-template-columns: initial; grid-template-columns: unset; values none indicates that there is no explicit grid. any columns will be implicitly generated and their size will be determined by the grid-auto-columns property. <length> a non-negative length, giving the width of the column. <percentage> is a non-negative <percentage> value relative to the inline size of the grid container. if the size of the grid container depends on the size of its tracks, then the percentage must be treated as auto. the intrinsic size contributions of the track may be adjusted to the size of t...
...And 8 more matches
grid-template-rows - CSS: Cascading Style Sheets
ithub repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...ist> values */ grid-template-rows: 100px 1fr; grid-template-rows: [linename] 100px; grid-template-rows: [linename1] 100px [linename2 linename3]; grid-template-rows: minmax(100px, 1fr); grid-template-rows: fit-content(40%); grid-template-rows: repeat(3, 200px); grid-template-rows: subgrid; /* <auto-track-list> values */ grid-template-rows: 200px repeat(auto-fill, 100px) 300px; grid-template-rows: minmax(100px, max-content) repeat(auto-fill, 200px) 20%; grid-template-rows: [linename1] 100px [linename2] repeat(auto-fit, [linename3 linename4] 300px) 100px; grid-template-rows: [linename1 linename2] 100px repeat(auto-fit, [linename1] 300px) [linename3]; /* global values */ grid-template-rows: inherit; grid...
...inename1] 300px) [linename3]; /* global values */ grid-template-rows: inherit; grid-template-rows: initial; grid-template-rows: unset; this property may be specified as: either the keyword value none or a <track-list> value or an <auto-track-list> value. values none is a keyword meaning that there is no explicit grid. any rows will be implicitly generated and their size will be determined by the grid-auto-rows property. <length> is a non-negative length. <percentage> is a non-negative <percentage> value, relative to the block size of the grid container. if the size of the grid container depends on the size of its tracks, then the percentage must be treated as auto. the intrinsic size contributions of the track may be adjusted to the size of the grid container, and increase ...
...And 8 more matches
<input type="month"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › month
the <datalist> provides ...
... the latest year and month, in the string format discussed in the value section above, to accept. if the value entered into the element exceeds this, the element fails constraint validation. if the value of the max attribute isn't a valid string in "yyyy-mm" format, then the element has no maximum value. this value must specify a year-month pairing later than or equal to the one specified by the min attribute. min the latest year and month to accept, in the same "yyyy-mm" format described above. if the value of the element is less than this, the element fails constraint validation. if a value is specified for min that isn't a valid year and month string, the input has no minimum value. this value must be a year-month pairing which is earlier than or equal to the one specified by the max a...
...he value of the htmlinputelement.value property. note: because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified. step the step attribute is a number that specifies the granularity that the value must adhere to, or the special value any, which is described below. only values which are equal to the basis for stepping (min if specified, value otherwise, and an appropriate default value if neither of those is provided) are valid. a string value of any means that no stepping is implied, and any value is allowed (barring other constraints, such as min and max). note: when the data entered by the user doesn't adhere to the stepping configuration, the user agent may round to the nearest valid value, preferring number...
...And 8 more matches
<input type="password"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › password
boards. note: any forms involving sensitive information like passwords (e.g. login forms) should be served over https; many browsers now implement mechanisms to warn against insecure login forms; see insecure passwords. value a domstring representing a password, or empty events change and input supported common attributes autocomplete, inputmode, maxlength, minlength, pattern, placeholder, readonly, required, and size idl attributes selectionstart, selectionend, selectiondirection, and value methods select(), setrangetext(), and setselectionrange() value the value attribute contains a domstring whose value is the current contents of the text editing control being used to enter the password. if the user hasn't entered anyt...
...ue of a password control, line feed and carriage return characters are stripped out of the value. ...
...control, line feed and carriage return characters are stripped out of the value. ...
...And 8 more matches
The "codecs" parameter in common media types - Web media technologies
le with the mime type video/mp4 doesn't say anything about what format the actual media within takes. for that reason, the codecs parameter can be added to the mime type describing media content. with it, container-specific information can be provided. this information may include things like the profile of the video codec, the type used for the audio tracks, and so forth. this guide briefly examines the syntax of the media type codecs parameter and how it's used with the mime type string to provide details about the contents of audio or video media beyond simply indicating the container type. 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 ...
...e default value is 0 (not monochrome). ccc ccc indicates the chroma subsampling as three digits. the first digit is subsampling_x, the second is subsampling_y. if both of those are 1, the third is the value of chroma_sample_position; otherwise, the third digit is always 0. ...
...meter, as well as the value to specify for the constraints component, cc. ...
...And 8 more matches
Element Positioning - Archive of obsolete content
« previousnext » here we'll look at controlling the position and size of an element. box element positioning so far, we know how to position elements either horizontally or vertically inside a box. we will often need more control over the position and size of elements within the box. for this, we first need to look at how a box works. ...
...er horizontally or vertically inside a box. we will often need more control over the position and size of elements within the box. for this, we first need to look at how a box works. the position of an element is determined by the layout style of its container. for example, the position of a button in a horizontal box is to the right of the previous button, if any. the size of an element is determined by two factors, the size that the element wants to be and the size you specify. the size that an element wants to be is determined by what is in the element. for example, a button's width is determined by the amount of text inside the button. an element will generally be as large as it needs to be to hold its contents, and no larger. some elements, such as textboxes have a default size, which ...
...abel="ok" width="100" height="40"/> however, it is not recommended that you do this. it is not very portable and may not fit in with some themes. a better way is to use style properties, which work similarly to style sheets in html. the following css properties can be used. width this specifies the width of the element. note that the css global skin of the xul application may also specify a min-width for the buttons and other elements, thus if simply setting the width property does not set the button width as you expect, try also to modify the button min-width property. height this specifies the height of the element. by setting either of the two properties, the element will be created with that width and height. if you specify only one size property, the other is calculated as need...
...And 7 more matches
Tree View Details - Archive of obsolete content
this is a fairly tricky process as it involves keeping track of which items have children and also which rows are open and closed. nesting level every row in the tree has a nesting level. ...
...this is a fairly tricky process as it involves keeping track of which items have children and also which rows are open and closed. nesting level every row in the tree has a nesting level. ...
...vel every row in the tree has a nesting level. the topmost rows are at level 0, the children of those rows are at level 1, their children at level 2 and so on. the tree will query the view for each row by calling its getlevel method to find out the level of that row. the view will need to return 0 for the outermost rows and higher values for inner rows. the tree will use this information to determine the hierarchical structure of the rows. in addition to the getlevel method, there is a hasnextsibling function which, given a row, should return true if there is another row afterwards at the same level. this function is used, specifically, to draw the nesting lines along the side of the tree. the getparentindex method is expected to return the parent row of a given row, that is, the row befor...
...And 7 more matches
Grids - Learn web development
it might be better to have tracks that are at least 100 pixels tall and can still expand if more content gets into them. a fairly basic fact about the web is that you never really know how tall something is going to be; addit...
...pixels, in which case it would cause an overflow. it might be better to have tracks that are at least 100 pixels tall and can still expand if more content gets into them. a fairly basic fact about the web is that you never really know how tall something is going to be; additional content or larger font sizes can cause problems with designs that attempt to be pixel perfect in every dimension. ...
...ause an overflow. it might be better to have tracks that are at least 100 pixels tall and can still expand if more content gets into them. a fairly basic fact about the web is that you never really know how tall something is going to be; additional content or larger font sizes can cause problems with designs that attempt to be pixel perfect in every dimension. ...
...And 7 more matches
Tips for authoring fast-loading HTML pages - Learn web development
timizing page load performance is not just for content which will be viewed by narrowband dial-up or mobile device visitors. it is just as important for broadband content and can lead to dramatic improvements even for your visitors with the fastest connections. tips reduce page weight page weight is by far the most important factor in page-load performance. reducing page weight through the elimination of unnecessary whitespace and comments, commonly known as minimization, and by moving inline script and css into external files, can improve download performance with minimal need for other changes in the page structure. tools such as html tidy can automatically strip leading whitespace and extra blank lines from valid html source. other tools can "compress" javascript by reformatting the s...
...g inline script and css into external files, can improve download performance with minimal need for other changes in the page structure. tools such as html tidy can automatically strip leading whitespace and extra blank lines from valid html source. other tools can "compress" javascript by reformatting the source or by obfuscating the source and replacing long identifiers with shorter versions. minimize the number of files reducing the number of files referenced in a web page lowers the number of http connections required to download a page, thereby reducing the time for these requests to be sent, and for their responses to be received. depending on a browser's cache settings, it may send a request with the if-modified-since header for each referenced file, asking whether the file has bee...
...e network node closest to the user, thereby reducing latency. further reading: understanding cdns reduce domain lookups since each separate domain costs time in a dns lookup, the page load time will grow along with the number of separate domains appearing in css link(s) and javascript and image src(es). this may not always be practical; however, you should always take care to use only the minimum necessary number of different domains in your pages. cache reused content make sure that any content that can be cached, is cached, and with appropriate expiration times. in particular, pay attention to the last-modified header. it allows for efficient page caching; by means of this header, information is conveyed to the user agent about the file it wants to load, such as when it was last ...
...And 7 more matches
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
ply omit the value), the function will run as soon as possible. (see the note below on why it runs "as soon as possible" and not "immediately".) more on why you might want to do this later. zero or more values that represent any parameters you want to pass to the function when it is run. note: the specified amount of time (or the delay) is not the guaranteed time to execution, but rather the minimum time to execution. the callbacks you pass to these functions cannot run until the stack on the main thread is empty. as a consequence, code like settimeout(fn, 0) will execute as soon as the stack is empty, not immediately. if you execute code like settimeout(fn, 0) but then immediately after run a loop that counts from 1 to 10 billion, your callback will be executed after a few seconds. i...
...'ve done in our version, but less accurate — you can't guarantee that the callback will fire after exactly 1000ms. a more accurate way would be to run starttime = date.now() to get a timestamp of exactly when the user clicked the start button, and then do date.now() - starttime to get the number of milliseconds after the start button was clicked. you also want to calculate the number of hours, minutes, and seconds as separate values, and then show them together in a string after each loop iteration. from the second counter, you can work out each of these. how would you calculate them? have a think about it: the number of seconds in an hour is 3600. the number of minutes will be the amount of seconds left over when all of the hours have been removed, divided by 60. the number o...
... you'll want to include a leading zero on your display values if the amount is less than 10, so it looks more like a traditional clock/watch. ...
...And 7 more matches
TypeScript support in Svelte - Learn web development
s on dom elements in svelte. we will now learn how to use typescript in svelte applications. first we'll learn what typescript is and what benefits it can bring us. then we'll see how to configure our project to work with typescript files. finally we will go over our app and see what modifications we have to make to fully take advantage of typescript features. prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line. you'll need a terminal with node + npm installed to compile and build your app. objective: learn how to configure and use typescript when developing svelte applications. note that our application is fully functional and portin...
... developers working on the same code base. and it is indeed being used by several large-scale projects, like angular 2, vue 3, ionic, visual studio code, jest and even the svelte compiler. nevertheless, some developers prefer to use it even on small projects like the one we are developing. in the end, it's your decision. ...
...er. nevertheless, some developers prefer to use it even on small projects like the one we are developing. in the end, it's your decision. in the following sections we hope to give you more evidence to make up your mind about it. creating a svelte typescript project from scratch you can start a new svelte typescript project using the standard template. all you have to do is run the following terminal commands (run them somewhere where you are storing your svelte test projects — it creates a new directory): npx degit sveltejs/template svelte-typescript-app cd svelte-typescript-app node scripts/setuptypescript.js this creates a starter project that includes typescript support, which you can then modify as you wish. then you'll have to tell npm to download dependencies and start the pr...
...And 7 more matches
Getting started with Svelte - Learn web development
article we'll provide a quick introduction to the svelte framework. we will see how svelte works and what sets it apart from the rest of the frameworks and tools we've seen so far. then we will learn how to setup our development environment, create a sample app, understand the structure of the project, and see how to run it locally and build it for production. prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line. svelte is a compiler that generates minimal and highly optimized javascript code from our sources; you'll need a terminal with node + npm installed to compile and build your app. objective: to setup a local svelte development environ...
...d to explore it. note: recently svelte has added official typescript support, one of its most requested features. we'll look at it later on in this tutorial series. we encourage you to go through the svelte tutorial for a really quick introduction to the basic concepts, before returning to this tutorial series to learn how to build something slightly more in-depth. it should take you about 30 minutes to complete. use cases svelte can be used to develop small pieces of an interface or whole applications. you can either start from scratch letting svelte drive your ui or you can incrementally integrate it into an existing application. nevertheless, svelte is particularly appropriate to tackle the following situations: web applications intended for low power devices: applications built ...
... allowing each component to define their own styles without the risk of clashing with other component's styles. it extends javascript by reinterpreting specific directives of the language to achieve true reactivity and ease component state management. the compiler only intervenes in very specific situations and only in the context of svelte components. extensions to the javascript language are minimal and carefully picked in order to not break javascript syntax nor alienate developers. in fact, you will be mostly working with vanilla javascript. first steps with svelte being a compiler, you can't just add a <script src="svelte.js"> tag to your page and import it into your app. you'll have to set up your development environment in order to let the compiler do its job. requirements in or...
...And 7 more matches
Introduction to NSPR
the netscape portable runtime (nspr) api allows compliant applications to use system facilities such as threads, thread synchronization, i/o, interval timing, atomic operations, and several other low-level services in a platform-independent manner. this chapter introduces key nspr programming concepts and illustrates them with sample code. the current implementation of nspr allows developers to compile a single source code base on macintosh (ppc), win32 (nt 3.51, nt 4.0, win'95), and over twenty versions of unix. nspr does not provide a platform for porting existing code. it must be used from the beginning of a software project. ...
.... this chapter introduces key nspr programming concepts and illustrates them with sample code. the current implementation of nspr allows developers to compile a single source code base on macintosh (ppc), win32 (nt 3.51, nt 4.0, win'95), and over twenty versions of unix. nspr does not provide a platform for porting existing code. it must be used from the beginning of a software project. ...
...duces key nspr programming concepts and illustrates them with sample code. the current implementation of nspr allows developers to compile a single source code base on macintosh (ppc), win32 (nt 3.51, nt 4.0, win'95), and over twenty versions of unix. nspr does not provide a platform for porting existing code. it must be used from the beginning of a software project. ...
...And 7 more matches
JIT Optimization Strategies
constants = {}; constants.n = 100; function testarray(array) { for (var i = 0; i < array.length; i++) { if (array[i] > constants.n) return true; } return false; } will have the loop compiled into the following when testarray gets hot. for (var i = 0; i < array.length; i++) { if (array[i] > 100) return true; } when this optimization is successful, property access is eliminated entirely and replaced with an inline constant. getprop_constant attempts to optimize reading a property that contains a uniquely-typed (or "singleton") object. with uniquely-typed objects, it is guaranteed that no other object has that same type. unique (or "singleton") types are assigned to certain kinds of objects, like global objects, top-level functions, and object literals declared at ...
...quely-typed objects, it is guaranteed that no other object has that same type. unique (or "singleton") types are assigned to certain kinds of objects, like global objects, top-level functions, and object literals declared at the top-level of a script. if a property has always contained the same uniquely-typed object, then the engine can use the unique type to map back to a specific object, and eliminate the property access, replacing it with a constant reference to the object. when this optimization is successful, property access is eliminated entirely and replaced with an inline constant. the different success and failure conditions are documented below: getprop_staticname attempts to optimize a property access on window which refers to a property on the global object. getprop_typedobjec...
... property that is not turned into a constant. it compiles down to a single cpu-level load instruction. function someconstructor() { this.x = 10; // x is a definite slot property this.y = 10; // y is a definite slot property somecomplicatedfunctioncall(); this.z = 20; // z is not a definite slot property. } in the above example, the properties x and y can always be determined to exist on any instance of someconstructor at definite locations, allowing the engine to infer deterministically the position of x without a shape guard. this optimization can fail for a number of reasons. if the types observed at the property access are polymorphic (more than one type), this optimization cannot succeed. furthermore, even if the object type is monomorphic, the optimization wi...
...And 7 more matches
nsCString
class declaration this is the canonical null-terminated string class. all subclasses promise null-terminated storage. instances of this class allocate strings on the heap. names: nsstring for wide characters nscstring for narrow characters this class is also known as nsaflat[c]string, where "flat" is used to denote a null-terminated string. method overview constructors operator= get find rfind rfindchar findcharinset rfindcharinset compare equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading b...
... compare equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii ...
... @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the ...
...And 7 more matches
nsDependentString
subclass of nststring that restricts string value to an immutable character sequence. this class does not own its data, so the creator of objects of this type must take care to ensure that a nstdependentstring continues to reference valid memory for the duration of its use. ...
...ndcharinset equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii ...
... @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the ...
...And 7 more matches
nsString
class declaration this is the canonical null-terminated string class. all subclasses promise null-terminated storage. instances of this class allocate strings on the heap. names: nsstring for wide characters nscstring for narrow characters this class is also known as nsaflat[c]string, where "flat" is used to denote a null-terminated string. method overview constructors operator= get find rfind rfindchar findcharinset rfindcharinset equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting ...
...ndcharinset equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii ...
... @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the ...
...And 7 more matches
Index
nipulating thunderbird address books. address book interfaces provides an overview of the related interfaces. see an overview of thunderbird components for a general description of the thunderbird user interface and related programmatic interfaces. 9 address book sync client design by richard h. pizzarro <rhp@netscape.com> 10 autoconfiguration in thunderbird administration, enterprise author: ben bucksch please do not change this document without consulting the author 11 autoconfig file format no summary! 12 autoconfig file format definition please see https://wiki.mozilla.org/thunderbird:autoconfiguration:configfileformat. 13 autoconfig: how to create a configuration file autoconfiguration,...
... thunderbird moved to autoconfiguration 15 buddy icons in mail seth spitzer mozilla is now able to show icons in the message header area and the addressbook card pane. 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. (see this document for info about that.) for the addressbook card pane, the icon will show is on disk at: <profile home>/nim/<value of pref aim.session.screenname>/picture/<screenname for card>.gif if aim.session.screenname is not set, the icon will not appear. if there is no card matching the ...
... see the source for nitty-gritty details or if this page seems to be wrong. glodaindexer provides the core indexing logic. glodamsgindexer has the message-specific stuff, although the actual attribute-providers are found in glodaexplicitattr and glodafundattr. glodaabindexer has the limited address book support. 32 index index found 72 pages: 33 ldap support administration, enterprise, thunderbird this document is intended to "fill in the gaps" about how enterprise customers can leverage and customize ldap support in mozilla thunderbird. it is not intended as an introduction to ldap and mozilla products. it assumes you are already familiar with configuring preferences for deployed builds in addition to setting up thunderbird to use an ldap directory.
...And 7 more matches
Version, UI, and Status Information - Plugins
agent(npp instance); the instance parameter represents the current plug-in instance. this function returns a string that contains the user_agent field of the browser. 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. to do so, it must find the major and minor version numbers, which are determined when the plug-in and navigator are compiled, and compare them. if the versions are not compatible, the plug-in can let the user know. the plug-in can also use the version number to find out whether a particular feature exists on the version of the browser that the plug-in is running in. the browser and plug-in api major version numbers represent code relea...
...ich are determined when the plug-in and navigator are compiled, and compare them. if the versions are not compatible, the plug-in can let the user know. the plug-in can also use the version number to find out whether a particular feature exists on the version of the browser that the plug-in is running in. the browser and plug-in api major version numbers represent code release numbers, and their minor version numbers represent point release numbers. for example, plug-in api version 6.03 has a major version number of 6 and a point release number of 3. differing version numbers may mean that the current plug-in api and the browser versions are incompatible. changes to the minor version numbers indicate a smaller difference than changes to the major version. changes to the major version number...
...ber of 6 and a point release number of 3. differing version numbers may mean that the current plug-in api and the browser versions are incompatible. changes to the minor version numbers indicate a smaller difference than changes to the major version. changes to the major version numbers probably indicate incompatibility. the plug-in calls the npn_version method to check for changes in major and minor plug-in api version numbers. it gets the values from the plug-in rather than from the browser. ...
...And 7 more matches
Network request details - Firefox Developer Tools
network monitor, which provides more detailed information about the request. the screenshots and descriptions in this section reflect firefox 78. earlier versions appeared similarly, but might not include some functionality. the tabs at the top of this pane enable you to switch between the following pages: headers messages (only for websocket items) cookies params response cache timings security (only for secure pages) stack trace (only when the request has a stack trace, e.g. a script called by another script). clicking the icon at the right-hand end of the toolbar closes the details pane and returns you to the list view. headers tab the headers tab has a toolbar, followed by three main sections. this includes: information about the request status: the respons...
...alue pair is copied. ...
...2019 13:01:39 gmt" }, { "name": "mediawiki-login-suppressed", "value": "true" }, { "name": "p3p", "value": "cp=\"this is not a p3p policy! ...
...And 7 more matches
Checking when a deadline is due - Web APIs
derstands. human-readable dates are quite different, with a number of different representations. recording the date information to provide a reasonable user experience on mobile devices, and to cut down on ambiguities, i decided to create an html form with: a text input for entering a title for your to-do list. this is the least avoidable bit of user typing. number inputs for the hour and minute parts of the deadline. on browsers that support type="number", you get a nice little up and down arrow number picker. on mobile platforms you tend to get a numeric keypad for entering data, which is helpful. on others you just get a standard text input, which is okay. <select> elements for inputting the day, month and year of the deadline. because these values are the most ambiguous for users...
...lso saves on annoying typing for mobile users. the days are recorded as numerical days of the month, the months are recorded as full month names, and the years are recorded as full four digit year numbers. when the form's submit button is pressed, we run the adddata() function, which starts like this: function adddata(e) { e.preventdefault(); if(title.value == '' || hours.value == null || minutes.value == null || day.value == '' || month.value == '' || year.value == null) { note.innerhtml += '<li>data not submitted — form incomplete.</li>'; return; } in this segment, we check to see if the form fields have all been filled in. if not, we drop a message into our developer notifications pane (see the bottom left of the app ui) to tell the user what is going on, and exit out...
...eveloper notifications pane (see the bottom left of the app ui) to tell the user what is going on, and exit out of the function. ...
...And 7 more matches
Performance - Web APIs
an object of this type can be obtained by calling the window.performance read-only attribute. note: this interface and its members are available in web workers, except where indicated below. also, note that performance markers and measures are per context. ...
...at performance markers and measures are per context. if you create a mark on the main thread (or other worker), you cannot see it in a worker thread, and vice versa. properties the performance interface doesn't inherit any properties. performance.navigation read only a legacy performancenavigation object that provides useful context about the operations included in the times listed in timing, including whether the page was a load or a refresh, how many redirections occurred, and so forth. not available in workers. performance.timing read only a legacy performancetiming object containing latency-related performance information. not available in workers. performance.memory read only a non-standard extension added in chrome, this property provides an object with basic memory ...
...rigin read only returns the high resolution timestamp of the start time of the performance measurement. methods the performance interface doesn't inherit any methods. performance.clearmarks() removes the given mark from the browser's performance entry buffer. performance.clearmeasures() removes the given measure from the browser's performance entry buffer. performance.clearresourcetimings() removes all performance entries with a entrytype of "resource" from the browser's performance data buffer. performance.getentries() returns a list of performanceentry objects based on the given filter. performance.getentriesbyname() returns a list of performanceentry objects based on the given name and entry type. performance.getentriesbytype() returns a list of performanceentry object...
...And 7 more matches
Movement, orientation, and motion: A WebXR example - Web APIs
understand the way the functions and data that are used during xr rendering work together. screenshot of this example in action the core of this example—the spinning, textured, lighted cube—is taken from our webgl tutorial series; namely, the penultimate article in the series, covering lighting in webgl. while reading this article and the accompanying source code, it's helpful to keep in mind that the display for a 3d headset is a single screen, divided in half. the left half of the screen is seen only by the left eye, while the right half is only seen by the right eye. rendering the scene for immersive presentation requires multiple renders of the scene—once from the perspective of each eye. when rendering the left eye, the xrwebgllayer has its viewport configured to restrict dra...
...ve a headset. setup and utility functions next, we declare the variables and constants used throughout the application, starting with those used to store webgl and webxr specific information: let polyfill = null; let xrsession = null; let xrinputsources = null; let xrreferencespace = null; let xrbutton = null; let gl = null; let animationframerequestid = 0; let shaderprogram = null; let programinfo = null; let buffers = null; let texture = null; let mouseyaw = 0; let mousepitch = 0; this is followed by a set of constants, mostly to contain various vectors and matrices used while rendering the scene. const viewerstartposition = vec3.fromvalues(0, 0, -10); const viewerstartorientation = vec3.fromvalues(0, 0, 1.0); const cubeorientation = vec3.create(); const cubematrix = mat4.create(); ...
... gl = canvas.getcontext("webgl", { xrcompatible: true }); if (allowmouserotation) { canvas.addeventlistener("pointermove", handlepointermove); canvas.addeventlistener("contextmenu", (event) => { event.preventdefault(); }); } if (allowkeyboardmotion) { document.addeventlistener("keydown", handlekeydown); } shaderprogram = initshaderprogram(gl, vssource, fssource); programinfo = { program: shaderprogram, attriblocations: { vertexposition: gl.getattriblocation(shaderprogram, 'avertexposition'), vertexnormal: gl.getattriblocation(shaderprogram, 'avertexnormal'), texturecoord: gl.getattriblocation(shaderprogram, 'atexturecoord'), }, uniformlocations: { projectionmatrix: gl.getuniformlocation(shaderprogram, 'uprojectionmatrix'), ...
...And 7 more matches
Using Web Workers - Web APIs
e hung off the worker object when used in the main script thread, but not when used in the worker. this is because, inside the worker, the worker is effectively the global scope. note: when a message is passed between the main thread and worker, it is copied or "transferred" (moved), not shared. read transferring data to and from workers: further details for a much more thorough explanation. terminating a worker if you need to immediately terminate a running worker from the main thread, you can do so by calling the worker's terminate method: myworker.terminate(); the worker thread is killed immediately. handling errors when a runtime error occurs in the worker, its onerror event handler is called. it receives an event named error which implements the errorevent interface. the event do...
...you'll see similar constructs in both multiply.js and square.js): myworker.port.onmessage = function(e) { result2.textcontent = e.data; console.log('message received from worker'); } when a message comes back through the port from the worker, we insert the calculation result inside the appropriate result paragraph. about thread safety the worker interface spawns real os-level threads, and mindful programmers may be concerned that concurrency can cause “interesting” effects in your code if you aren't careful. however, since web workers have carefully controlled communication points with other threads, it's actually very hard to cause concurrency problems. there's no access to non-threadsafe components or the dom. and you have to pass specific data in and out of a thread through se...
...steners and help us communicate with the worker: function queryableworker(url, defaultlistener, onerror) { var instance = this, worker = new worker(url), listeners = {}; this.defaultlistener = defaultlistener || function() {}; if (onerror) {worker.onerror = onerror;} this.postmessage = function(message) { worker.postmessage(message); } this.terminate = function() { worker.terminate(); } } then we add the methods of adding/removing listeners: this.addlisteners = function(name, listener) { listeners[name] = listener; } this.removelisteners = function(name) { delete listeners[name]; } here we let the worker handle two simple operations for illustration: getting the difference of two numbers and making an alert after th...
...And 7 more matches
Color picker tool - CSS: Cascading Style Sheets
lor info box */ #color-info { width: 360px; float: left; } #color-info .title { width: 100%; padding: 15px; font-size: 18px; text-align: center; background-image: url('https://mdn.mozillademos.org/files/6071/color-wheel.png'); background-repeat:no-repeat; background-position: center left 30%; } #color-info .copy-container { position: absolute; top: -100%; } #color-info .property { min-width: 280px; height: 30px; margin: 10px 0; text-align: center; line-height: 30px; } #color-info .property > * { float: left; } #color-info .property .type { width: 60px; height: 100%; padding: 0 16px 0 0; text-align: right; } #color-info .property .value { width: 200px; height: 100%; padding: 0 10px; font-family: "segoe ui", arial, helvetica, sans-serif; font-size: 16px; color:...
...over.png');*/ background-position: bottom left; } #color-palette .controls .lock[locked-state='true'] { /*background-image: url('images/locked.png');*/ background-position: top left ; } #color-palette .controls .lock[locked-state='true']:hover { /*background-image: url('images/lock-hover.png');*/ background-position: top right; } /** * canvas */ #canvas { width: 100%; height: 300px; min-height: 250px; border-top: 1px solid #ddd; background-image: url('https://mdn.mozillademos.org/files/6025/grain.png'); background-repeat: repeat; position: relative; float: left; } #canvas[data-tutorial='drop'] { text-align: center; font-size: 30px; color: #777; } #canvas[data-tutorial='drop']:before { content: "drop colors here to compare"; width: 40%; padding: 30px 9% 70px 11%; b...
...r modify"; width: 40%; font-size: 24px; position: absolute; top: 130px; left: 32%; z-index: 2; } #canvas [data-tutorial='dblclick'] { background-color: #999 !important; } #canvas [data-tutorial='dblclick']:before { content: "double click to activate"; width: 80px; color: #fff; position: absolute; top: 10%; left: 20%; z-index: 2; } #canvas .sample { width: 100px; height: 100px; min-width: 20px; min-height: 20px; position: absolute; border: 1px solid rgba(255, 255, 255, 0.3); } #canvas .sample:hover { cursor: move; } #canvas .sample[data-active='true']:after { content: ""; position: absolute; background: url('https://mdn.mozillademos.org/files/6065/arrow.png') center no-repeat; width: 100%; height: 12px; top: -12px; z-index: 2; } #canvas .sample:hover > * { cu...
...And 7 more matches
Controlling Ratios of Flex Items Along the Main Axis - CSS: Cascading Style Sheets
ral size of flex items before any growing or shrinking takes place, and to the concept of free space. flex item sizing in order to work out how much space there is available to lay out flex items, the browser needs to know how big the item is to start with. how is this worked out for items that don’t have a width or a height applied using an absolute length unit? there is a concept in css of min-content and max-content — these keywords are defined in the css intrinsic and extrinsic sizing specification, and can be used in place of a length unit. in the live example below for instance i have two paragraph elements that contain a string of text. the first paragraph has a width of min-content. in a browser that supports this keyword you should be able to see that the text has taken all o...
...essentially, the longest word in the string is dictating the size. ...
...essentially, the longest word in the string is dictating the size. the second paragraph has a value of max-content and so it does the opposite. ...
...And 7 more matches
animation - CSS: Cascading Style Sheets
Web › CSS › animation
the animation shorthand css property applies an animation between styles. it is a shorthand for animation-name, animation-duration, animation-timing-function, animation-delay, animation-iteration-count, animation-direction, animation-fill-mode, and animation-play-state. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...tion, animation-timing-function, animation-delay, animation-iteration-count, animation-direction, animation-fill-mode, and animation-play-state. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...e example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...And 7 more matches
clamp() - CSS: Cascading Style Sheets
Web › CSS › clamp
the clamp() css function clamps a value between an upper and lower bound. clamp() enables selecting a middle value within a range of values between a defined minimum and maximum. it takes three parameters: a minimum value, a preferred value, and a maximum allowed value. the clamp() function can be used anywhere a <length>, <frequency>, <angle>, <time>, <percentage>, <number>, or <integer> is allowed. clamp(min, val, max) is resolved as max(min, min(val, max)) the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. note that using clamp() for font sizes, as in these examples, allows you to set a font-size that grows with t...
...min(val, max)) the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. 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. it has the same effect as the code in fluid typography but in one line, and without the use of media queries. syntax the clamp() function takes three comma separated expressions as its parameter, in the order of minimum value, preferred value, maximum value. the minimum value is the smallest (most negative) value. this is the lower bound in the range...
...he code in fluid typography but in one line, and without the use of media queries. syntax the clamp() function takes three comma separated expressions as its parameter, in the order of minimum value, preferred value, maximum value. the minimum value is the smallest (most negative) value. this is the lower bound in the range of allowed values. if the preferred value is less than this value, the minimum value will be used. the preferred value is the expression whose value will be used as long as the result is between the minimum and maximum values. the maximum value is the largest (most positive) expression value to which the value of the property will be assigned if the preferred value is greater than this upper bound. the expressions can be math functions (see calc() for more informatio...
...And 7 more matches
grid-auto-rows - CSS: Cascading Style Sheets
https://github.com/mdn/interactive-examples and send us a pull request. if a grid item is positioned into a row that is not explicitly sized by grid-template-rows, implicit grid tracks are created to hold it. this can happen either by explicitly positioning into a row that is out of range, or by the auto-placement algorithm creating additional rows. ...
...by the auto-placement algorithm creating additional rows. ...
...ating additional rows. ...
...And 7 more matches
width - CSS: Cascading Style Sheets
Web › CSS › width
css property sets an element's width. by default, it sets the width of the content area, but if box-sizing is set to border-box, it sets the width of the border area. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...active example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. the min-width and max-width properties override width. syntax /* <length> values */ width: 300px; width: 25em; /* <percentage> value */ width: 75%; /* keyword values */ width: max-content; width: min-content; width: fit-content(20em); width: auto; /* global values */ width: inherit; width: initial; width: unset; the width property is specified as either: one of the following keyword values: min-content, max-content, fit-content, auto. a <length> or a <percentage>. values <length> defines the width as an absolute value. <percentage> defines the width as a percentage of the conta...
...ed as either: one of the following keyword values: min-content, max-content, fit-content, auto. a <length> or a <percentage>. values <length> defines the width as an absolute value. <percentage> defines the width as a percentage of the containing block's width. auto the browser will calculate and select a width for the specified element. max-content the intrinsic preferred width. min-content the intrinsic minimum width. fit-content(<length-percentage>) uses the fit-content formula with the available space replaced by the specified argument, i.e. min(max-content, max(min-content, <length-percentage>)). accessibility concerns ensure that elements set with a width aren't truncated and don't obscure other content when the page is zoomed to increase text size. mdn unders...
...And 7 more matches
Audio and Video Delivery - Developer guides
, 5000); }) .catch(function onerror(error) { console.log(error.message); }); see mediarecorder api for more details. media source extensions (mse) media source extensions is a w3c working draft that plans to extend htmlmediaelement to allow javascript to generate media streams for playback. allowing javascript to generate streams facilitates a variety of use cases like adaptive streaming and time shifting live streams. encrypted media extensions (eme) encrypted media extensions is a w3c proposal to extend htmlmediaelement, providing apis to control playback of protected content. the api supports use cases ranging from simple clear key decryption to high value video (given an appropriate user agent implementation). license/key exchange is controlled by the application, facil...
...implementation). license/key exchange is controlled by the application, facilitating the development of robust playback applications supporting a range of content decryption and protection technologies. one of the principle uses of eme is to allow browsers to implement drm (digital rights management), which helps to prevent web-based content (especially video) from being copied. adaptive streaming new formats and protocols are being rolled out to facilitate adaptive streaming. adaptive streaming media means that the bandwidth and typically quality of the stream can change in real-time in reaction to the user's available bandwidth. adaptive streaming is often used in conjunction with live streaming where smooth delivery of audio or video is paramount. the main formats used for adaptive s...
...mse defines byte streams according to isobmff and m2ts (both supported in dash, the latter supported in hls). ...
...And 7 more matches
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
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. we'll also take a look at how to let the user pick a color. then we'll wrap things up with a brief discussion of how to use color wisely: how to select appropriate colors, keeping in mind the needs of people with differing visual capabilities. things that can have color at the element level, everything in html can have color applied to it. instead, let's look at things in terms of the kinds of things that are drawn in the elements, such as text and borders and so forth. for each, we'll see a list of the css properties that apply color to them. at a fundamental level, the color...
...ext and borders and so forth. for each, we'll see a list of the css properties that apply color to them. at a fundamental level, the color property defines the foreground color of an html element's content and the background-color property defines the element's background color. these can be used on just about any element. text whenever an element is rendered, these properties are used to determine the color of the text, its background, and any decorations on the text. color the color to use when drawing the text and any text decorations (such as the addition of under- or overlines, strike-through lines, and so forth. background-color the text's background color. text-shadow configures a shadow effect to apply to text. among the options for the shadow is the shadow's base color (wh...
... alpha the alpha channel is a number between 0.0 (fully transparent) and 1.0 (fully opaque). you can also specify a percentage where 0% is the same as 0.0 and 100% is the same as 1.0. for example, a bright red that's 50% opaque can be represented as rgb(255, 0, 0, 0.5) or rgb(100%, 0, 0, 50%). hsl functional notation designers and artists often prefer to work using the hsl (hue/saturation/luminosity) color method. on the web, hsl colors are represented using hsl functional notation. the hsl() css function is very similar to the rgb() function in usage otherwise. figure 1. an hsl color cylinder. hue defines the actual color based on the position along a circular color wheel representing the colors of the visible spectrum. saturation is a percentage of how much of the way between being...
...And 7 more matches
<input type="week"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › week
ascript using the input element's value property, for example: var weekcontrol = document.queryselector('input[type="week"]'); weekcontrol.value = '2017-w45'; additional attributes in addition to the attributes common to <input> elements, week inputs offer the following attributes: attribute description max the latest year and week to accept as valid input min the earliest year and week to accept as valid input readonly a boolean which, if present, indicates that the user cannot edit the field's contents step the stepping interval (the distance between allowed values) to use for both user interface and constraint validation max the latest (time-wise) year and week number, in the string format discussed in the value se...
... max the latest (time-wise) year and week number, in the string format discussed in the value section above, to accept. if the value entered into the element exceeds this, the element fails constraint validation. if the value of the max attribute isn't a valid week string, then the element has no maximum value. this value must be greater than or equal to the year and week specified by the min attribute. min the earliest year and week to accept. if the value of the element is less than this, the element fails constraint validation. if a value is specified for min that isn't a valid week string, the input has no minimum value. this value must be less than or equal to the value of the max attribute. readonly a boolean attribute which, if present, means this field cannot be edited by...
...tly setting the htmlinputelement.value property. note: because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified. step the step attribute is a number that specifies the granularity that the value must adhere to, or the special value any, which is described below. only values which are equal to the basis for stepping (min if specified, value otherwise, and an appropriate default value if neither of those is provided) are valid. a string value of any means that no stepping is implied, and any value is allowed (barring other constraints, such as min and max). note: when the data entered by the user doesn't adhere to the stepping configuration, the user agent may round to the nearest valid value, preferring number...
...And 7 more matches
Proxy Auto-Configuration (PAC) file - HTTP
the javascript function contained in the pac file defines the function: function findproxyforurl(url, host) { // ... } syntax function findproxyforurl(url, host) parameters url the url being accessed. the path and query components of https:// urls are stripped. ...
...be used socks4 host:port socks5 host:port the specified socks server (with the specified sock version) should be used if there are multiple semicolon-separated settings, the left-most setting will be used, until firefox fails to establish the connection to the proxy. in that case, the next value will be used, etc. ...
...pecified sock version) should be used if there are multiple semicolon-separated settings, the left-most setting will be used, until firefox fails to establish the connection to the proxy. in that case, the next value will be used, etc. the browser will automatically retry a previously unresponsive proxy after 30 minutes. additional attempts will continue beginning at one hour, always adding 30 minutes to the elapsed time between attempts. ...
...And 7 more matches
Populating the page: how browsers work - Web Performance
gle threaded. for smooth interactions, the developer's goal is to ensure performant site interactions, from smooth scrolling to being responsive to touch. render time is key, with ensuring the main thread can complete all the work we throw at it and still always be available to handle user interactions. web performance can be improved by understanding the single-threaded nature of the browser and minimizing the main thread's responsibilities, where possible and appropriate, to ensure rendering is smooth and responses to interactions are immediate. navigation navigation is the first step in loading a web page. it occurs whenever a user requests a page by entering a url into the address bar, clicking a link, submitting a form, as well as other actions. one of the goals of web performance is ...
...zing the main thread's responsibilities, where possible and appropriate, to ensure rendering is smooth and responses to interactions are immediate. navigation navigation is the first step in loading a web page. it occurs whenever a user requests a page by entering a url into the address bar, clicking a link, submitting a form, as well as other actions. one of the goals of web performance is to minimize the amount of time a navigation takes to complete. in ideal conditions, this usually doesn't take too long, but latency and bandwidth are foes which can cause delays. dns lookup the first step of navigating to a web page is finding where the assets for that page are located. if you navigate to https://example.com, the html page is located on the server with ip address of 93.184.216.34. if ...
...ccurately syn, syn-ack, ack—because there are three messages transmitted by tcp to negotiate and start a tcp session between two computers. yes, this means three more messages back and forth between each server, and the request has yet to be made. tls negotiation for secure connections established over https, another "handshake" is required. this handshake, or rather the tls negotiation, determines which cipher will be used to encrypt the communication, verifies the server, and establishes that a secure connection is in place before beginning the actual transfer of data. this requires three more round trips to the server before the request for content is actually sent. while making the connection secure adds time to the page load, a secure connection is worth the latency expense, as th...
...And 7 more matches
Understanding WebAssembly text format - WebAssembly
both the binary and textual formats, the fundamental unit of code in webassembly is a module. in the text format, a module is represented as one big s-expression. s-expressions are a very old and very simple textual format for representing trees, and thus we can think of a module as a tree of nodes that describe the module’s structure and its code. unlike the abstract syntax tree of a programming language, though, webassembly’s tree is pretty flat, mostly consisting of lists of instructions. first, let’s see what an s-expression looks like. each node in the tree goes inside a pair of parentheses — ( ... ). the first label inside the parenthesis tells you what type of node it is, and after that there is a space-separated list of either attributes or child nodes. so that means th...
...n convert it into a binary file called add.wasm using wabt (see converting webassembly text format to wasm for details). next, we’ll load our binary into a typed array called addcode (as described in fetching webassembly bytecode), compile and instantiate it, and execute our add function in javascript (we can now find add() in the exports property of the instance): webassembly.instantiatestreaming(fetch('add.wasm')) .then(obj => { console.log(obj.instance.exports.add(1, 2)); // "3" }); note: you can find this example in github as add.html (see it live also). also see webassembly.instantiatestreaming() for more details about the instantiate function. exploring fundamentals now we’ve covered the real basics, let’s move on to look at some more advanced features. calling fu...
...f declaring that we want to export this function, and defining the name we want to export it as. ...
...And 7 more matches
Using the WebAssembly JavaScript API - WebAssembly
e import has a two-level namespace — the internal function $i is imported from imports.imported_func. we need to reflect this two-level namespace in javascript when writing the object to be imported into the wasm module. ...
...ported into the wasm module. create a <script></script> element in your html file, and add the following code to it: var importobject = { imports: { imported_func: arg => console.log(arg) } }; streaming the webassembly module new in firefox 58 is the ability to compile and instantiate webassembly modules directly from underlying sources. this is achieved using the webassembly.compilestreaming() and webassembly.instantiatestreaming() methods. ...
...wing code to it: var importobject = { imports: { imported_func: arg => console.log(arg) } }; streaming the webassembly module new in firefox 58 is the ability to compile and instantiate webassembly modules directly from underlying sources. this is achieved using the webassembly.compilestreaming() and webassembly.instantiatestreaming() methods. these methods are easier than their non-streaming counterparts, because they can turn the byte code directly into module/instance instances, cutting out the need to separately put the response into an arraybuffer. ...
...And 7 more matches
An Interview With Douglas Bowman of Wired News - Archive of obsolete content
red or disappeared. when you get to that point, the amount of markup you have to sift through to find anything becomes ridiculous. until this redesign, wired news wasn't even using css to style the content inside tables. the sheer amount [sic] of redundant <font> tags inside every cell was probably enough to double file size. my initial attempts at the markup and css for the wired news design eliminated the majority of our tables, but left one master table to control the primary columns of each page. that approach meant that the content of every column would have to be loaded and calculated before it would be rendered in the browser window. that wasn't good enough. around that time, i started discovering great sites like glish.com and bluerobot.com. both presented and documented viable means...
...od enough. around that time, i started discovering great sites like glish.com and bluerobot.com. both presented and documented viable means of producing multi-column layouts without a single table. despite some initial setbacks with those approaches due to our own unique scenarios, it wasn't long before i discovered a variation of one of their methods that worked for the wired news design. by eliminating tables that were strictly used for layout, we significantly cut back on the amount of markup and useless tags in our html, and gained a structure that is much easier to maintain. now that the content is not locked into a specific table structure, we have much more flexibility in how we present that content. a few changes to the css can completely alter the presentation of thousands of pages.
...cific table structure, we have much more flexibility in how we present that content. a few changes to the css can completely alter the presentation of thousands of pages. as a very welcome side benefit, we also believe the accessibility of wired news will dramatically improve without the clutter of nested layout tables. are you setting up your columns with floats or positioning? in trying to eliminate that last table i was using to set the column structure of our pages, i took a close look at both floated divs and positioned divs. i went back and forth between each one for two weeks, and finally narrowed in on positioned divs as the choice for wired news. why did you choose positioning over floats? floats had a few disadvantages from my perspective. one was the required order of content w...
...And 6 more matches
MMgc - Archive of obsolete content
gc is not only a garbage collector, but a general-purpose memory manager. the flash player uses it for nearly all memory allocations. mmgc can handle both managed and unmanaged memory. managed memory is memory that is reclaimed automatically by the garbage collector. the garbage collector is "managing" it, detecting when the memory is no longer reachable from anywhere in the application and reclaiming it at that time. in mmgc, you get managed memory by subclassing gcobject/gcfinalizedobject/rcobject, or by calling gc::alloc. unmanaged memory is everything else. this is c++ memory management as you're accustomed to it. 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. another way to think about it: unma...
...fb a block given back to the heap manager is memset to this (fb == free block). finalizers if your c++ class is a subclass of gcfinalizedobject or rcfinalizedobject, it has finalizer support. a finalizer is a method which will be invoked by the gc when an unreachable object is about to be destroyed. it's similar to a destructor. it differs from a destructor in that it is usually called nondeterministically, i.e. in whatever random order the gc decides to destroy objects. c++ destructors are usually invoked in a comparatively predictable order, since they're invoked explicitly by the application code. in mmgc, the c++ destructor is actually used as the finalizer. if you don't subclass gcfinalizedobject or rcfinalizedobject, any c++ destructor on your garbage collected class will basically b...
...ctually used as the finalizer. if you don't subclass gcfinalizedobject or rcfinalizedobject, any c++ destructor on your garbage collected class will basically be ignored. only if you subclass gcfinalizedobject or rcfinalizedobject will mmgc know that you want finalization behavior on your class. it's best to avoid finalizers if you can, since finalization behavior can be unpredictable and nondeterministic, and also slows down the gc since the finalizers need to be invoked. finalizer access rules finalizers are very restricted in the set of objects they may access. finalizers may not perform any of the following actions: fire any write barriers dereference a pointer to any gc object, including member variables (except see below about rcobject references) allocate any gc memory (gc::alloc), ex...
...And 6 more matches
Microsummary XML grammar reference - Archive of obsolete content
mmarize. <exclude> (optional) a regular expression matching the urls of pages that the generator is not able to summarize. the <pages> element can contain zero or more <include> and <exclude> child elements, each of which must contain a valid javascript-compatible regular expression. it must not contain any other elements, and it does not have any attributes. when a generator is examined to determine whether or not it is able to summarize a page, the regular expressions provided by the child elements are evaluated against the url of the page. a generator is considered to be able to summarize a page if at least one of the <include> expressions matches the url of the page and none of the <exclude> expressions match the url of the page. the order in which child elements appear wit...
...#the_<pages>_element. the <update> element the optional <update> element specifies how frequently firefox should update microsummaries generated by the generator. the element can be used to specify both an absolute update interval and a series of conditional intervals based on the content of the page being summarized. ...
...nt can be used to specify both an absolute update interval and a series of conditional intervals based on the content of the page being summarized. attributes: interval (optional) an absolute interval of time, in minutes, that must elapse between updates. child elements: <condition> (optional) an xpath boolean expression along with a conditional interval of time, in minutes, that must elapse between updates if the expression evaluates to true. the interval attribute defines an absolute interval in minutes. ...
...And 6 more matches
Textbox (XPFE autocomplete) - Archive of obsolete content
attributes accesskey, alwaysopenpopup, autocompletesearch, autocompletesearchparam, autofill, autofillaftermatch, autofill, completedefaultindex, crop, disableautocomplete, disableautocomplete, disabled, disablehistory, enablehistory, focused, forcecomplete, forcecomplete, highlightnonmatches, ignoreblurwhilesearching, ignoreblurwhilesearching, inputtooltiptext, label, maxlength, maxrows, minresultsforpopup, minresultsforpopup, nomatch, onchange, onerrorcommand, oninput, onsearchcomplete, ontextcommand, ontextentered, ontextrevert, ontextreverted, open, readonly, searchsessions, showcommentcolumn, showcommentcolumn, showpopup, size, tabindex, tabscrolling, tabscrolling, timeout, type, useraction, value properties accessible, alwaysopenpopup, autofill, autofillaftermatc...
...mn, showcommentcolumn, showpopup, size, tabindex, tabscrolling, tabscrolling, timeout, type, useraction, value properties accessible, alwaysopenpopup, autofill, autofillaftermatch, completedefaultindex, crop, disableautocomplete, disabled, editable, focused, forcecomplete, highlightnonmatches, ignoreblurwhilesearching, inputfield, issearching, iswaiting, label, maxlength, maxrows, minresultsforpopup, nomatch, open, popup, popupopen, resultspopup, searchcount, searchparam, searchsessions, selectionend, selectionstart, sessioncount, showcommentcolumn, showpopup, size, tabindex, tabscrolling, textlength, textvalue, timeout, type, useraction, value methods addsession, clearresults, getdefaultsession, getresultat, getresultcount, getresultvalueat, getsession, getses...
...rs that appears in the label attribute for the element. alwaysopenpopup obsolete since gecko 1.9.1 type: boolean note: applies to: thunderbird and seamonkeyif true, the autocomplete popup will be displayed even when there are no matches. if false, the default value, the popup will be hidden. this attribute is obsolete as of gecko 1.9.1; to control the display of the popup, use the minresultsforpopup attribute instead. autocompletesearch new in thunderbird 2requires seamonkey 1.1 type: space-separated list of values a space-separated list of search component names, each of which implements the nsiautocompletesearch interface. the components are created using the name @mozilla.org/autocomplete/search;1?name= where name is listed in this attribute. ...
...And 6 more matches
The Implementation of the Application Object Model - Archive of obsolete content
al/remote merging good for? the first reason to have local/remote merging is that a remote file must be able to reference local data and have it merged in with the information that it specified. an example of this feature is a downloadable file that describes the user's main bookmarks folder. because the file lives remotely, it can be updated whenever the owner of the web site sees fit. a site admin could add new bookmarks to the file, and then the user would pick them up. however, in order for this to work, the local bookmarks have to be merged in with the remote bookmarks specified by the site. the second reason to have local/remote merging is to save state and/or to record customizations that the user has made to his or her user interface. imagine a remote file that describes the user's p...
...the display of web pages. what content developers want from the next release of mozilla is a standards-compliant browser. if we ship a browser that does not have 100% support for css2, for example, but we've extended html by adding 20-30 new tags, people are going to put down their blinders and see only the fact that we were off adding a whole slew of new stuff to html when we could have been firming up our standards story. by making xul a separate beast, this is less of an issue. since an aom tree cannot be placed inside a dom tree, xul applications don't ever occur inside web pages. by enforcing this distinction, we can successfully defend ourselves from any claims that we were "mucking about with strange new html" when we could have been working on our standards story. forget xul and rd...
...regation of data... the list goes on and on. future time-saving. xp development takes much less time than native platform development. but if we pay the cost and get xul into the system now, in the future xul development will take even less time than xp development. the additional cost up front to implement xul is worth it for the amount of time it will save in future versions of the browser. timing. it's now or never. if this approach isn't taken now, then we'll fall back into our old pattern. this is the pivotal point, because the apps are all being re-written from scratch. for this particular codebase, if we don't do this from start, we won't do it at all. why use rdf at all? ok, ok. so you've convinced me that xul is the way and the light. but why do you need to use rdf at all? nsico...
...And 6 more matches
progressmeter - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] a meter which can be used to display the progress of a lengthy operation. it is drawn as a bar that is filled as the operation completes. in addition, an indeterminate progressmeter may be created by setting the mode attribute to undetermined. this is used when the length of time to complete an operation is not known beforehand. more information is available in the xul tutorial. ...
...illed as the operation completes. in addition, an indeterminate progressmeter may be created by setting the mode attribute to undetermined. this is used when the length of time to complete an operation is not known beforehand. more information is available in the xul tutorial. ...
...n indeterminate progressmeter may be created by setting the mode attribute to undetermined. this is used when the length of time to complete an operation is not known beforehand. more information is available in the xul tutorial. ...
...And 6 more matches
Audio for Web games - Game development
the user has added the site to their home screen. many browsers will simply ignore any requests made by your game to automatically play audio; instead playback for audio needs to be started by a user-initiated event, such as a click or tap. this means you will have to structure your audio playback to take account of that. this is usually mitigated against by loading the audio in advance and priming it on a user-initiated event. for more passive audio auto play, for example background music that starts as soon as a game loads, one trick is to detect any user initiated event and start playback then. for other more active sounds that are to be used during the game we could consider priming them as soon as something like a start button is pressed. to prime audio like this we want to play a p...
...ouldn't be overridden. buffering and preloading likely as an attempt to mitigate runaway mobile network data use, we also often find that buffering is disabled before playback has been initiated. buffering is the process of the browser downloading the media in advance, which we often need to do to ensure smooth playback. the htmlmediaelement interface comes with lots of properties to help determine whether a track is in a state to be playable. note: in many ways the concept of buffering is an outdated one. as long as byte-range requests are accepted (which is the default behavior), we should be able to jump to a specific point in the audio without having to download the preceding content. however, preloading is still useful — without it, there would always need to be some client-server...
... jsfiddle. note: on mobile we may need to trigger this code from a user-initiated event such as a start button being pressed, as described above. note: watch out for bit rates. encoding your audio at lower bit rates means smaller file sizes but lower seeking accuracy. background music music in games can have a powerful emotional effect. you can mix and match various music samples and assuming you can control the volume of your audio element you could cross-fade different musical pieces. using the playbackrate() method you can even adjust the speed of your music without affecting the pitch, to sync it up better with the action. all this is possible using the standard <audio> element and associated htmlmediaelement api, but it becomes much easier and more flexible with the more advanc...
...And 6 more matches
Beginner's guide to media queries - Learn web development
ault to being for all media types. media feature rules after specifying the type, you can then target a media feature with a rule. 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. these features are used to create layouts that respond to different screen sizes. for example, to change the body text color to red if the viewport is exactly 600 pixels, you would use the following media query. @media screen and (width: 600px) { body { color: red; } } open this example in the browser, or view the source. the width (...
...ayouts that respond to different screen sizes. for example, to change the body text color to red if the viewport is exactly 600 pixels, you would use the following media query. @media screen and (width: 600px) { body { color: red; } } open this example in the browser, or view the source. ...
...example, to change the body text color to red if the viewport is exactly 600 pixels, you would use the following media query. @media screen and (width: 600px) { body { color: red; } } open this example in the browser, or view the source. the width (and height) media features can be used as ranges, and therefore be prefixed with min- or max- to indicate that the given value is a minimum, or a maximum. for example, to make the color blue if the viewport is narrower than 600 pixels, use max-width: @media screen and (max-width: 600px) { body { color: blue; } } open this example in the browser, or view the source. in practice, using minimum or maximum values is much more useful for responsive design so you will rarely see width or height used alone. there are...
...And 6 more matches
The HTML5 input types - Learn web development
d always perform security checks on any form-submitted data on the server-side as well as the client-side, because client-side validation is too easy to turn off, so malicious users can still easily send bad data through to your server. read website security for an idea of what could happen; implementing server-side validation is somewhat beyond the scope of this module, but you should bear it in mind. note that a@b is a valid email address according to the default provided constraints. this is because the email input type allows intranet email addresses by default. to implement different validation behavior, you can use the pattern attribute, and you can also custom the error messages; we'll talk how to use these features in the client-side form validation article later on. note: if the d...
...of number. this control looks like a text field but allows only floating-point numbers, and usually provides buttons in the form of a spinner to increase and decrease the value of the control. on devices with dynamic keyboards, the numeric keyboard is generally displayed. the following screenshot (from firefox for android) provides an example: with the number input type, you can constrain the minimum and maximum values allowed by setting the min and max attributes. you can also use the step attribute to set the increment increase and decrease caused by pressing the spinner buttons. by default, the number input type only validates if the number is an integer. to allow float numbers, specify step="any". if omitted, the step value defaults to 1, meaning only whole numbers are valid. let's ...
...validates if the number is an integer. to allow float numbers, specify step="any". if omitted, the step value defaults to 1, meaning only whole numbers are valid. let's look at some examples. the first one below creates a number control whose value is restricted to any value between 1 and 10, and whose increase and decrease buttons change its value by 2. <input type="number" name="age" id="age" min="1" max="10" step="2"> the second one creates a number control whose value is restricted to any value between 0 and 1 inclusive, and whose increase and decrease buttons change its value by 0.01. <input type="number" name="change" id="pennies" min="0" max="1" step="0.01"> the number input type makes sense when the range of valid values is limited, for example a person's age or height. if the ra...
...And 6 more matches
Introducing a complete toolchain - Learn web development
next is only one way that the featured tools can be used for a project. note: it's also worth repeating that not all of these tools need to be run on the command line. many of today's code editors (such as vs code and atom) have integration support for a lot of tools via plugins. introducing our case study the toolchain that we are creating in this article will be used to build and deploy a mini site that lists data (taken from one of nasa's open apis) concerning potentially hazardous space objects that threaten our existence on earth! it looks like this: you can see a live version of the site at near-misses.netlify.com. tools used in our toolchain in this article we're going to use the following tools and features: jsx, a react-related set of syntax extensions that allow you to...
...t. you won't need to know react to follow this tutorial, but we've included this to give you an idea of how a non-native web language could be integrated into a toolchain. the latest built-in javascript features (at time of writing), such as import. useful development tools such as prettier for formatting and eslint for linting. postcss to provide css nesting capabilities. parcel to build and minify our code, and to write a bunch of configuration file content automatically for us. github to manage our source code control. netlify to automate our deployment process. you may not be familiar with all the above features and tools or what they are doing, but don't panic — we'll explain each part as we move through this article. toolchains and their inherent complexity as with any chain...
... deploy to your production server to ensure your software works as intended — this already sounds like a necessary toolchain. 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. we will however be avoiding any superfluous tooling, with the aim of keeping complexity to a minimum. for example, we could have included a tool to minimize our svg file sizes during build. however, this project has only 4 svg images, which were manually minified using svgo before adding them to the project. a couple of prerequisites besides the tools we're going to install that contribute to our toolchain, we mentioned two web services in the above list of tools. let's take this opportu...
...And 6 more matches
How Mozilla's build system works
for many developers, typing mach build to build the tree is sufficient to work with the source tree. this document explains how the build system works. note: this document is not intended for developers who just want to build mozilla. for that, see the build documentation. ...
...phase 1: configure phase 1 centers around the configure script. the configure script is a bash shell script. 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. you don't have to worry about how you obtain a configure file: the build system does this for you. the primary job of configure is to determine characteristics of the system and compiler, apply options passed into it, and validate everything looks ok to build. the primary output of the configure script is an executable file in the object directory called config.status. configure also produces some additional files (like autoconf.mk). however, the most important file in terms of architecture is config.status. the existence of a config.s...
...stem and what the existing build configuration looks like. for example, a data structure defines which compiler to use, how to invoke it, which application features are enabled, and so on. you are encouraged to open config.status to have a look! after we have emitted a config.status file, we proceed to phase 2. phase 2: build backend preparation and the build definition once configure has determined what the current build configuration is, we need to apply this to the source tree so we can actually build. what essentially happens is the automatically produced config.status python script is executed as soon as configure has generated it. config.status is charged with the task of telling a tool how to build the tree. to do this, config.status must first scan the build system definition. th...
...And 6 more matches
IPDL Tutorial
the protocol is declared must have a matching name, pplugin.ipdl. generated c++ code when pplugin.ipdl is compiled, the headers ppluginparent.h, and ppluginchild.h will be generated in the ipc/ipdl/_ipdlheaders/ directory of the build tree. the ppluginparent and ppluginchild classes are abstract classes that must be subclassed. each outgoing message is a c++ method which can be called. each incoming message is a pure-virtual c++ method which must be implemented: class ppluginparent { public: bool sendinit(const nscstring& pluginpath) { // generated code to send an init() message } bool sendshutdown() { // generated code to send a shutdown() message } protected: /** * a subclass of ppluginparent must implement this method to handle the ready() message. */ bool re...
... 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. a custom serializer and deserializer must be provided by your c++ code. 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_boo...
... to initialize a union, simply assign a valid value to it, as follows: avariant = false; structs ipdl has built-in support for arbitrary collections of serializable data types. struct namevaluepair { nscstring name; nscstring value; }; in implementation code, these str...
...And 6 more matches
Mozilla Development Strategies
this article offers some strategies and suggestions to help developers stay productive. warning: the content of this article may be out of date. it has not been updated for usage of mercurial (instead of cvs). work on the most important bugs first everyone likes to check in. but keep in mind that your checkin rate isn't everything. it's better to fix one data loss bug, crasher, or performance bug that really affects the user than edge case bugs that are rarely seen or minor bugs. make sure documentation gets updated if the bug you're fixing is likely to require an update to developer documentation once it's fixed, be sure to add the dev-doc-needed keyword to the bug (or ask someone to do it, if you don't have editbugs privileges on bugzilla). this puts the bug on the radar ...
...n bugzilla). this puts the bug on the radar of our documentation team to ensure that once the bug is resolved, the documentation will be updated appropriately. if you don't mark the bug, your work might go unnoticed by the docs team! of course, our documentation is a wiki; you can really help by updating the documentation yourself. even if you're not comfortable with your writing skills, keep in mind that our helpful, happy documentation gnomes will follow along behind you and clean up for you. note: you can mark the bug with this keyword at any time; you don't need to wait until it's actually fixed. take extra time to do it right the first time it's also better to come up with one really solid, well tested, well commented, clean, easy to maintain piece of code than a bunch of quick fixes...
...e: you can mark the bug with this keyword at any time; you don't need to wait until it's actually fixed. take extra time to do it right the first time it's also better to come up with one really solid, well tested, well commented, clean, easy to maintain piece of code than a bunch of quick fixes. you (or someone else) will be back in that code someday. it's easier to do it right once, when your mind is in the problem, than to do it once quickly and then have to come back and do it again the right way. the only thing worse than not understanding someone else's code is not understanding your own. test your code qa's job is to assure quality, not to add quality. that's your job. it's your responsibility to find and fix the problems in your code before checking in. when you land your bug-free...
...And 6 more matches
JS_GetGCParameter
max_bytes, jsgc_max_malloc_bytes, jsgc_max_nursery_bytes, jsgc_bytes, jsgc_number, jsgc_mode, jsgc_unused_chunks, jsgc_total_chunks, jsgc_slice_time_budget, jsgc_mark_stack_limit, jsgc_high_frequency_time_limit, jsgc_high_frequency_low_limit, jsgc_high_frequency_high_limit, jsgc_high_frequency_heap_growth_max, jsgc_high_frequency_heap_growth_min, jsgc_low_frequency_heap_growth, jsgc_dynamic_heap_growth, jsgc_dynamic_mark_slice, jsgc_allocation_threshold, jsgc_min_empty_chunk_count, jsgc_max_empty_chunk_count, jsgc_compaction_enabled, jsgc_allocation_threshold_factor, jsgc_allocation_threshold_factor_avoid_interrupt, jsgc_nursery_free_threshold_for_idle_collection, jsgc_pretenure_threshold, ...
... jsgc_max_malloc_bytes / "maxmallocbytes" number of js_malloc bytes before last ditch gc. ...
... jsgc_max_malloc_bytes / "maxmallocbytes" number of js_malloc bytes before last ditch gc. ...
...And 6 more matches
Redis Tips
bout redis as a database with some kind of non-existent relationship to sql, think of it as a data structure server with a rich set of commands for querying and manipulating those data structures over a network connection. redis data types include: strings hashes lists sets ordered sets (called zsets in redis) transactions publishers and subscribers this table lists some common programming tasks and data structures, and suggests some redis functions or data structures for them: dictionary lookup set, get, setnx, etc. counters set, incr, incrby list manipulation lpush, rpush, lpop, rpop, llen, linsert, lindex, etc. event logging lists, zsets, pubsub queues lists (rpush, blpop, blpoprpush, etc.) priority queues ...
...mands - an ever-growing list of related commands is given on the right-hand side of the page. recipes - at the bottom of many pages is a section that gives usage patterns or recipes for the command under discussion. there are many insightful ideas to be found here. getting started with redis before you go any further in this document, make sure you have played with redis for at least 5 or 10 minutes. if you have not, here is a fantastic on-line, interactive redis tutorial: http://try.redis.io/ for reference later on, you'll want the source of all things redis: https://redis.io you'll want to run a redis-server on your machine, and use the redis-cli at the command-line for hacking. node.js redis client: https://github.com/mranney/node_redis npm install redis python redis cli...
...re executed sequentially as a single atomic operation. here's a stupid node script to show how this works: #!/usr/bin/env node var r = require('redis').createclient(); r.multi() .set("foo", 42) .set("bar", "ice cream") .set("baz", 6.28) .get("foo") .get("bar") .get("baz") .exec(function(err, resultlist) { console.log(json.stringify(resultlist, null, 2)); r.end(); // terminate the redis connection; node can quit }); when run, this prints: [ "ok", "ok", "ok", "42", "ice cream", "6.28" ] the result list includes one value per each command executed. awesome. note that if one of your commands crashes, the others still all execute! (try this by breaking one of the set statements by leaving out the value argument.) you'll get one return value for ea...
...And 6 more matches
Starting WebLock
erface: one that takes a cid and another interface that takes a contract id. here we'll use the latter. the first parameter to the getservicebycontractid is of course the contract id, which is defined in the nsxpcom.h header file. the next parameter is a nifty macro that returns the iid for the interface name that you pass in. the last parameter assigns an out interface pointer to a nscomptr. assuming there weren't any unexpected errors, the variable catman holds the nsicategorymanager interface pointer, which you can use to add the component as a startup observer by calling a method on the nsicategorymanager. the next step is to figure out which parameters to pass to the method. there is a category name and a name-value pair, but since the name-value pair meaning is category-specific, you n...
... id yes xpcom-shutdown any contract id no xpcom-autoregistration any contract id no app-startup any service, contract id * the table above summarizes the popular persistent notifications registered through the category manager. the name of the category itself is a well defined string, but the name-value pairs can be anything. when naming your component in the category, take care to use something that means something and doesn't muddy up the namespace. in this case, "weblock" is unique and provides context to anyone looking at the category. the value of the name-value part is expected to be the contract id of the component. since every category can define the name-value pairs, the application "app-startup" category can support n...
...lock component in this tutorial uses xul to define the additional browser ui in a cross-platform way, and xul uses javascript to access and control xpcom components, but gecko's pluggable ui allows any user interface to call into gecko and the components you create as easily as you can from xul. see xul for a discussion of how xul interacts with javascript and xpcom. creating the weblock programming interface design is one of the hardest parts of any programming problem. the question the interface for the weblock component must answer is: how should weblock look to the outside world? what, in other words, is the interaction of clients with the weblock component? in this section, we enumerate the basic functionality the component should expose and create the single interface that organizes ...
...And 6 more matches
NS_ConvertASCIItoUTF16
ndcharinset equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii ...
... @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the ...
...rs nsstring& atarget nsstring& anewvalue void replacesubstring(const prunichar*, const prunichar*) - source parameters prunichar* atarget prunichar* anewvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string. you can control whether whitespace is yanked from start a...
...And 6 more matches
NS_ConvertUTF16toUTF8
compare equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii ...
... @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the ...
... source parameters nscstring& atarget nscstring& anewvalue void replacesubstring(const char*, const char*) - source parameters char* atarget char* anewvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string. you can control whether whitespace is yanked from start a...
...And 6 more matches
NS_ConvertUTF8toUTF16
ndcharinset equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii ...
... @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the ...
...rs nsstring& atarget nsstring& anewvalue void replacesubstring(const prunichar*, const prunichar*) - source parameters prunichar* atarget prunichar* anewvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string. you can control whether whitespace is yanked from start a...
...And 6 more matches
NS_LossyConvertUTF16toASCII
compare equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii ...
... @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the ...
... source parameters nscstring& atarget nscstring& anewvalue void replacesubstring(const char*, const char*) - source parameters char* atarget char* anewvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string. you can control whether whitespace is yanked from start a...
...And 6 more matches
nsAdoptingCString
compare equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii appendliteral(c...
... @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the ...
... source parameters nscstring& atarget nscstring& anewvalue void replacesubstring(const char*, const char*) - source parameters char* atarget char* anewvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string. you can control whether whitespace is yanked from start a...
...And 6 more matches
nsAdoptingString
ndcharinset equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii appendliteral(c...
... @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the ...
...rs nsstring& atarget nsstring& anewvalue void replacesubstring(const prunichar*, const prunichar*) - source parameters prunichar* atarget prunichar* anewvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string. you can control whether whitespace is yanked from start a...
...And 6 more matches
nsAutoString
ndcharinset equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii ...
... @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the ...
...rs nsstring& atarget nsstring& anewvalue void replacesubstring(const prunichar*, const prunichar*) - source parameters prunichar* atarget prunichar* anewvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string. you can control whether whitespace is yanked from start a...
...And 6 more matches
nsCAutoString
arat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char assign assignascii assignliteral(const char assi...
... @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search ...
... nscstring& atarget nscstring& anewvalue void replacesubstring(const char*, const char*) - source parameters char* atarget char* anewvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string. you can control whether whitespace is ya...
...And 6 more matches
nsFixedCString
compare equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii ...
... @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the ...
... source parameters nscstring& atarget nscstring& anewvalue void replacesubstring(const char*, const char*) - source parameters char* atarget char* anewvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string. you can control whether whitespace is yanked from start a...
...And 6 more matches
nsFixedString
ndcharinset equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii ...
... @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the ...
...rs nsstring& atarget nsstring& anewvalue void replacesubstring(const prunichar*, const prunichar*) - source parameters prunichar* atarget prunichar* anewvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string. you can control whether whitespace is yanked from start a...
...And 6 more matches
nsPromiseFlatCString
compare equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii ...
... @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the ...
... source parameters nscstring& atarget nscstring& anewvalue void replacesubstring(const char*, const char*) - source parameters char* atarget char* anewvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string. you can control whether whitespace is yanked from start a...
...And 6 more matches
nsPromiseFlatString
ndcharinset equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii ...
... @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the ...
...rs nsstring& atarget nsstring& anewvalue void replacesubstring(const prunichar*, const prunichar*) - source parameters prunichar* atarget prunichar* anewvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string. you can control whether whitespace is yanked from start a...
...And 6 more matches
nsXPIDLCString
compare equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii appendliteral(c...
... @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the ...
... source parameters nscstring& atarget nscstring& anewvalue void replacesubstring(const char*, const char*) - source parameters char* atarget char* anewvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string. you can control whether whitespace is yanked from start a...
...And 6 more matches
nsXPIDLString
ndcharinset equalsignorecase tofloat tointeger mid left right setcharat stripchars stripwhitespace replacechar replacesubstring trim compresswhitespace assignwithconversion appendwithconversion appendint appendfloat beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char assign assignascii assignliteral(const char assignliteral(char adopt replace replaceascii append appendascii appendliteral(c...
... @param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search. use -1 to search the ...
...rs nsstring& atarget nsstring& anewvalue void replacesubstring(const prunichar*, const prunichar*) - source parameters prunichar* atarget prunichar* anewvalue trim void trim(const char*, prbool, prbool, prbool) - source this method trims characters found in atrimset from either end of the underlying string. @param aset -- contains chars to be trimmed from both ends @param aeliminateleading @param aeliminatetrailing @param aignorequotes -- if true, causes surrounding quotes to be ignored @return this parameters char* aset prbool aeliminateleading prbool aeliminatetrailing prbool aignorequotes compresswhitespace void compresswhitespace(prbool, prbool) - source this method strips whitespace from string. you can control whether whitespace is yanked from start a...
...And 6 more matches
nsIScrollable
gecko 29.0 (firefox 29.0 / thunderbird 29.0 / seamonkey 2.26) method overview long getcurscrollpos(in long scrollorientation); obsolete since gecko 29.0 long getdefaultscrollbarpreferences(in long scrollorientation); void getscrollbarvisibility(out boolean verticalvisible, out boolean horizontalvisible); void getscrollrange(in long scrollorientation, out long minpos, out long maxpos); obsolete since gecko 29.0 void setcurscrollpos(in long scrollorientation, in long curpos); obsolete since gecko 29.0 void setcurscrollposex(in long curhorizontalpos, in long curverticalpos); obsolete since gecko 29.0 void setdefaultscrollbarpreferences(in long scrollorientation, in long scrollbarpref); void setscrollrange(in long scrollori...
... constant value description scrollorientation_x 1 horizontal scrolling. when passing t...
... constant value description scrollorientation_x 1 horizontal scrolling. when passing this in to a method you are requesting or setting data for the horizontal scrollbar. ...
...And 6 more matches
nsITreeView
es attribute type description rowcount long the total number of rows in the tree (including the offscreen rows). read only. selection nsitreeselection the selection for this view. ...
... rowcount long the total number of rows in the tree (including the offscreen rows). read only. selection nsitreeselection the selection for this view. ...
...to get the behavior where drops are only allowed on items, such as the mailnews folder pane, always return false when the orientation is not drop_on. note: drop_on will only be passed to candrop() if the item is a container; see iscontainer(). boolean candrop( in long index, in long orientation, in nsidomdatatransfer datatransfer ); param...
...And 6 more matches
WebIDL bindings
d to flag the functions that return your object as [newobject] in the webidl. if your object is not refcounted then the return value of functions that return it should return an nsautoptr. c++ reflections of webidl constructs c++ reflections of webidl operations (methods) a webidl operation is turned into a method call on the underlying c++ object. the return type and argument types are determined as described below. in addition to those, all methods that are allowed to throw will get an errorresult& argument appended to their argument list. non-static methods that use certain webidl types like any or object will get a jscontext* argument prepended to the argument list. static methods will be passed a const globalobject& for the relevant global and can get a jscontext* by calling context...
... like this: struct dict { bool init(jscontext* acx, js::handle<js::value> aval, const char* asourcedescription = "value"); optional<nsstring> mbar; int32_t mfoo; } note that the dictionary members are sorted in the struct in alphabetical order. api for working with dictionaries there are a few useful methods found on dictionaries and dictionary members that you can use to quickly determine useful things. member.waspassed() - as the name suggests, was a particular member passed? (e.g., if (arg.foo.waspassed() { /* do nice things!*/ }) dictionary.isanymemberpresent() - great for checking if you need to do anything. (e.g., if (!arg.isanymemberpresent()) return; // nothing to do) member.value() - getting the actual data/value of a member that was passed. (e.g., mbar.ass...
..., errorresult& arv); bool has(mozilla::dom::stringset* self, const nsastring& akey, errorresult& arv); void add(mozilla::dom::stringset* self, const nsastring& akey, errorresult& arv); } // namespace setlikehelpers } iterable unlike maplike and setlike, iterable does not have any c++ helpers, as the structure backing the iterable data for the interface is left up to the developer. with that in mind, the generated iterable bindings expect the wrapper object to provide certain methods for the interface to access. iterable interfaces have different requirements, based on if they are single or pair value iterators. example interface for a single value iterator: interface longiterable { iterable<long>; getter long(unsigned long index); readonly attribute unsigned long length; }; for s...
...And 6 more matches
Streams - Plugins
a stream is created telling the plug-in when a stream is deleted finding out how much data the plug-in can accept writing the stream to the plug-in sending the stream in random-access mode sending the stream in file mode telling the plug-in when a stream is created to tell the plug-in instance when a new stream is created, the browser calls the npp_newstream method. this method also determines which mode it should use to send data to the plug-in. the browser can create a stream for several different types of data: for the file specified in the data attribute of the object element or the src attribute of the embed element for a data file for a full-page instance the npp_newstream method has the following syntax: nperror npp_newstream(npp instance, npmimetype type, npstream *s...
...modes except np_seek. note: a plug-in can also use the npn_geturl method to request a stream for an arbitrary url. telling the plug-in when a stream is deleted the browser calls the npp_destroystream method when it completes the stream sent to the plug-in, either successfully or abnormally. once the plug-in returns from this method, the browser deletes the npstream object. the plug-in can terminate the stream itself by calling npn_destroystream. you should delete any private data allocated in the plug-in's stream->pdata field when you destroy a stream. the plug-in can store private data associated with the stream in stream->pdata. the browser stores private data in stream->ndata; this value should not be changed by the plug-in. nperror npp_destroystream(npp instance, npstream *stream,...
...rectly by some action, such as by deleting the instance or initiating higher-priority network operations. npres_network_err: the stream failed because of problems with the network, disk i/o error, lack of memory, or some other problem. finding out how much data the plug-in can accept after a call to npp_newstream and before writing data to the plug-in, the browser calls npp_writeready to determine the maximum number of bytes that the plug-in can consume. this function allows the browser to send only as much data to the instance as it can handle at one time, and it helps both the browser and the plug-in to use their resources efficiently. after a call to npp_newstream, in which the plug-in requested a normal-mode stream, the browser delivers the data in the stream progressively in a serie...
...And 6 more matches
HTMLInputElement - Web APIs
rface provides special properties and methods for manipulating the options, layout, and presentation of <input> elements. ...
...e provides special properties and methods for manipulating the options, layout, and presentation of <input> elements. ...
...st> ancestor; its disabled property is true. properties that apply only to elements of type checkbox or radio checked boolean: returns / sets the current state of the element when type is checkbox or radio. defaultchecked boolean: returns / sets the default state of a radio button or checkbox as originally specified in html that created this object. indeterminate boolean: returns whether the checkbox or radio button is in indeterminate state. for checkboxes, the effect is that the appearance of the checkbox is obscured/greyed in some way as to indicate its state is indeterminate (not checked but not unchecked). does not affect the value of the checked attribute, and clicking the checkbox will set the value to false. properties that apply on...
...And 6 more matches
Capabilities, constraints, and settings - Web APIs
often, your code needs to know whether or not an api exists and if so, what its limitations are on the user agent it's running on. figuring this out has often been difficult, and has usually involved looking at some combination of which user agent (or browser) you're running on, which version it is, looking to see if certain objects exist, trying to see whether various things work or not and determining what errors occur, and so forth. the result has been a lot of very fragile code, or a reliance on libraries which figure this stuff out for you, then implement polyfills to patch the holes in the implementation on your behalf. the twin concepts of constraints and capabilities let the browser and web site or app exchange information about what constrainable properties the browser's implementat...
...ormation about what constrainable properties the browser's implementation supports and what values it supports for each one. this article discusses capabilities and constraints, as well as media settings, and includes an example we call the constraint exerciser. the constraint exerciser lets you experiment with the results of different constraint sets being applied to the audio and video tracks coming from the computer's a/v input devices (such as its webcam and microphone). 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. this isn't always necessary, since any that aren't known will simply be i...
... browser knows about. this isn't always necessary, since any that aren't known will simply be ignored when you specify them—but if you have any that you can't get by without, you can start by checking to be sure they're on the list. once the script knows whether the property or properties it wishes to use are supported, it can then check the capabilities of the api and its implementation by examining the object returned by the track's getcapabilities() method; this object lists each supported constraint and the values or range of values which are supported. finally, the track's applyconstraints() method is called to configure the api as desired by specifying the values or ranges of values it wishes to use for any of the constrainable properties about which it has a preference. the track'...
...And 6 more matches
Pointer events - Web APIs
additionally, a pointer event contains the usual properties present in mouse events (client coordinates, target element, button states, etc.) in addition to new properties for other forms of input: pressure, contact geometry, tilt, etc. in fact, the pointerevent interface inherits all of the mouseevent properties, thus facilitating the migration of content from mouse events to pointer events. terminology active buttons state the condition when a pointer has a non-zero value for the buttons property. for example, in the case of a pen, when the pen has physical contact with the digitizer, or at least one button is depressed while hovering. active pointer any pointer input device that can produce events. a pointer is considered active if it can still produce further events. for example, a...
...fted or moved. digitizer a sensing device with a surface that can detect contact. most commonly, the sensing device is a touch-enabled screen that can sense input from an input device such as a pen, stylus, or finger. some sensing devices can detect the close proximity of the input device, and the state is expressed as a hover following the mouse. hit test the process the browser uses to determine a target element for a pointer event. typically, this is determined by considering the pointer's location and also the visual layout of elements in a document on screen media. pointer a hardware-agnostic representation of input devices that can target a specific coordinate (or set of coordinates) on a screen. examples of pointer input devices are mouse, pen/stylus, and touch contacts. pointer...
...ies are read only .) pointerid a unique identifier for the pointer causing the event. width the width (magnitude on the x axis), in css pixels, of the contact geometry of the pointer. height the height (magnitude on the y axis), in css pixels, of the contact geometry of the pointer. pressure the normalized pressure of the pointer input in the range of 0 to 1, where 0 and 1 represent the minimum and maximum pressure the hardware is capable of detecting, respectively. tangentialpressure the normalized tangential pressure of the pointer input (also known as barrel pressure or cylinder stress) in the range -1 to 1, where 0 is the neutral position of the control. tiltx the plane angle (in degrees, in the range of -90 to 90) between the y–z plane and the plane containing both the po...
...And 6 more matches
SVGPreserveAspectRatio - Web APIs
which means that attempts to modify the object will result in an exception being thrown. ...
...h means that attempts to modify the object will result in an exception being thrown. ...
... will result in an exception being thrown. ...
...And 6 more matches
Adding 2D content to a WebGL context - Web APIs
itions of the pixels and their colors. there are two shader functions run when drawing webgl content: the vertex shader and the fragment shader. you write these in glsl and pass the text of the code into webgl to be compiled for execution on the gpu. together, a set of vertex and fragment shaders is called a shader program. let's take a quick look at the two types of shader, with the example in mind of drawing a 2d shape into the webgl context. vertex shader each time a shape is rendered, the vertex shader is run for each vertex in the shape. its job is to transform the input vertex from its original coordinate system into the clip space coordinate system used by webgl, in which each axis has a range from -1.0 to 1.0, regardless of aspect ratio, actual size, or any other factors. the ver...
... 1.0, regardless of aspect ratio, actual size, or any other factors. the vertex shader must perform the needed transforms on the vertex's position, make any other adjustments or calculations it needs to make on a per-vertex basis, then return the transformed vertex by saving it in a special variable provided by glsl, called gl_position. the vertex shader can, as needed, also do things like determine the coordinates within the face's texture of the texel to apply to the vertex, apply the normals to determine the lighting factor to apply to the vertex, and so on. this information can then be stored in varyings or attributes as appropriate to be shared with the fragment shader. our vertex shader below receives vertex position values from an attribute we define called avertexposition. that pos...
...ix * 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. but when we do our math, we will need it to be a vec4, so rather than convert it to a vec4 every time we do math, we'll just use a vec4 from the beginning. this eliminates operations from every calculation we do in our shader. performance matters. in this example, we're not computing any lighting at all, since we haven't yet applied any to the scene. that will come later, in the example lighting in webgl. note also the lack of any work with textures here; that will be added in using textures in webgl. fragment shader the fragment shader is called once for ev...
...And 6 more matches
Fundamentals of WebXR - Web APIs
the needed data to let you update the imagery shown to the user based on that movement. webxr additionally provides support for accepting inputs from control devices such as handheld vr controllers or specialized mixed reality gamepads. webxr is not a rendering technology, and provides no features for actually managing 3d data or rendering it to the display. this is an important fact to keep in mind; while webxr manages the timing, scheduling, and the various points of view relevant when drawing the scene, it does not actually know how to load and manage models, render and texture them, and so forth. that part is entirely up to you. fortunately, webgl and the various webgl-based frameworks and libraries are available to make it much easier to deal with all of that. how is webxr different f...
... does not actually know how to load and manage models, render and texture them, and so forth. that part is entirely up to you. fortunately, webgl and the various webgl-based frameworks and libraries are available to make it much easier to deal with all of that. how is webxr different from webvr? webvr was generally considered to be an experimental api designed to help specification writers determine the best approaches to creating an api for virtual reality on the web. as browser developers built support for webvr and allowed developers to experiment, it became clear that in order to finish an api for virtual environments on the web, it would make more sense to start a new specification than to try to "fix" webvr. thus, webxr was created. the most obvious difference, at the highest level, ...
...ile devices. what is field of view? the field of view is, at its essence, the extent of the environment you are able to see at any one time. the width of the field of view is measured as the angle defining the arc from the far left edge of your field of view to the far right edge, and is specified in either degrees or radians. a human eye is typically able to take in a fov of around 135°. assuming a person has two healthy eyes, their total field of view is about 200° to 220° wide. why is the fov wider with two eyes, but not double the single-eye fov? it's because the two eyes fovs overlap a lot. that overlap is what gives us depth perception; within the overlap area — which is around 115° across — we have depth perception. outside that overlap area, our vision is monocular and lack...
...And 6 more matches
Grid template areas - CSS: Cascading Style Sheets
orward way to place items on your grid. however, there is an alternate method to use for positioning items on the grid which you can use alone or in combination with line-based placement. this method involves placing our items using named template areas, and we will find out exactly how this method works. you will see very quickly why we sometimes call this the ascii-art method of grid layout! naming a grid area you have already encountered the grid-area property. this is the property that can take as a value all four of the lines used to position a grid area. .box1 { grid-area: 1 / 1 / 4 / 2; } what we are doing here when defining all four lines, is defining the area by specifying the lines that enclose that area. we can also define an area by giving it a name and then specify the...
...-area: hd; } .footer { grid-area: ft; } .content { grid-area: main; } .sidebar { grid-area: sd; } having defined these names i then create my layout. this time, instead of placing my items using line numbers specified on the items themselves, i create the whole layout on the grid container. ...
... . . ft ft ft ft ft ft"; } <div class="wrapper"> <div class="header">header</div> <div class="sidebar">sidebar</div> <div class="content">content</div> <div class="footer">footer</div> </div> in order to make the layout nea...
...And 6 more matches
attr() - CSS: Cascading Style Sheets
Web › CSS › attr
d that points to a non-existent document with a generic error condition. integer <integer> the attribute value is parsed as a css <integer>. if it is not valid, that is not an integer or out of the range accepted by the css property, the default value is used. leading and trailing spaces are stripped. 0, or, if 0 is not a valid value for the property, the property's minimum value. number <number> the attribute value is parsed as a css <number>. if it is not valid, that is not a number or out of the range accepted by the css property, the default value is used. leading and trailing spaces are stripped. 0, or, if 0 is not a valid value for the property, the property's minimum value. length <length> the attribute...
...parsed as a css <length> dimension, that is including the unit (e.g. 12.5em). if it is not valid, that is not a length or out of the range accepted by the css property, the default value is used. if the given unit is a relative length, attr() computes it to an absolute length. leading and trailing spaces are stripped. 0, or, if 0 is not a valid value for the property, the property's minimum value. em, ex, px, rem, vw, vh, vmin, vmax, mm, cm, in, pt, or pc <length> the attribute value is parsed as a css <number>, that is without the unit (e.g. 12.5), and interpreted as a <length> with the specified unit. if it is not valid, that is not a number or out of the range accepted by the css property, the default value is used. if the given unit is a relative l...
... the unit (e.g. 12.5), and interpreted as a <length> with the specified unit. if it is not valid, that is not a number or out of the range accepted by the css property, the default value is used. if the given unit is a relative length, attr() computes it to an absolute length. leading and trailing spaces are stripped. ...
...And 6 more matches
<input type="tel"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › tel
sing a specific input type for telephone numbers also makes adding custom validation and handling of phone numbers more convenient. note: browsers that don't support type tel fall back to being a standard text input. value a domstring representing a telephone number, or empty events change and input supported common attributes autocomplete, list, maxlength, minlength, pattern, placeholder, readonly, and size idl attributes list, selectionstart, selectionend, selectiondirection, and value methods select(), setrangetext(), setselectionrange() value the <input> element's value attribute contains a domstring that either represents a telephone number or is an empty string (""). additional attributes in addition to the attrib...
...in addition to the attributes that operate on all <input> elements regardless of their type, telephone number inputs support the following attributes: attribute description list the id of the <datalist> element that contains the optional pre-defined autocomplete options maxlength the maximum length, in utf-16 characters, to accept as a valid input minlength the minimum length that is considered valid for the field's contents pattern a regular expression the entered value must match to pass constraint validation placeholder an example value to display inside the field when it has no value readonly a boolean attribute which, if present, indicates that the field's contents should not be user-editable ...
...lect from this predefined list or provide a different value. maxlength the maximum number of characters (as utf-16 code units) the user can enter into the telephone number field. this must be an integer value 0 or higher. if no maxlength is specified, or an invalid value is specified, the telephone number field has no maximum length. ...
...And 6 more matches
A re-introduction to JavaScript (JS tutorial) - JavaScript
it is often derided as being a toy, but beneath its layer of deceptive simplicity, powerful language features await. javascript is now used by an incredible number of high-profile applications, showing that deeper knowledge of this technology is an important skill for any web or mobile developer. it's useful to start with an overview of the language's history. javascript was created in 1995 by brendan eich while he was an engineer at netscape. javascript was first released with netscape 2 early in 1996. ...
... since. the fourth edition was abandoned, due to political differences concerning language complexity. many parts of the fourth edition formed the basis for ecmascript edition 5, published in december of 2009, and for the 6th major edition of the standard, published in june of 2015. because it is more familiar, we will refer to ecmascript as "javascript" from this point on. unlike most programming languages, the javascript language has no concept of input or output. it is designed to run as a scripting language in a host environment, and it is up to the host environment to provide mechanisms for communicating with the outside world. the most common host environment is the browser, but javascript interpreters can also be found in a huge list of other places, including adobe acrobat, adobe ...
...lete desktop environments like gnome (one of the most popular guis for gnu/linux operating systems), and others. overview javascript is a multi-paradigm, dynamic language with types and operators, standard built-in objects, and methods. its syntax is based on the java and c languages — many structures from those languages apply to javascript as well. javascript supports object-oriented programming with object prototypes, instead of classes (see more about prototypical inheritance and es2015 classes). javascript also supports functional programming — because they are objects, functions may be stored in variables and passed around like any other object. let's start off by looking at the building blocks of any language: the types. javascript programs manipulate values, and those values al...
...And 6 more matches
Lexical grammar - JavaScript
ecmascript also defines certain keywords and literals and has rules for automatic insertion of semicolons to end statements. control characters control characters have no visual representation but are used to control the interpretation of the text. ...
...red using their connected form in certain languages (wikipedia). u+feff byte order mark <bom> used at the start of the script to mark it as unicode and the text's byte order (wikipedia). white space white space characters improve the readability of source text and separate tokens from each other. these characters are usually unnecessary for the functionality of the code. minification tools are often used to remove whitespace in order to reduce the amount of data that needs to be transferred. white space characters code point name abbreviation description escape sequence u+0009 character tabulation <ht> horizontal tabulation \t u+000b line tabulation <vt> vertical tabulation \v u+000c for...
...on <vt> vertical tabulation \v u+000c form feed <ff> page breaking control character (wikipedia). ...
...And 6 more matches
The Box Model - Archive of obsolete content
it is important to know how it works in order to make interfaces that are easy to localize, skin and use in different types of operating systems, screen sizes and resolutions. the xul box model is a significant improvement over the html layout model, which is mostly vertical. with xul you can define vertically oriented as well as horizontally oriented interfaces, providing greater flexibility in interface design. ...
...uch too often, and it would require a great deal of css code to avoid using it. at any rate, it can always be overriden using css, so your extension won't lose skinability because of it. flexibility is defined as a numeric value. the default value for most elements is 0, which means that the element will not stretch in the direction of its orientation, and its size in that dimension will be determined by its contents and padding. if you want an element to be flexible, you should set its flexibility to 1. this makes the element stretch to occupy as much available space there is in the direction of its orientation. if we add flexibility to the hbox in our first example, we get the following result: the box flexes to cover the available horizontal space. the buttons maintain their size. if ...
...ow the flexible button is taking the available inner space, moving the other two buttons all the way to the end of the box. what would happen if we also add flexibility to the "parrot" button? since both buttons have a flexibility of 1, the available space is distributed evenly among the two. note that this is not always the case. if one of the buttons has a very long label that restricts its minimum size, then it could be the label determining its size, while the other button would flex taking the rest of the room. now, if you want a different size distribution in flexible elements, you can use flexibility values higher than 1. in this case, the "cat" button has a flex value of 3, while the "parrot" button still has a flex value of 1. the "cat" button is now larger in a 3 to 1 propor...
...And 5 more matches
Using XPInstall to Install Plugins - Archive of obsolete content
are component to be installed. in our case, this is the plugin software. a javascript file called install.js, which is the install logic that drives the installation. this includes instructions on where to install the software, and what messages to feed to the user. you can create an xpinstall file by first zipping all the items you want installed with winzip (create a zip archive) and then renaming it with the xpi file extension instead of the zip file extension. unlike native code installers (for example, files called setup.exe), the programming language for install operations in xpi is javascript. since the file format that contains the software and the install.js javascript file is a cross-platform file (zip) and since javascript is understood by mozilla browsers on all platforms, often...
... because of the similarity between the two installer technologies, it is easy to convert your smartupdate files to xpinstall files. smartupdate involves a digitally signed jar file which contained the software components to be installed as well as a javascript install.js file (called the install script) as the installer logic. downloads and installs would be initiated with a security dialog box naming the certificate authority and the signer. often, the smartupdate download was triggered via the pluginurl attribute of the embed tag: <embed type="application/x-randomtype" src="myfile.typ" width="50" height="50" pluginurl="http://mytypecompany.xyz/jarpacks/mytypeplugin.jar"></embed> in the example above, the pluginurl attribute points to the signed jar file, which netscape communicator 4.x wo...
...pplication a string signifying the plugin identifier associated with the plugin. this value is actually entered in the client version registry upon installation, a mozilla-browser file that stores metadata about the software that has just been installed. this value can be queried via web-page delivered javascript, and is useful for initiating xpinstall downloads via trigger scripts. you can determine the version of the software that has been installed, and determine whether to update it, all via javascript in a web-page. a string representing the four digit version of the software. caveat: certain versions of mozilla-based browsers (such as netscape 6.x) treat the use of the equals character ("=") as an illegal token and thus do not allow invocation of initinstall with strings containing "...
...And 5 more matches
timepicker - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] the timepicker is used to allow the user to enter a time. it contains three fields to enter the hour, minute and second. arrow buttons next to the fields allow the values to be adjusted with the mouse. a fourth textbox appears for 12 hour clocks which allows selection of am or pm. to specify the initial, use the value attribute set to a value of either the form hh:mm:ss or hh:mm. the value may be retrieved and changed using the value property or the datevalue property. ...
...x appears for 12 hour clocks which allows selection of am or pm. to specify the initial, use the value attribute set to a value of either the form hh:mm:ss or hh:mm. the value may be retrieved and changed using the value property or the datevalue property. the former specifies the time as a string of the form hh:mm:ss whereas the latter specifies the time as a date object. in addition, the hour, minute and second properties may be used to retrieve and modify each component of the time separately. the change event is fired whenever the time is changed. 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. to avoid this, you can use the workaround described here, i.e., use window.se...
... erratic behavior when the time is changed using the keyboard instead of the mouse. to avoid this, you can use the workaround described here, i.e., use window.settimeout(actual-event-handler-function, 0); to queue up your event handler to run after the rest of the picker's change event handlers. attributes disabled, hideseconds, increment, readonly, tabindex, value properties amindicator, datevalue, disabled, hideseconds, hour, hourleadingzero, increment, is24hourclock, ispm, minute, minuteleadingzero, pmindicator, readonly, second, secondleadingzero, tabindex, value examples <timepicker value="12:05"/> attributes disabled type: boolean indicates whether the element is disabled or not. if this attribute is set, the element is disabled. disabled elements ar...
...And 5 more matches
The Business Benefits of Web Standards - Archive of obsolete content
velopers - both agency and inhouse - simply do not want to work using outdated methodologies and platforms with uncertain standards, with all the consequent uncertainty in quality. they have adopted web standards long ago and now work where these new skills are appreciated. familiarity with dreamweaver or any other legacy software is not a good basis for hiring creative development personnel. eliminate unwelcome future costs a very significant portion of electronically-stored information is produced for the web and written in html format. most of this information uses invalid html which happens to be displayed correctly in permissive older browsers. as the web evolves, web browsers may eventually become either less permissive, or behave differently when given invalid markup (e.g. parse inva...
... any additional costs in the future. extensibility using strict html and separating structure from content paves the way to xhtml, an xml-compatible version of html. using xhtml will enable web authors to leverage tools from the xml world, such as xslt, to easily manipulate xml data. using xhtml is a way to enter a set of standards composed of xml-based technologies, such as xml, xslt (transforming data), svg (animated graphics), mathml (describing mathematic expressions)... such technologies have been designed to be interoperable, are the base of web services. this goes much further than just web authoring. reduce costs of maintenance and site operations what is maintenance anyway? one of the most important features of a successful site is constantly evolving relevant content which in t...
...need not become involved in the actual process of publishing that content at all. and the person applying the markup need not necessarily, know (or care) how it is going to be styled. that has been the real impact of the zen garden, in helping to demonstrate the stunning results which are possible without altering the markup, and indeed keeping the amount of presentational markup to an acceptable minimum. the content - markup - style; model also lends itself very neatly to linear methods of production. no web development activity need or indeed - should take place until the content has been produced. conversely once the content is to hand the development/publishing process should be lighteningly fast. which is as it should be. if we have produced content we want to publish it now. not in 6 w...
...And 5 more matches
JavaScript basics - Learn web development
it was invented by brendan eich (co-founder of the mozilla project), the mozilla foundation, and the mozilla corporation. javascript is versatile and beginner-friendly. ...
...it was invented by brendan eich (co-founder of the mozilla project), the mozilla foundation, and the mozilla corporation. javascript is versatile and beginner-friendly. ...
...nd the mozilla corporation. javascript is versatile and beginner-friendly. with more experience, you'll be able to create games, animated 2d and 3d graphics, comprehensive database-driven apps, and much more! javascript itself is relatively compact, yet very flexible. developers have written a variety of tools on top of the core javascript language, unlocking a vast amount of functionality with minimum effort. these include: browser application programming interfaces (apis) built into web browsers, providing functionality such as dynamically creating html and setting css styles; collecting and manipulating a video stream from a user's webcam, or generating 3d graphics and audio samples. third-party apis that allow developers to incorporate functionality in sites from other content provi...
...And 5 more matches
A first splash into JavaScript - Learn web development
what javascript is. objective: to have a first bit of experience at writing some javascript, and gain at least a basic understanding of what writing a javascript program involves. ...
... you won't be expected to understand all of the code in detail immediately — we just want to introduce you to the high-level concepts for now, and give you an idea of how javascript (and other programming languages) work. in subsequent articles, you'll revisit all these features in a lot more detail! note: many of the code features you'll see in javascript are the same as in other programming languages — functions, loops, etc. the code syntax looks different, but the concepts are still largely the same. thinking like a programmer one of the hardest things to learn in programming is not the syntax you need to learn, but how to apply it to solve real world problems. you need to start thinking like a programmer — this generally involves looking at descriptions of what your progra...
... programming is not the syntax you need to learn, but how to apply it to solve real world problems. you need to start thinking like a programmer — this generally involves looking at descriptions of what your program needs to do, working out what code features are needed to achieve those things, and how to make them work together. this requires a mixture of hard work, experience with the programming syntax, and practice — plus a bit of creativity. the more you code, the better you'll get at it. we can't promise that you'll develop "programmer brain" in five minutes, but we will give you plenty of opportunity to practice thinking like a programmer throughout the course. ...
...And 5 more matches
Mozilla’s UAAG evaluation report
12, 2001 candidate recommendation of uaag 1.0. this may be different from the most recent version, check for updates on the user agent working group home page. look to the "techniques" document for real-world implementation examples of each checkpoint. this uaag evaluation report covers nightly builds of the mozilla web browser itself, running on windows 2000, as of february 20, 2002. we are claiming to support html 4, css 2, png, jpg and gif. this evaluation does not cover mailnews or composer. there may be accessibility and customizability features not listed here. a very good resource is the customizing document. when filing mozilla bugs based on uaag requirements, please use bug 24413 as the uaag meta bug. checkpoint information (same scaled used on w3c's uaag implementation reports page...
...ltimedia players 2.6 respect synchronization cues. (p1) na this relates to multimedia players 2.7 repair missing content. (p2) p no alt repair strategies in place. reasons: the title attribute is almost never present when the alt isn't. in the rare cases where it is, it is of no help (typically it's just the filename, maybe with a file size). also, in the overwhelming majority of cases, the filename is unintelligible. developers interested in this problem can look at the getalternatetext() method -- see the cvs history for suggestions. we consider this to be a very difficult problem. 2.8 no repair text. (p3) p we have no repair strategy in 2.7 we have no way to configure that alt="" still needs to be repaired 2.9 render conditional...
...7 toggle images. (p2) p our interface for image toggling needs redesign unfortunately, there are quite a few open bugs on image toggling guideline 4. ensure user control of rendering. checkpoint title status notes/plans checkpoint title status notes/plans 4.1 configure text size. ...
...And 5 more matches
Debugging Table Reflow
is anonymous and what kind of constrained has been appliedcolindex=0 isanonymous=0 constraint=0. the following constraint types are known: enoconstraint = 0, epixelconstraint = 1, // pixel width epercentconstraint = 2, // percent width eproportionconstraint = 3, // 1*, 2*, etc. ...
...width epercentconstraint = 2, // percent width eproportionconstraint = 3, // 1*, 2*, etc. ...
...nt = 2, // percent width eproportionconstraint = 3, // 1*, 2*, etc. cols attribute assigns 1* e0proportionconstraint = 4 // 0*, means to force to min width after this follows the width information for each column: widths=-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 the table code knows ten different width's: #define num_widths 10 #define num_major_widths 3 // min, des, fix #define min_con 0 // minimum width required of the content + padding #define des_con 1 // desired width of the content + padding #define fix 2 // fixed width either from the content or cell, col, etc. ...
...And 5 more matches
nss tech note1
to use the nss asn.1 and quickder decoders nss technical note: 1 nss 3.6 contains several decoders for asn.1 and der.two of them are extensively used and are part of the public nss api : the "classic" asn.1 decoder, written by lisa repka . this was written to be a generic decoder, that includes both der (distinguished encoding rules) and ber (basic encoding rules).† it handles both streaming and non-streaming input. the "quickder" decoder, written by julien pierre for nss 3.6 . this decoder was written when performance issues were discovered with the classic decoder. it can only decode der .† it does not handle streaming input, and requires that all input be present before beginning to decode. despite their differences, the two decoders have a lot in common. quickder was writ...
...t before beginning to decode. despite their differences, the two decoders have a lot in common. quickder was written to be as compatible as possible with the classic decoder, in order to ease migration to it in areas of critical performance bottlenecks. for this reason, i will first describe all the common functionality of the two decoders, before outlining their differences. ...
...cstatus sec_quickderdecodeitem(prarenapool* arena, void* dest, const sec_asn1template* templateentry, secitem* src); here is a description of the arguments : secitem* src† is a structure containing a pointer to the binary data to be decoded, as well as its size. const sec_asn1template* templateentry is a pointer to one or more decoder templates. ...
...And 5 more matches
PKCS #11 Module Specs
names can be any alpha/numeric combination, and are parsed case-insensitive. ...
...can be any alpha/numeric combination, and are parsed case-insensitive. values can contain any printable ascii value, including utf8 characters. values can contain embedded blanks either through quoting the entire value, or by escaping the embedded blanks with '\'. the value is considered quoted if the first character after the '=' is ', ", {, [, or <. if the value is quoted, then the value is terminated with and ending quote of the form ', ", ), ], }, or > matching the respective starting quote. ending quotes can be escaped. embedded '\' charaters are considered escape characters for the next character in the stream. note that case must be preserved in the values. these modules specs can be passed by the application directly to nss via the secmod_loadusermodule() call. to initialize a pkcs ...
...explicitly logged in. rootflags - comma separated of flags describing any root certs that may be stored (case-insensitive). valid flags are: hasrootcerts - claims that this token has the default root certs and trust values. at init time nss, will try to look for a default root cert device if one has not already been loaded. hasroottrust - parsed but ignored. timeout - time in minutes before the current authentication should be rechecked. this value is only used if askpwd is set to 'timeout'. (default = 0). askpwd - case-insensitive flag describing how password prompts should be manages. only one of the following can be specified. every - prompt whenever the a private key on this token needs to be access (this is on the entire token, not on a key-by-key basis. ...
...And 5 more matches
NSS Tools certutil
ficate. -f password-file specify a file that will automatically supply the password to include in a certificate or to access a certificate database. this is a plain-text file containing one password. be sure to prevent unauthorized access to this file. -g keysize set a key size to use when generating new public and private key pairs. the minimum is 512 bits and the maximum is 8192 bits. the default is 1024 bits. any size that is a multiple of 8 between the minimum and maximum is allowed. -h tokenname specify the name of a token to use or act on. unless specified otherwise the default token is an internal slot (specifically, internal slot 2). this slot can also be explicitly named with the string "interna...
...to reduce the default period. for example, setting a value of -2 would subtract 2 from the default and create a validity period of one month. -w offset-months set an offset from the current system time, in months, for the beginning of a certificate's validity period. use when creating the certificate or adding it to a database. express the offset in integers, using a minus sign (-) to indicate a negative offset. if this argument is not used, the validity period begins at the current system time. the length of the validity period is set with the -v argument. -x use the certificate database tool to generate the signature for a certificate being created or added to a database, rather than obtaining a signature from a separate ca. ...
...blic key for the database, instead of the default value of 65537. the available alternate values are 3 and 17. -z noise-file read a seed value from the specified binary file to use in generating a new rsa private and public key pair. this argument makes it possible to use hardware-generated seed values and unnecessary to manually create a value from the keyboard. the minimum file size is 20 bytes. -1 add a key usage extension to a certificate that is being created or added to a database. this extension allows a certificate's key to be dedicated to supporting specific operations such as ssl server or object signing. the certificate database tool will prompt you to select a particular usage for the certificate's key. these usages are d...
...And 5 more matches
NSS Tools modutil
orary directory. files destined for the temporary directory are guaranteed to be in place before any executable file is run; they are not deleted until all executable files have finished. absolutepath specifies the destination directory of the file as an absolute path. if both relativepath and absolutepath are specified, the installer attempts to use the relative path; if it is unable to determine a relative path, it uses the absolute path. executable specifies that the file is to be executed during the course of the installation. typically this string would be used for a setup program provided by a module vendor, such as a self-extracting setup.exe. more than one file can be specified as executable, in which case the files are run in the order in which they are specified in the scrip...
...if communicator iscurrently running, you should exit communicator before continuing thisoperation. type 'q <enter>' to abort, or <enter> to continue: after you press enter, the tool displays the following: creating "c:\databases\key3.db"...done.creating "c:\databases\cert8.db"...done.creating "c:\dat...
...if communicator iscurrently running, you should exit communicator before continuing thisoperation. type 'q <enter>' to abort, or <enter> to continue: after you press enter, the tool displays the following: using database directory c:\databases...successfully changed defaults. enabling a slot th...
...And 5 more matches
Hacking Tips
this will trigger for *any* asm.js/wasm call, so you should find a way to set this breakpoint for the only generated codes you want to look at. run the program. do next in gdb until you reach the definition of the funcptr: // call the per-exported-function trampoline created by generateentry. ...
...e gecko profiler. this method of profiling has the advantage of mixing the javascript stack with the c++ stack, which is useful to analyze library function issues. one tip is to start looking at a script with an inverted js stack to locate the most expensive js function, then to focus on the frame of this js function, and to remove the inverted stack and look at c++ part of this function to determine from where the cost is coming from. using the jit inspector (browser) install the jit inspector addon in your browser. this addon provides estimated cost of ionmonkey , the baseline compiler, and the interpreter. in addition it provides a clean way to analyze if instructions are inferred as being monomorphic or polymorphic in addition to the number of time each category of type has been observ...
...e simplest way to do this is to run python -m simplehttpserver from within the above directory. the other being disable this check in "about:config", by temporarily switching "security.fileuri.strict_origin_policy" to false note 2: the files can be very big and take a long time to load in the browser. therefore it might be good to reduce the logged file. this will remove entries that took only a minor time (=entries that will only show up with les than 1px). this can be done with the reduce.py script in https://github.com/haytjes/tracelogger/tree/master/tools_v2. you need to download "engine.js", "reduce.py", "reduce.js", "reduce-tree.js" and "reduce-corrections.js". running this tool is a matter of running "python reduce.py js_shell /tmp/tl-data.json tl-reduced". where js_shell is a real s...
...And 5 more matches
nsINavBookmarksService
e gecko 1.9 nsiuri getfolderuri(in print64 folder); obsolete since gecko 1.9 long long getidforitemat(in long long aparentid, in long aindex); prtime getitemdateadded(in long long aitemid); astring getitemguid(in long long aitemid); obsolete since gecko 14.0 long long getitemidforguid(in astring aguid); obsolete since gecko 14.0 long getitemindex(in long long aitemid); prtime getitemlastmodified(in long long aitemid); autf8string getitemtitle(in long long aitemid); unsigned short getitemtype(in long long aitemid); astring getkeywordforbookmark(in long long aitemid); obsolete since gecko 40.0 astring getkeywordforuri(in nsiuri auri); obsolete since gecko 40.0 nsitransaction getre...
...acallback, in nsisupports auserdata); void setfolderreadonly(in long long afolder, in boolean areadonly); void setfoldertitle(in print64 folder, in astring title); obsolete since gecko 1.9 void setitemdateadded(in long long aitemid, in prtime adateadded); void setitemguid(in long long aitemid, in astring aguid); obsolete since gecko 14.0 void setitemindex(in long long aitemid, in long anewindex); void setitemlastmodified(in long long aitemid, in prtime alastmodified); void setitemtitle(in long long aitemid, in autf8string atitle); void setkeywordforbookmark(in long long aitemid, in astring akeyword); obsolete since gecko 40.0 void setkeywordforuri(in nsiuri uri, in astring keyword); obsolete since gecko 1.
...bsolete since gecko 1.9 obsolete since gecko 40.0 attributes attribute type description bookmarksmenufolder long long the item id of the bookmarks menu folder. read only. note: renamed from bookmarksroot in gecko 1.9 placesroot long long the item id of the top-level folder that contains bookmarks, tags and all other places data. this contains administrative data as well as user data, and is therefore not recommended for use in queries. read only. tagsfolder long long the item id of the top-level folder that contains the tag "folders". read only. note: renamed from tagroot in gecko 1.9 toolbarfolder long long the item id of the personal toolbar folder. read only. note: renamed from toolbarroot in gecko 1.9 ...
...And 5 more matches
Monster example - Firefox Developer Tools
this article describes a very simple web page that we'll use to illustrate some features of the memory tool. you can try the site at https://mdn.github.io/performance-scenarios/js-allocs/alloc.html. ...
... this article describes a very simple web page that we'll use to illustrate some features of the memory tool. you can try the site at https://mdn.github.io/performance-scenarios/js-allocs/alloc.html. ...
... this article describes a very simple web page that we'll use to illustrate some features of the memory tool. you can try the site at https://mdn.github.io/performance-scenarios/js-allocs/alloc.html. ...
...And 5 more matches
Drag Operations - Web APIs
itted copy copy only move move only link link only copymove copy or move only copylink copy or link only linkmove link or move only all copy, move, or link uninitialized the default value is all. note that these values must be used exactly as listed above. for example, setting the effectallowed property to copymove allows a copy or move operation but prevents the user from performing a link operation. if you don't change the effectallowed property, then any operation is allowed, just like with the 'all' value. so you don't need to adjust this property unless you want to exclude specific types. during a drag operation, a listener for the dragenter or dragover events can check the effectallowed property to see which operations are permitted. a related property, dropeffect, sh...
...roperty. otherwise, it will be set to an alternate value that is allowed. event.datatransfer.dropeffect = "copy"; in this example, copy is the effect that is performed. you can use the value none to indicate that no drop is allowed at this location, although it is preferred not to cancel the event in this case. within the drop and dragend events, you can check the dropeffect property to determine which effect was ultimately chosen. if the chosen effect were "move", then the original data should be removed from the source of the drag within the dragend event. specifying drop targets a listener for the dragenter and dragover events are used to indicate valid drop targets, that is, places where dragged items may be dropped. most areas of a web page or application are not valid places to ...
...ement in its new location. to do this, you could create an image or separator element and simply insert it into the document during the dragenter event. the dragover event will fire at the element the mouse is pointing at. naturally, you may need to move the insertion marker around a dragover event as well. you can use the event's clientx and clienty properties as with other mouse events to determine the location of the mouse pointer. finally, the dragleave event will fire at an element when the drag leaves the element. this is the time when you should remove any insertion markers or highlighting. you do not need to cancel this event. any highlighting or other visual effects specified using the :-moz-drag-over pseudoclass will be removed automatically. the dragleave event will always fire, ...
...And 5 more matches
Intersection Observer API - Web APIs
}); }; the list of entries received by the callback includes one entry for each target which reporting a change in its intersection status. check the value of the isintersecting property to see if the entry represents an element that currently intersects with the root. be aware that your callback is executed on the main thread. it should operate as quickly as possible; if anything time-consuming needs to be done, use window.requestidlecallback(). also, note that if you specified the root option, the target must be a descendant of the root element. how intersection is calculated all areas considered by the intersection observer api are rectangles; elements which are irregularly shaped are considered as occupying the smallest rectangle which encloses all of the element's parts. similar...
...nt with a container, we need to know what that container is. that container is the intersection root, or root element. this can be either a specific element in the document which is an ancestor of the element to be observed, or null to use the document's viewport as the container. the root intersection rectangle is the rectangle used to check against the target or targets. this rectangle is determined like this: if the intersection root is the implicit root (that is, the top-level document), the root intersection rectangle is the viewport's rectangle. if the intersection root has an overflow clip, the root intersection rectangle is the root element's content area. otherwise, the root intersection rectangle is the intersection root's bounding client rectangle (as returned by calling getb...
...or each observed target which has had the degree to which it intersects the root change such that the amount exposed crosses over one of the thresholds, in either direction. you can see if the target currently intersects the root by looking at the entry's isintersecting property; if its value is true, the target is at least partially intersecting the root element or document. this lets you determine whether the entry represents a transition from the elements intersecting to no longer intersecting or a transition from not intersecting to intersecting. note that it's possible to have a non-zero intersection rectangle, which can happen if the intersection is exactly along the boundary between the two or the area of boundingclientrect is zero. this state of the target and root sharing a bounda...
...And 5 more matches
Key Values - Web APIs
ignal the start of a special control sequence of characters called an "escape sequence." vk_escape (0x1b) kvk_escape (0x35) gdk_key_escape (0xff1b) qt::key_escape (0x01000000) keycode_escape (111) "execute" the execute key. vk_execute (0x2b) qt::key_execute (0x01020003) "find" the find key. opens an interface (typically a dialog box) for performing a find/search operation. appcommand_find gdk_key_find (0xff68) "finish" [5] the finish key. vk_oem_finish (0xf1) "help" the help key. opens or toggles the display of help information. vk_help (0x2f) appcommand_help kvk_help (0x72) gdk_key_help (0xff6a) qt::key_help (0x01000058) keycode_help (259) "pause" the pau...
...he "mediaplay" key value, which is used for media controllers, rather than to control applications and processes. vk_play (0xfa) gdk_key_3270_play (0xfd16) qt::key_play (0x01020005) "props" the props (properties) key. "select" the select key. vk_select (0x29) gdk_key_select (0xff60) keycode_button_select (109) "zoomin" [6] the zoomin key. gdk_key_zoomin (0x1008ff8b) qt::key_zoomin (0x010000f6) keycode_zoom_in (168) "zoomout" [6] the zoomout key. gdk_key_zoomout (0x1008ff8c) qt::key_zoomout (0x010000f7) keycode_zoom_out (169) [1] in google chrome 52, the cancel key incorrectly returns the key code "pause". this is fixed in chrome 53. (see chrome bug 6127...
...and google chrome report the same, unless the japanese keyboard layout is in effect, in which case it generates "kanamode" instead. [5] the finish key gemerates the key code "unidentified" on internet explorer (tested on release 9 and 11). firefox reports the same, unless the japanese keyboard layout is in effect, in which case it generates "katakana" instead. [6] firefox didn't support the "zoomin" and "zoomout" keys until firefox 37. device keys keyboardevent.key value description virtual keycode windows mac linux android "brightnessdown" the brightness down key. typically used to reduce the brightness of the display. gdk_key_monbrightnessdown (0x1008ff03) qt::key_monbrightnessdown (0x010000b3) keycode_brightness_down (2...
...And 5 more matches
Using textures in WebGL - Web APIs
// yes, it's a power of 2. generate mips. gl.generatemipmap(gl.texture_2d); } else { // no, it's not a power of 2. turn off mips and set // wrapping to clamp to edge gl.texparameteri(gl.texture_2d, gl.texture_wrap_s, gl.clamp_to_edge); gl.texparameteri(gl.texture_2d, gl.texture_wrap_t, gl.clamp_to_edge); gl.texparameteri(gl.texture_2d, gl.texture_min_filter, gl.linear); } }; image.src = url; return texture; } function ispowerof2(value) { return (value & (value - 1)) == 0; } the loadtexture() routine starts by creating a webgl texture object texture by calling the webgl createtexture() function. it then uploads a single blue pixel using teximage2d(). this makes the texture immediately usable as a solid blue color even though it...
...ng an image of a few bricks to cover a brick wall. mipmapping and uv repeating can be disabled with texparameteri(). this will allow non-power-of-two (npot) textures at the expense of mipmapping, uv wrapping, uv tiling, and your control over how the device will handle your texture. // gl.nearest is also allowed, instead of gl.linear, as neither mipmap. gl.texparameteri(gl.texture_2d, gl.texture_min_filter, gl.linear); // prevents s-coordinate wrapping (repeating). gl.texparameteri(gl.texture_2d, gl.texture_wrap_s, gl.clamp_to_edge); // prevents t-coordinate wrapping (repeating). gl.texparameteri(gl.texture_2d, gl.texture_wrap_t, gl.clamp_to_edge); again, with these parameters, compatible webgl devices will automatically accept any resolution for that texture (up to their maximum dimensions...
...r); // prevents s-coordinate wrapping (repeating). gl.texparameteri(gl.texture_2d, gl.texture_wrap_s, gl.clamp_to_edge); // prevents t-coordinate wrapping (repeating). gl.texparameteri(gl.texture_2d, gl.texture_wrap_t, gl.clamp_to_edge); again, with these parameters, compatible webgl devices will automatically accept any resolution for that texture (up to their maximum dimensions). without performing the above configuration, webgl requires all samples of npot textures to fail by returning transparent black: rgba(0,0,0,0). to load the image, add a call to our loadtexture() function within our main() function. this can be added after the initbuffers(gl) call. // load texture const texture = loadtexture(gl, 'cubetexture.png'); mapping the texture onto the faces at this point, the texture is...
...And 5 more matches
Window.open() - Web APIs
Web › API › Window › open
name optional a domstring specifying the name of the browsing context (window, <iframe> or tab) into which to load the specified resource; if the name doesn't indicate an existing context, a new window is created and is given the name specified by windowname. this name can be used as the target for the target attribute of <a> or <form> elements. the name should not contain whitespace. keep in mind that this will not be used as the window's title. windowfeatures optional a domstring containing a comma-separated list of window features given with their corresponding values in the form "name=value". these features include options such as the window's default size and position, whether or not to include toolbar, and so forth. there must be no whitespace in the string. see window features be...
...maximized as well. size if only one of them is specified, the behavior is implementation-dependent, and web author should not rely on it. width or innerwidth specifies the width of the content area, viewing area of the new secondary window in pixels. the width value includes the width of the vertical scrollbar if present. the width value does not include the sidebar if it is expanded. the minimum required value is 100. height or innerheight specifies the height of the content area, viewing area of the new secondary window in pixels. the height value includes the height of the horizontal scrollbar if present. the height value does not include other ui parts such as location bar, title bar, tab bar, etc. the minimum required value is 100. if the windowfeatures parameter is non-empty...
...ser window in pixels. this outerwidth value includes the window vertical scrollbar (if present) and left and right window resizing borders. outerheight (only on firefox, obsolete from firefox 80) specifies the height of the whole browser window in pixels. this outerheight value includes any/all present toolbar, window horizontal scrollbar (if present) and top and bottom window resizing borders. minimal required value is 100. toolbar and ui parts features in modern browsers (firefox 76 or newer, google chrome, safari, chromium edge), the following features are just a condition for whether to open popup or not. see popup condition section. the following features control the visibility of each ui parts, all features can be set to yes or 1, or just be present to be on. set them to no or 0...
...And 5 more matches
Accessibility documentation index - Accessibility
pporting live regions as an area for screen readers to innovate and compete. 4 aria test cases aria, accessibility for each example we test the "expected" results with assistive technologies, for each browser that at supports wai-aria in. where a failure occurs we will test the browser for api incorrectness, using tools such as msaa inspect. this must be done in order to determine where to file a bug (browser or at). 5 aria annotations aria, accessibility, wai-aria, annotations, comments, details, suggestions wai-aria version 1.3 sees the addition of a set of new features, collectively known as aria annotations, which allow the creation of accessible annotations inside web documents. typical use cases include edit suggestions (i.e. an addition and/or ...
...a form can be submitted. this attribute can be used with any typical html form element; it is not limited to elements that have an aria role assigned. 26 using the aria-valuemax attribute aria, accessibility the aria-valuemax attribute is used to define the maximum value allowed for a range widget such as a slider, spinbutton or progressbar. ...
...l form element; it is not limited to elements that have an aria role assigned. 26 using the aria-valuemax attribute aria, accessibility the aria-valuemax attribute is used to define the maximum value allowed for a range widget such as a slider, spinbutton or progressbar. 27 using the aria-valuemin attribute aria, accessibility, needscontent the aria-valuemin attribute is used to define the minimum value allowed for a range widget such as a slider, spinbutton or progressbar. if the aria-valuenow has a known maximum and minimum, the author should provide properties for aria-valuemax and aria-valuemin.the value of aria-valuemin must be less than or equal to the value of aria-valuemax. 28 using the aria-valuenow attribute aria, accessibili...
...And 5 more matches
@viewport - CSS: Cascading Style Sheets
Web › CSS › @viewport
authored styles have had an opportunity to adjust the viewport. this is typically based on the size of the window on desktop browsers that aren't in full screen mode. on mobile devices (or desktop devices that are in full screen mode), the initial viewport is usually the portion of a device's screen that is available for application use. this may be either the full screen or the full screen area minus areas controlled by the operating system (such as a taskbar) or the application-available screen area (either the full screen or the screen minus any areas owned by the operating system or other applications). @viewport { width: 100vw; /*sets the width of the actual viewport to the device width*/ } note: the use of <meta name="viewport"> tag overrides @viewport syntax the at-rule conta...
...he screen minus any areas owned by the operating system or other applications). @viewport { width: 100vw; /*sets the width of the actual viewport to the device width*/ } note: the use of <meta name="viewport"> tag overrides @viewport syntax the at-rule contains a set of nested descriptors in a css block that is delimited by curly braces. a zoom factor of 1.0 or 100% corresponds to no zooming. larger values zoom in. smaller values zoom out. descriptors browser support for @viewport is weak at this time, with support being largely available in internet explorer and edge. even in those browsers, only a small number of descriptors are available. browsers will ignore @viewport if they don't support it, and will ignore any descriptors that they don't recognize. ...
...rresponds to no zooming. larger values zoom in. smaller values zoom out. descriptors browser support for @viewport is weak at this time, with support being largely available in internet explorer and edge. even in those browsers, only a small number of descriptors are available. browsers will ignore @viewport if they don't support it, and will ignore any descriptors that they don't recognize. min-width used in the determination of the width of the viewport when the document is first displayed. max-width used in the determination of the width of the viewport when the document is first displayed. width a shorthand descriptor for setting both min-width and max-width. min-height used in the determination of the height of the viewport when the document is first displayed. max-height u...
...And 5 more matches
transition-delay - CSS: Cascading Style Sheets
ss="box">lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position:absolute; -webkit-transition-property: width height background-color font-size left top color; -webkit-transition-duration:2s; -webkit-transition-delay:0.5s; -webkit-transition-timing-function: linear; transition-property: width height background-color font-size left top color; transition-duration:2s; transition-delay:0.5s; transition-timing-function: linear; } .box1{ width: 50px; height: 50px; background-color: blue; color: yellow; font-size: 18px; left: 150px; top:25px; position:absolute; -webkit-transition-property: widt...
...y:0.5s; transition-timing-function: linear; } .box1{ width: 50px; height: 50px; background-color: blue; color: yellow; font-size: 18px; left: 150px; top:25px; position:absolute; -webkit-transition-property: width height background-color font-size left top color; -webkit-transition-duration:2s; -webkit-transition-delay:0.5s; -webkit-transition-timing-function: linear; transition-property: width height background-color font-size left top color; transition-duration:2s; transition-delay:0.5s; transition-timing-function: linear; } function updatetransition() { var el = document.queryselector("div.box"); if (el) { el.classname = "box1"; } else { el = document.queryselector("div.box1"); el.classname = "box"; ...
...ass="box">lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position:absolute; -webkit-transition-property: width height background-color font-size left top color; -webkit-transition-duration:2s; -webkit-transition-delay:1s; -webkit-transition-timing-function: linear; transition-property: width height background-color font-size left top color; transition-duration:2s; transition-delay:1s; transition-timing-function: linear; } .box1{ width: 50px; height: 50px; background-color: blue; color: yellow; font-size: 18px; left: 150px; top:25px; position:absolute; -webkit-transition-property: width h...
...And 5 more matches
transition-duration - CSS: Cascading Style Sheets
v class="box">lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position:absolute; -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color; -webkit-transition-duration:0.5s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration:0.5s; transition-timing-function: ease-in-out; } .box1{ transform: rotate(270deg); -webkit-transform: rotate(270deg); width: 50px; height: 50px; background-color: blue; color: yellow; font-size: 18px; left:...
...nsform: rotate(270deg); -webkit-transform: rotate(270deg); width: 50px; height: 50px; background-color: blue; color: yellow; font-size: 18px; left: 150px; top:25px; position:absolute; -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color; -webkit-transition-duration:0.5s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transformv color; transition-duration:0.5s; transition-timing-function: ease-in-out; } function updatetransition() { var el = document.queryselector("div.box"); if (el) { el.classname = "box1"; } else { el = document.queryselector("div.box1"); el.classna...
...rent"> <div class="box">lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position:absolute; -webkit-transition-property: width height background-color font-size left top -webkit-transform color; -webkit-transition-duration:1s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform color; transition-duration:1s; transition-timing-function: ease-in-out; } .box1{ transform: rotate(270deg); -webkit-transform: rotate(270deg); width: 50px; height: 50px; background-color: blue; color: yellow; font-size: 18px; left: 150px; top:25px...
...And 5 more matches
transition - CSS: Cascading Style Sheets
the transition css property is a shorthand property for transition-property, transition-duration, transition-timing-function, and transition-delay. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. transitions enable you to define the transition between two states of an element. different states may be defined using pseudo-classes like :hover or :active or dynamically set using javascript. ...
...ve-examples and send us a pull request. transitions enable you to define the transition between two states of an element. different states may be defined using pseudo-classes like :hover or :active or dynamically set using javascript. ...
...et using javascript. ...
...And 5 more matches
Index - Developer guides
Web › Guide › Index
full styling of the player will be taken care of in a future article. 9 cross-browser audio basics apps, audio, guide, html5, media, events 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 10 live streaming web audio and video guide, adaptive streaming live streaming technology is often employed to relay live events such as sports, concerts and more generally tv and radio programmes that are output live. often shortened to just streaming, live streaming is the process of transmitting media 'live' to computers and devices. this is a fairly complex and nascent subject with a lot of variable...
...apps, buffer, html5, timeranges, video, buffering, seeking sometimes it's useful to know how much <audio> or <video> has downloaded or is playable without delay — a good example of this is the buffered progress bar of an audio or video player. this article discusses how to build a buffer/seek bar using timeranges, and other features of the media api. ...
...g sometimes it's useful to know how much <audio> or <video> has downloaded or is playable without delay — a good example of this is the buffered progress bar of an audio or video player. this article discusses how to build a buffer/seek bar using timeranges, and other features of the media api. ...
...And 5 more matches
<input type="email"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › email
ed as appropriate to visually denote whether the current value of the field is a valid e-mail address or not. on browsers that don't support inputs of type email, a email input falls back to being a standard text input. value a domstring representing an e-mail address, or empty events change and input supported common attributes autocomplete, list, maxlength, minlength, multiple, name,pattern, placeholder, readonly, required, size, and type idl attributes list and value methods select() value the <input> element's value attribute contains a domstring which is automatically validated as conforming to e-mail syntax. more specifically, there are three possible value formats that will pass validation: an empty string ("") in...
...additional attributes in addition to the attributes that operate on all <input> elements regardless of their type, email inputs support the following attributes: attribute description list the id of the <datalist> element that contains the optional pre-defined autocomplete options maxlength the maximum number of characters the input should accept minlength the minimum number of characters long the input can be and still be considered valid multiple whether or not to allow multiple, comma-separated, e-mail addresses to be entered pattern a regular expression the input's contents must match in order to be valid placeholder an exemplar value to display in the input field whenever it is empty readon...
...irements: users can select from this predefined list or provide a different value. maxlength the maximum number of characters (as utf-16 code units) the user can enter into the email input. this must be an integer value 0 or higher. if no maxlength is specified, or an invalid value is specified, the email input has no maximum length. this value must also be greater than or equal to the value of minlength. the input will fail constraint validation if the length of the text value of the field is greater than maxlength utf-16 code units long. constraint validation is only applied when the value is changed by the user. minlength the minimum number of characters (as utf-16 code units) the user can enter into the email input. this must be an non-negative integer value smaller than or equal to ...
...And 5 more matches
<input type="search"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › search
his interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. value a domstring representing the value contained in the search field. events change and input supported common attributes autocomplete, list, maxlength, minlength, pattern, placeholder, required, size. idl attributes value methods select(), setrangetext(), setselectionrange(). value the value attribute contains a domstring representing the value contained in the search field. you can retrieve this using the htmlinputelement.value property in javascript. searchterms = mysearch.value; if no validation constraints are ...
...nal attributes in addition to the attributes that operate on all <input> elements regardless of their type, search field inputs support the following attributes: attribute description list the id of the <datalist> element that contains the optional pre-defined autocomplete options maxlength the maximum number of characters the input should accept minlength the minimum number of characters long the input can be and still be considered valid pattern a regular expression the input's contents must match in order to be valid placeholder an exemplar value to display in the input field whenever it is empty readonly a boolean attribute indicating whether or not the contents of the input should be read-only ...
...ements: users can select from this predefined list or provide a different value. maxlength the maximum number of characters (as utf-16 code units) the user can enter into the search field. this must be an integer value 0 or higher. if no maxlength is specified, or an invalid value is specified, the search field has no maximum length. ...
...And 5 more matches
<input type="text"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › text
r this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. value a domstring representing the text contained in the text field. events change and input supported common attributes autocomplete, list, maxlength, minlength, pattern, placeholder, readonly, required and size idl attributes list, value methods select(), setrangetext() and setselectionrange(). value the value attribute is a domstring that contains the current value of the text entered into the text field. you can retrieve this using the value property in javascript. let thetext = mytextinput.value; if no validat...
... additional attributes in addition to the attributes that operate on all <input> elements regardless of their type, text inputs support the following attributes: attribute description list the id of the <datalist> element that contains the optional pre-defined autocomplete options maxlength the maximum number of characters the input should accept minlength the minimum number of characters long the input can be and still be considered valid pattern a regular expression the input's contents must match in order to be valid placeholder an exemplar value to display in the input field whenever it is empty readonly a boolean attribute indicating whether or not the contents of the input should be read-only ...
...quirements: users can select from this predefined list or provide a different value. maxlength the maximum number of characters (as utf-16 code units) the user can enter into the text input. this must be an integer value 0 or higher. if no maxlength is specified, or an invalid value is specified, the text input has no maximum length. this value must also be greater than or equal to the value of minlength. the input will fail constraint validation if the length of the text value of the field is greater than maxlength utf-16 code units long. constraint validation is only applied when the value is changed by the user. minlength the minimum number of characters (as utf-16 code units) the user can enter into the text input. this must be an non-negative integer value smaller than or equal to t...
...And 5 more matches
<input type="url"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › url
ses are automatically applied as appropriate to visually denote whether the current value of the field is a valid url or not. on browsers that don't support inputs of type url, a url input falls back to being a standard text input. value a domstring representing a url, or empty events change and input supported common attributes autocomplete, list, maxlength, minlength, pattern, placeholder, readonly, required and size idl attributes list, value, selectionend, selectiondirection methods select(), setrangetext() and setselectionrange(). value the <input> element's value attribute contains a domstring which is automatically validated as conforming to url syntax. more specifically, there are two possible value formats that wil...
... additional attributes in addition to the attributes that operate on all <input> elements regardless of their type, url inputs support the following attributes: attribute description list the id of the <datalist> element that contains the optional pre-defined autocomplete options maxlength the maximum number of characters the input should accept minlength the minimum number of characters long the input can be and still be considered valid pattern a regular expression the input's contents must match in order to be valid placeholder an exemplar value to display in the input field whenever it is empty readonly a boolean attribute indicating whether or not the contents of the input should be read-only ...
...requirements: users can select from this predefined list or provide a different value. maxlength the maximum number of characters (as utf-16 code units) the user can enter into the url input. this must be an integer value 0 or higher. if no maxlength is specified, or an invalid value is specified, the url input has no maximum length. this value must also be greater than or equal to the value of minlength. the input will fail constraint validation if the length of the text value of the field is greater than maxlength utf-16 code units long. constraint validation is only applied when the value is changed by the user. minlength the minimum number of characters (as utf-16 code units) the user can enter into the url input. this must be an non-negative integer value smaller than or equal to th...
...And 5 more matches
<meter>: The HTML Meter element - HTML: Hypertext Markup Language
Web › HTML › Element › meter
none, both the starting and ending tag are mandatory. permitted parents any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles no role permitted dom interface htmlmeterelement attributes this element includes the global attributes. value the current numeric value. ...
...ending tag are mandatory. permitted parents any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles no role permitted dom interface htmlmeterelement attributes this element includes the global attributes. value the current numeric value. ...
... permitted aria roles no role permitted dom interface htmlmeterelement attributes this element includes the global attributes. value the current numeric value. this must be between the minimum and maximum values (min attribute and max attribute) if they are specified. if unspecified or malformed, the value is 0. if specified, but not within the range given by the min attribute and max attribute, the value is equal to the nearest end of the range. ...
...And 5 more matches
Cross-Origin Resource Sharing (CORS) - HTTP
Web › HTTP › CORS
from unless the response from other origins includes the right cors headers. the cors mechanism supports secure cross-origin requests and data transfers between browsers and servers. modern browsers use cors in apis such as xmlhttprequest or fetch to mitigate the risks of cross-origin http requests. who should read this article? everyone, really. more specifically, this article is for web administrators, server developers, and front-end developers. modern browsers handle the client side of cross-origin sharing, including headers and policy enforcement. but the cors standard means servers have to handle new request and response headers. another article for server developers discussing cross-origin sharing from a server perspective (with php code snippets) is supplementary reading. what ...
...s request method, and then, upon "approval" from the server, sending the actual request. servers can also inform clients whether "credentials" (such as cookies and http authentication) should be sent with requests. cors failures result in errors, but for security reasons, specifics about the error are not available to javascript. all the code knows is that an error occurred. the only way to determine what specifically went wrong is to look at the browser's console for details. subsequent sections discuss scenarios, as well as provide a breakdown of the http headers used. examples of access control scenarios we present three scenarios that demonstrate how cross-origin resource sharing works. all these examples use xmlhttprequest, which can make cross-site requests in any supporting browser...
... http/1.1 200 ok date: mon, 01 dec 2008 00:23:53 gmt server: apache/2 access-control-allow-origin: * keep-alive: timeout=2, max=100 connection: keep-alive transfer-encoding: chunked content-type: application/xml […xml data…] in response, the server sends back an access-control-allow-origin header. the use of the origin header and of access-control-allow-origin sho...
...And 5 more matches
JavaScript data types and data structures - JavaScript
this article attempts to list the built-in data structures available in javascript and what properties they have. these can be used to build other data structures. wherever possible, comparisons with other languages are drawn. dynamic typing javascript is a loosely typed and dynamic language. ...
...ect instance also used as data structures: new object, new array, new map, new set, new weakmap, new set, new date and almost everything made with new keyword; function : a non-data structure, though it also answers for typeof operator: typeof instance === "function". this is merely a special shorthand for functions, though every function constructor is derived from object constructor. keep in mind the only valuable purpose of typeof operator usage is checking the data type. if we wish to check any structural type derived from object it is pointless to use typeof for that, as we will always receive "object". the indeed proper way to check what sort of object we are using is instanceof keyword. but even in that case there might be misconceptions. primitive values all types except objects ...
...umber type is a double-precision 64-bit binary format ieee 754 value (numbers between -(253 − 1) and 253 − 1). in addition to representing floating-point numbers, the number type has three symbolic values: +infinity, -infinity, and nan ("not a number"). to check for the largest available value or smallest available value within ±infinity, you can use the constants number.max_value or number.min_value. 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. beyond this range, integers in javascript are not safe anymore and will be a double-precision floating point approximation of the value. the number type has only one int...
...And 5 more matches
Loops and iteration - JavaScript
sed this way as a loop: for (let step = 0; step < 5; step++) { // runs 5 times, with values of step 0 through 4. console.log('walking east one step'); } there are many different kinds of loops, but they all essentially do the same thing: they repeat an action some number of times. (note that it's possible that number could be zero!) the various loop mechanisms offer different ways to determine the start and end points of the loop. there are various situations that are more easily served by one type of loop over the others. the statements for loops provided in javascript are: for statement do...while statement while statement labeled statement break statement continue statement for...in statement for...of statement for statement a for loop repeats until a specified condit...
... expression initialexpression, if any, is executed. this expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity. this expression can also declare variables. the conditionexpression expression is evaluated. if the value of conditionexpression is true, the loop statements execute. if the value of condition is false, the for loop terminates. (if the condition expression is omitted entirely, the condition is assumed to be true.) the statement executes. to execute multiple statements, use a block statement ({ ... }) to group those statements. if present, the update expression incrementexpression is executed. control returns to step 2. example in the example below, the function contains a for statement that counts the number ...
...less than 3: let n = 0; let x = 0; while (n < 3) { n++; x += n; } with each iteration, the loop increments n and adds that value to x. ...
...And 5 more matches
Array.prototype.indexOf() - JavaScript
the indexof() method returns the first index at which a given element can be found in the array, or -1 if it is not present. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax arr.indexof(searchelement[, fromindex]) parameters searchelement element to locate in the array. fromindex optional the index to start the search at. if the index is greater than or equal to the array's length, -1 is returned, which means the array will not be searched. if the provided index value is a negative number, it is taken as the offset from the end of the array. note: if the provided index is negative, the array is still ...
...hod, see string.prototype.indexof(). polyfill indexof() was added to the ecma-262 standard in the 5th edition; as such it may not be present in all browsers. you can work around this by utilizing the following code at the beginning of your scripts. this will allow you to use indexof() when there is still no native support. ...
...262, 5th edition, assuming typeerror and math.abs() have their original values. // this version tries to optimize by only checking for "in" when looking for undefined and // skipping the definitely fruitless nan search. other parts are merely cosmetic conciseness. // whether it is actually faster remains to be seen. ...
...And 5 more matches
Date - JavaScript
re about it on the igalia blog and fill out the survey. it needs real-world feedback from web developers, but is not yet ready for production use! description the ecmascript epoch and timestamps a javascript date is fundamentally specified as the number of milliseconds that have elapsed since midnight on january 1, 1970, utc. this date and time is the same as the unix epoch, which is the predominant base value for computer-recorded date and time values. note: it's important to keep in mind that while the time value at the heart of a date object is utc, the basic methods to fetch the date and time or its components all work in the local (i.e. host system) time zone and offset. it should be noted that the maximum date is not of the same value as the maximum safe integer (number.max_safe_i...
...pecified date according to local time. date.prototype.getfullyear() returns the year (4 digits for 4-digit years) of the specified date according to local time. date.prototype.gethours() returns the hour (0–23) in the specified date according to local time. date.prototype.getmilliseconds() returns the milliseconds (0–999) in the specified date according to local time. date.prototype.getminutes() returns the minutes (0–59) in the specified date according to local time. date.prototype.getmonth() returns the month (0–11) in the specified date according to local time. date.prototype.getseconds() returns the seconds (0–59) in the specified date according to local time. date.prototype.gettime() returns the numeric value of the specified date as the number of milliseconds sin...
...fied date according to local time. date.prototype.getseconds() returns the seconds (0–59) in the specified date according to local time. date.prototype.gettime() returns the numeric value of the specified date as the number of milliseconds since january 1, 1970, 00:00:00 utc. (negative values are returned for prior times.) date.prototype.gettimezoneoffset() returns the time-zone offset in minutes for the current locale. date.prototype.getutcdate() returns the day (date) of the month (1–31) in the specified date according to universal time. date.prototype.getutcday() returns the day of the week (0–6) in the specified date according to universal time. date.prototype.getutcfullyear() returns the year (4 digits for 4-digit years) in the specified date according to universal time...
...And 5 more matches
Function.prototype.apply() - JavaScript
urely not? apply to the rescue! 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. ...
...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. as an example, here are math.max/math.min, used to find out the maximum/minimum value in an array. ...
... 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. as an example, here are math.max/math.min, used to find out the maximum/minimum value in an array. ...
...And 5 more matches
Intl.NumberFormat() constructor - JavaScript
you can enable this formatting by setting the currencysign option to "accounting". the default value is "standard". localematcher the locale matching algorithm to use. possible values are "lookup" and "best fit"; the default is "best fit". for information about this option, see the intl page. notation the formatting that should be displayed for the number, the defaults is "standar...
...display the unit formatting style to use in unit formatting, the defaults is "short". "long" (e.g., 16 litres) "short" (e.g., 16 l) "narrow" (e.g., 16l) usegrouping whether to use grouping separators, such as thousands separators or thousand/lakh/crore separators. possible values are true and false; the default is true. ...
...y the unit formatting style to use in unit formatting, the defaults is "short". "long" (e.g., 16 litres) "short" (e.g., 16 l) "narrow" (e.g., 16l) usegrouping whether to use grouping separators, such as thousands separators or thousand/lakh/crore separators. possible values are true and false; the default is true. ...
...And 5 more matches
Math.random() - JavaScript
e chosen (253 or higher), it's possible in extremely rare cases to calculate the usually-excluded upper bound. getting a random number between 0 (inclusive) and 1 (exclusive) function getrandom() { return math.random(); } getting a random number between two values this example returns a random number between the specified values. ...
...late the usually-excluded upper bound. getting a random number between 0 (inclusive) and 1 (exclusive) function getrandom() { return math.random(); } getting a random number between two values this example returns a random number between the specified values. the returned value is no lower than (and may possibly equal) min, and is less than (and not equal) max. ...
...ing a random number between 0 (inclusive) and 1 (exclusive) function getrandom() { return math.random(); } getting a random number between two values this example returns a random number between the specified values. the returned value is no lower than (and may possibly equal) min, and is less than (and not equal) max. ...
...And 5 more matches
Math.random() - JavaScript
e chosen (253 or higher), it's possible in extremely rare cases to calculate the usually-excluded upper bound. getting a random number between 0 (inclusive) and 1 (exclusive) function getrandom() { return math.random(); } getting a random number between two values this example returns a random number between the specified values. ...
...late the usually-excluded upper bound. getting a random number between 0 (inclusive) and 1 (exclusive) function getrandom() { return math.random(); } getting a random number between two values this example returns a random number between the specified values. the returned value is no lower than (and may possibly equal) min, and is less than (and not equal) max. ...
...ing a random number between 0 (inclusive) and 1 (exclusive) function getrandom() { return math.random(); } getting a random number between two values this example returns a random number between the specified values. the returned value is no lower than (and may possibly equal) min, and is less than (and not equal) max. ...
...And 5 more matches
Promise - JavaScript
nts: f = () => expression to create the lazily-evaluated expression, and f() to evaluate. note: a promise is said to be settled if it is either fulfilled or rejected, but not pending. you will also hear the term resolved used with promises — this means that the promise is settled or “locked in” to match the state of another promise. states and fates contains more details about promise terminology. chained promises the methods promise.then(), promise.catch(), and promise.finally() are used to associate further action with a promise that becomes settled. these methods also return a newly generated promise object, which can optionally be used for chaining; for example, like this: const mypromise = (new promise(myexecutorfunc)) .then(handlefulfilleda,handlerejecteda) .then(...
... must be handled immediately. (see throw -999 in the example, below, for a technique to handle the consequences.) on the other hand, in the absence of an immediate need, it is simpler to leave out error handling until a final .catch() statement. the signatures of these two functions are simple, they accept a single parameter of any type. these functions are written by you, the programmer. the termination condition of these functions determines the "settled" state of the next promise in the chain. any termination other than a throw creates a "resolved" state, while terminating with a throw creates a "rejected" state. handlefulfilled(value) { /*...*/; return nextvalue; } handlerejection(reason) { /*...*/; throw nextreason; } handlerejection(reason) { /*...*/; return nextvalue; } t...
... in the resolve(...) function above. // it doesn't have to be a string, but if it is only a succeed message, it probably will be. console.log("yay! " + successmessage) }); example with diverse situations this example shows diverse techniques for using promise capabilities, and diverse situations that can occur. to understand this, start by scrolling to the bottom of the code block, and examine the promise chain. upon provision of an initial promise, a chain of promises can follow. the chain is composed of .then() calls, and typically (but not necessarily) has a single .catch() at the end, optionally followed by .finally(). in this example, the promise chain is initiated by a custom written new promise() construct; but in actual practice, promise chains more typically start with an api...
...And 5 more matches
Codecs used by WebRTC - Web media technologies
presented at the same time as the audio that corresponds. general codec requirements before looking at codec-specific capabilities and requirements, there are a few overall requirements that must be met by any codec configuration used with webrtc. unless the sdp specifically signals otherwise, the web browser receiving a webrtc video stream must be able to handle video at at least 20 fps at a minimum resolution of 320 pixels wide by 240 pixels tall. it's encouraged that video be encoded at a frame rate and size no lower than that, since that's essentially the lower bound of what webrtc generally is expected to handle. sdp supports a codec-independent way to specify preferred video resolutions (rfc 6236. this is done by sending an a=imageattr sdp attribute to indicate the maximum resoluti...
...s when using webrtc) is described in rfc 7741: rtp payload format for vp8 video. avc / h.264 support for avc's constrained baseline (cb) profile is required in all fully-compliant webrtc implementations. cb is a subset of the main profile, and is specifically designed for low-complexity, low-delay applications such as mobile video and videoconferencing, as well as for platforms with lower performing video processing capabilities. our overview of avc and its features can be found in the main video codec guide. special parameter support requirements avc offers a wide array of parameters for controlling optional values. in order to improve reliability of webrtc media sharing across multiple platforms and browsers, it's required that webrtc endpoints that support avc handle certain parameter...
...ow for more details about any webrtc-specific considerations that exist for each codec listed above. it's useful to note that rfc 7874 defines more than a list of audio codecs that a webrtc-compliant browser must support; it also provides recommendations and requirements for special audio features such as echo cancelation, noise reduction, and audio leveling. note: the list above indicates the minimum required set of codecs that all webrtc-compatible endpoints are required to implement. a given browser may also support other codecs; however, cross-platform and cross-device compatibility may be at risk if you use other codecs without carefully ensuring that support exists in all browsers your users might choose. in addition to the mandatory audio codecs, some browsers support additional c...
...And 5 more matches
Enhanced Extension Installation - Archive of obsolete content
that it destroys the component registries, finishes pending transactions and regenerates metadata appropriately. datasource structure the extension manager implements a rdf datasource which contains a composite of the two xml/rdf datasources at the two install locations. the composite datasource handles all read-only information requests, and when data must be written the extension manager determines the appropriate datasource to write and flush to. the model looks something like this: nsextensionsdatasource.prototype = { _composite // the composite that manages the two // datasources at the install locations for // read-only information requests _profileextensions // the rdf/xml datasource for the items ...
...ns and themes. this is a by-product of the fact that there are physical per-type containers in the datasource. sections of ui that display installed items are rooted on these containers. tracking item type item type is tracked for the most part by containment in one or other of the two containers. in situations where an item is not yet a member of one of the containers, type is inelegantly determined by checking for presence of a theme-only property on the item's install manifest rdf file. installation initiation when an item is installed from the web, xpinstall is invoked and it calls into the extension system when it discovers that the xpi file contains an install.rdf manifest. the extension manager extracts that file and checks to see if the item is compatible with the running version...
...nstall function may take several steps. if the item is found incompatible, a version update check is performed as before. if updated compatibility information is found this is written into the in-memory representation of the the temporary install manifest and the install function is called recursively, supplying this updated install manifest as the source for _getinstalldata. ...
...And 4 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. as a rough overview this is a version string split by periods, some examples: 2.0 1.0b1 3.0pre1 5.0.1.2 note: before firefox 1.5 the more basic firefox version format was used: major.minor.release.build[+] where only digits were allowed. the toolkit version format supports the firefox version format but allows greater flexibility. how applications determine compatibility when installing add-ons applications look at the targetapplication entries in the add-on's install.rdf. an entry must exist with an id matching the id of the application. additionally the minversion and maxversion of this entry must be a range that includes the version of the running application. if the application ha...
...sion then the application will retrieve updated compatibility information from the add-on's updateurl. if the install.rdf contains any targetplatform entries then the platform of the currently running application must be listed or the installation will be rejected. firefox 3 note in applications based on gecko 1.9 you can also use a targetapplication entry with an id toolkit@mozilla.org and minversion and maxversion that match the toolkit version of the running application. this allows you to say that your add-on will install into any toolkit based application. overriding compatibility checking for testing purposes you can tell the application to somewhat ignore compatibility checks when installing add-ons. simply create the boolean preference extensions.checkcompatibility and set ...
...purposes you can tell the application to somewhat ignore compatibility checks when installing add-ons. simply create the boolean preference extensions.checkcompatibility and set it to false. note: before firefox 1.5 the preference app.extensions.version could be used to override the version that the application believed itself to be to allow normally incompatible extensions to install. choosing minversion and maxversion minversion and maxversion should specify the range of versions of the application you have tested with. in particular you should never specify a maxversion that is larger than the currently available version of the application since you do not know what api and ui changes are just around the corner. with compatibility updating it is not necessary to release a whole new vers...
...And 4 more matches
Appendix: What you should know about open-source software licenses - Archive of obsolete content
this covers three rights and six conditions. what is important to us now is the following three rights: open source rights: a user can create and distribute copies of the source code; a user can obtain a program’s source code; a user can modify the source code. any oss license will include these rights. the user is free to use (duplicate, distribu...
...ser is free to use (duplicate, distribute, and modify) the source code, following certain conditions. this means that the author is granting users the use of the work in the strong, authorial sense, and when i write “use” in the rest of this document it is generally in that sense. ...
...ions. this means that the author is granting users the use of the work in the strong, authorial sense, and when i write “use” in the rest of this document it is generally in that sense. ...
...And 4 more matches
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
ar, showing that it ran correctly. benefits of testing implementing the tests described here confirms that the methods work correctly, and builds confidence in your implementations. ...
...ed the same way, but what will you do if an invalid string is passed? what if you attempt to run with nothing in the stack—what result will you return then? try to keep in mind real-world circumstances while you’re working on this. ...
...othing in the stack—what result will you return then? ...
...And 4 more matches
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
label="button1" ordinal="3"/> <button label="button2" ordinal="2"/> <button label="button3" ordinal="1"/> </vbox> listing 5: changing order with ordinal figure 4: output of listing 5 box size you can set the size of xul elements explicitly using the width and height attributes, as shown in listing 6. ...
.../> <button label="button2" ordinal="2"/> <button label="button3" ordinal="1"/> </vbox> listing 5: changing order with ordinal figure 4: output of listing 5 box size you can set the size of xul elements explicitly using the width and height attributes, as shown in listing 6. ...
...on label="button2" ordinal="2"/> <button label="button3" ordinal="1"/> </vbox> listing 5: changing order with ordinal figure 4: output of listing 5 box size you can set the size of xul elements explicitly using the width and height attributes, as shown in listing 6. if you are creating elements that can grow using the flex attribute, you can also set minimums and maximums using minwidth, minheight, maxwidth, and maxheight. ...
...And 4 more matches
CSS3 - Archive of obsolete content
ing the notion of css qualified name, using the ' | ' syntax and adding the @namespace css at-rule. selectors level 3 recommendation since september 29th, 2011 adds: substring matching attribute selectors, e[attribute^="value"], e[attribute$="value"], e[attribute*="value"] . new pseudo-classes: :target, :enabled and :disabled, :checked, :indeterminate, :root, :nth-child and :nth-last-child, :nth-of-type and :nth-last-of-type, :last-child, :first-of-type and :last-of-type, :only-child and :only-of-type,:empty, and :not. pseudo-elements are now characterized by two colons rather than one: :after becomes ::after, :before becomes ::before, :first-letter becomes ::first-letter, and :first-line becomes ::first-line. the new general sibl...
...user interface module level 3 recommendation since june 21st, 2018 adds: the ability to tweak the box model using the css box-sizing property. at risk: due to insufficient browser support, standardization of the padding-box value may be postponed to the next iteration of this module. allow the styling of forms according their content using the css :indeterminate, :default, :valid, :invalid, :in-range, :out-of-range, :required, :optional, :read-only, and :read-write pseudo-classes and the ::value, ::choices, ::repeat-item, and ::repeat-index pseudo-elements. at risk: due to insufficient browser support, standardization of the pseudo-elements ::value, ::choices, ::repeat-item, and ::repeat-index may be postponed to the next iteration of this modu...
...evel 3 candidate recommendation makes initial and inherit keywords usable on any css property. formally defines the css data types of css 2.1, that were implicitely defined by their grammar token and some textual precisions. adds: definition for new font-relative length units: rem and ch . definition for viewport-relative length units: vw, vh, vmax, and vmin . precision about the real size of the absolute length units, which are not really absolute, but defined in relation with the reference pixel . definition for <angle>, <time>, <frequency>, <resolution>. normative value to the definition of <color>, <image>, and <position>. definition for the calc(), attr(), and toggle() functional notations. at risk: due to insufficient ...
...And 4 more matches
compareTo - Archive of obsolete content
rev revision number. bld build number. ...
... rev revision number. bld build number. ...
... rev revision number. bld build number. ...
...And 4 more matches
textbox - Archive of obsolete content
| methods | related ] an input field where the user can enter text. it is similar to the html input element. only one line of text is displayed by default. the multiline attribute can be specified to display a field with multiple rows. more information is available in the xul tutorial. ...
...espinbuttons, increment, label, max, maxlength, min, multiline, newlines, onblur, onchange, onfocus, oninput, placeholder, preference, readonly, rows, searchbutton, size, spellcheck, tabindex, timeout, type, value, wrap, wraparound properties accessibletype, clickselectsall, decimalplaces, decimalsymbol, defaultvalue, disabled, editor, emptytext, increment, inputfield, label, max, maxlength, min, placeholder, readonly, searchbutton, selectionend, selectionstart, size, spinbuttons, tabindex, textlength, timeout, type, value, valuenumber, wraparound methods decrease, increase, reset, select, setselectionrange style classes plain examples <vbox> <label control="your-name" value="enter your name:"/> <textbox id="your-name" value="john"/> </vbox> attributes cols ty...
... label type: string if present and not empty, this will be exposed to screen readers through the label property. type: integer the maximum value that the scale or number box may be set to. the default value is 100 for scales and infinity for number boxes. maxlength type: integer the maximum number of characters that the textbox allows to be entered. min type: integer the minimum value the textbox's value may take. the default value is 0. multiline type: boolean if true, the textbox displays multiple lines. if the user presses enter, a new line is started. if false, the textbox only allows entry of one line. newlines type: one of the values below how the text box handles pastes with newlines in them. possible value...
...And 4 more matches
Gecko Compatibility Handbook - Archive of obsolete content
site in aol for macos and compuserve 7 to check for browser detection and network issues. testing aol from within a firewall if you need to connect to aol via a corporate firewall, america online has registered tcp/ip ports 5190 and 11523 so you can communicate with the aol client software. this way you can test your site on the aol client from behind your firewall, provided that your network administrators will open these ports. you need to be connected to the internet to test your site on aol; it isn't possible to access your site on a local machine via your lan, without an internet connection. see webmaster@aol for further information. solution quick reference as discussed in mozilla's using web standards in your web pages, coding for cross-browser compatibility requires you write sta...
...rectly specified the mime type for the content. internet explorer tries to guess the mime type of documents while gecko browsers relies upon the web server to specify the correct mime type. gecko does not try to 'sniff' the mime type for a document in order to reduce the possibility of unsecure, dangerous content masquerading as as a safe mime type. use perl's head utitility to determine the actual mime type being used by the web server. correct any incorrect server mime types. (related article) stylesheet is not being recognized the presence of the title attribute in a link element that references an external stylesheet can cause the stylesheet may be causing the external stylesheet to be ignored. make sure that any stylesheet which should alw...
...se the stylesheet may be causing the external stylesheet to be ignored. make sure that any stylesheet which should always be applied is persistent instead of preferred. (related article) connecting to a secure site fails, but connects in internet explorer the web server does not properly implement the fall back negotiation for ssl. the web server administrator needs to upgrade the ssl software. in order to use a site with a defective implementation of ssl, visitors need to disable tls in their netscape 6/7 or mozilla browser until the site has upgraded to software that correctly implements ssl. dhtml menus implemented using hiermenu have problems the hiermenu version is obsolete. the earliest version of hiermenu only suppor...
...And 4 more matches
The First Install Problem - Archive of obsolete content
omenclature that gives us the desired uniqueness. this uri nomenclature is called a plugin identifier (plid) and is described on a separate page. the following write-up describes how a plugin installer can write keys to the win32 system registry to enable gecko-based browsers to discover the plugin at runtime. write a key under hkey_local_machine\software\mozillaplugins\ which is a vendor-determined plid. if the hkey_local_machine\software\mozillaplugins key doesn't exist, create it, and write the vendor-determined plid for each module that the vendor wishes to install. example: a piece of software called myapplication might create hkey_local_machine\software\mozillaplugins\@mycompany.com/myapplication,version=5.0.1/ where the plid is something the corporation that makes myapplication (myc...
...note that myapplication consists of one dll (which is an npapi plugin handling a given mimetype -- say application/x-myapp) and one xpt file, for scriptable interfaces. ...
... consists of one dll (which is an npapi plugin handling a given mimetype -- say application/x-myapp) and one xpt file, for scriptable interfaces. caveat emptor: if the key cannot be created under hkey_local_machine, create it as hkey_current_user\software\mozillaplugins\ under hkey_current_user. on windows xp and windows 2000, in order to write to the registry, sometimes the software may need administrator privileges. thus, some installers may need to write to the hkey_current_user key; this doesn't require administrator privileges. traditionally, hkey_current_user is a copy of everything in hkey_local_machine. 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). add the ...
...And 4 more matches
Bounding volume collision detection with THREE.js - Game development
use the box3 and sphere objects. once instantiated, they have methods available to do intersection tests against other volumes. instantiating boxes to create a box3 instance, we need to provide the lower and upper boundaries of the box. ...
...ated, they have methods available to do intersection tests against other volumes. instantiating boxes to create a box3 instance, we need to provide the lower and upper boundaries of the box. usually we will want this aabb to be "linked" to an object in our 3d world (like a character.) in three.js, geometry instances have a boundingbox property with min and max boundaries for the object. ...
...so any transformations such as scale, position, etc. applied to the mesh will be ignored while computing the calculating box. ...
...And 4 more matches
MDN Web Docs Glossary: Definitions of Web-related terms
authority certified challenge-response authentication character character encoding character set chrome cia cipher cipher suite ciphertext class client hints closure cms code splitting codec compile compile time computer programming conditional constant constructor continuous media control flow cookie copyleft cors cors-safelisted request header cors-safelisted response header crawler crlf cross axis cross-site scripting crud cryptanalysis cryptographic hash function ...
...al of service descriptor (css) deserialization developer tools dhtml digest digital certificate distributed denial of service dmz dns doctype document directive document environment dom (document object model) domain domain name domain sharding dominator dos attack dtls (datagram transport layer security) dtmf (dual-tone multi-frequency signaling) dynamic programming language dynamic typing e ecma ecmascript effective connection type element empty element encapsulation encryption endianness engine ...
... gonk google chrome gpl gpu graceful degradation grid grid areas grid axis grid cell grid column grid container grid lines grid row grid tracks guard gutters gzip compression h hash head high-level programming language hmac hoisting host hotlink houdini hpkp hsts html html5 http http header http/2 http/3 https hyperlink hypertext i i18n iana icann ice ide idempotent identifier ...
...And 4 more matches
Sending form data - Learn web development
dation in the previous article, we're ready to submit! this article looks at what happens when a user submits a form — where does the data go, and how do we handle it when it gets there? we also look at some of the security concerns associated with sending form data. prerequisites: basic computer literacy, an understanding of html, and basic knowledge of http and server-side programming. objective: to understand what happens when form data is submitted, including getting a basic idea of how data is processed on the server first we'll discuss what happens to the data when a form is submitted. client/server architecture at it's most basic, the web uses a client/server architecture that can be summarized as follows. a client (usually a web browser) sends a req...
...the http protocol. the server answers the request using the same protocol. an html form on a web page is nothing more than a convenient user-friendly way to configure an http request to send data to a server. this enables the user to provide information to be delivered in the http request. note: to get a better idea of how client-server architectures work, read our server-side website programming first steps module. on the client side: defining how to send the data the <form> element defines how the data will be sent. all of its attributes are designed to let you configure the request to be sent when a user hits a submit button. the two most important attributes are action and method. the action attribute the action attribute defines where the data gets sent. its value must be a val...
...ed on a secure page but you specify an insecure http url with the action attribute, all browsers display a security warning to the user each time they try to send data because the data will not be encrypted. the names and values of the non-file form controls are sent to the server as name=value pairs joined with ampersands. the action value should be a file on the server that can handle the incoming data, including ensuring server-side validation. the server then responds, generally handling the data and loading the url defined by the action attribute, causing a new page load (or a refresh of the existing page, if the action points to the same page). how the data is sent depends on the method attribute. the method attribute the method attribute defines how data is sent. the http protocol...
...And 4 more matches
Getting started with HTML - Learn web development
er important basic language features. along the way, there will be an opportunity to play with html too! prerequisites: basic computer literacy, basic software installed, and basic knowledge of working with files. objective: to gain basic familiarity with html, and practice writing a few html elements. what is html? html (hypertext markup language) is not a programming language. it is a markup language that tells web browsers how to structure the web pages you visit. it can be as complicated or as simple as the web developer wants it to be. html consists of a series of elements, which you use to enclose, wrap, or mark up different parts of content to make it appear or act in a certain way. the enclosing tags can make content into a hyperlink to connect to anot...
... the line. to close the element, put the closing tag </em> at the end of the line. doing this should give the line italic text formatting! see your changes update live in the output area. if you make a mistake, you can clear your work using the reset button. if you get really stuck, press the show solution button to see the answer. playable code <h2>live output</h2> <div class="output" style="min-height: 50px;"> </div> <h2>editable code</h2> <p class="a11y-label">press esc to move focus away from the code area (tab inserts a tab character).</p> <textarea id="code" class="playable-code" style="min-height: 100px;width: 95%"> this is my text. </textarea> <div class="controls"> <input id="reset" type="button" value="reset" /> <input id="solution" type="button" value="show solution" /...
...he title attribute, and when clicked, navigates to the web address in the href attribute. remember that you need to include a space between the element name, and between each attribute. if you make a mistake, you can always reset it using the reset button. if you get really stuck, press the show solution button to see the answer. ...
...And 4 more matches
HTML table basics - Learn web development
Learn › HTML › Tables › Basics
o html). objective: to gain basic familiarity with html tables. what is a table ? a table is a structured set of data made up of rows and columns (tabular data). a table allows you to quickly and easily look up values that indicate some kind of connection between different types of data, for example a person and their age, or a day of the week, or the timetable for a local swimming pool. tables are very commonly used in human society, and have been for a long time, as evidenced by this us census document from 1800: it is therefore no wonder that the creators of html provided a means by which to structure and present tabular data on the web. how does a table work? the point of a table is that it is rigid. information is easily interpreted by making visual associat...
... when done correctly, even blind people can interpret tabular data in an html table — a successful html table should enhance the experience of sighted and visually impaired users alike. table styling you can also have a look at the live example on github! one thing you'll notice is that the table does look a bit more readable there — this is because the table you see above on this page has minimal styling, whereas the github version has more significant css applied. be under no illusion; for tables to be effective on the web, you need to provide some styling information with css, as well as good solid structure with html. 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. we won't foc...
... significant css applied. be under no illusion; for tables to be effective on the web, you need to provide some styling information with css, as well as good solid structure with html. 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. we won't focus on css in this module, but we have provided a minimal css stylesheet for you to use that will make your tables more readable than the default you get without any styling. you can find the stylesheet here, and you can also find an html template that applies the stylesheet — these together will give you a good starting point for experimenting with html tables. when should you not use html tables? html tables should be used for tabular data —...
...And 4 more matches
Drawing graphics - Learn web development
this article provides an introduction to canvas, and further resources to allow you to learn more. 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. ...
...raws outline (stroke) text. both of these take three properties in their basic usage: the text string to draw and the x and y coordinates of the point to start drawing the text at. this works out as the bottom left corner of the text box (literally, the box surrounding the text you draw), which might confuse you as other drawing operations tend to start from the top left corner — bear this in mind. there are also a number of properties to help control text rendering such as font, which lets you specify font family, size, etc. it takes as its value the same syntax as the css font property. try adding the following block to the bottom of your javascript: ctx.strokestyle = 'white'; ctx.linewidth = 1; ctx.font = '36px arial'; ctx.stroketext('canvas text', 50, 50); ctx.fillstyle = 'red'; c...
... causes the coordinate origin (0, 0) to be moved to the center of the canvas, rather than being at the top left corner. this is very useful in many situations, like this one, where we want our design to be drawn relative to the center of the canvas. ...
...And 4 more matches
What is JavaScript? - Learn web development
tions such as "what is it?" and "what can you do with it?", and making sure you are comfortable with javascript's purpose. prerequisites: basic computer literacy, a basic understanding of html and css. objective: to gain familiarity with what javascript is, what it can do, and how it fits into a web site. a high-level definition javascript is a scripting or programming language that allows you to implement complex features on web pages — every time a web page does more than just sit there and display static information for you to look at — displaying timely content updates, interactive maps, animated 2d/3d graphics, scrolling video jukeboxes, etc. — you can bet that javascript is probably involved. it is the third layer of the layer cake of standard web ...
...w name'); para.textcontent = 'player 1: ' + name; } try clicking on this last version of the text label to see what happens (note also that you can find this demo on github — see the source code, or run it live)! javascript can do a lot more than that — let's explore what in more detail. so what can it really do? the core client-side javascript language consists of some common programming features that allow you to do things like: store useful values inside variables. in the above example for instance, we ask for a new name to be entered then store that name in a variable called name. operations on pieces of text (known as "strings" in programming). in the above example we take the string "player 1: " and join it to the name variable to create the complete text label, e.g. ''...
...mplete text label, e.g. ''player 1: chris". running code in response to certain events occurring on a web page. we used a click event in our example above to detect when the button is clicked and then run the code that updates the text label. and much more! what is even more exciting however is the functionality built on top of the client-side javascript language. ...
...And 4 more matches
Measuring performance - Learn web development
the metrics you choose to measure should be relevant to your users, site, and business goals. ...
...nologies. objective: to provide information about web performance metrics that you can collect through various web performance apis and tools that you can use to visualize that data. performance apis when writing code for the web, there are a large number of web apis available that allow you to create your own performance measuring tools. you can use the navigation timing api to measure client-side web performance; including the amount of time needed to unload the previous page, how long domain lookups take, the total time spent executing the window's load handler, and more. you can use the api for metrics related to all of the navigation events displayed in the didagram below. the performance api, which provides access to performance-related information for t...
...e needed to unload the previous page, how long domain lookups take, the total time spent executing the window's load handler, and more. you can use the api for metrics related to all of the navigation events displayed in the didagram below. the performance api, which provides access to performance-related information for the current page, includes the performance timeline api, the navigation timing api, the user timing api, and the resource timing api. these interfaces allows the accurate measurement of the time it takes for javascript tasks to complete. the performanceentry object is part of the performance timeline. a performance entry can be directly created by making a performance mark or measure (for example by calling the mark() method) at an explicit point in an application. perfor...
...And 4 more matches
Client-Server Overview - Learn web development
as most website server-side code handles requests and responses in similar ways, this will help you understand what you need to do when writing most of your own code. prerequisites: basic computer literacy. a basic understanding of what a web server is. objective: to understand client-server interactions in a dynamic website, and in particular what operations need to be performed by server-side code. ...
... client-server interactions in a dynamic website, and in particular what operations need to be performed by server-side code. there is no real code in the discussion because we haven't yet chosen a web framework to use to write our code! this discussion is however still very relevant, because the described behaviour must be implemented by your server-side code, irrespective of which programming language or web framework you select. web servers and http (a primer) web browsers communicate with web servers using the hypertext transfer protocol (http). when you click a link on a web page, submit a form, or run a search, the browser sends an http request to the server. this request includes: a url identifying the target server and resource (e.g. an html file, a particular data point ...
...s are inherently "insecure" as they can be changed by users and then resubmitted. as a result url parameters/get requests are not used for requests that update data on the server. post data. post requests add new resources, the data for which is encoded within the request body. client-side cookies. cookies contain session data about the client, including keys that the server can use to determine their login status and permissions/accesses to resources. web servers wait for client request messages, process them when they arrive, and reply to the web browser with an http response message. the response contains an http response status code indicating whether or not the request succeeded (e.g. "200 ok" for success, "404 not found" if the resource cannot be found, "403 forbidden" if t...
...And 4 more matches
Website security - Learn web development
u can do to harden your web application against the most common attacks. prerequisites: basic computer literacy. objective: to understand the most common threats to web application security and what you can do to reduce the risk of your site being hacked. what is website security? the internet is a dangerous place! with great regularity, we hear about websites becoming unavailable due to denial of service attacks, or displaying modified (and often damaging) information on their homepages. in other high-profile cases, millions of passwords, email addresses, and credit card details have been leaked into the public domain, exposing website users to both personal embarrassment and financial risk. the purpose of website security is to prevent these (or any) sorts ...
...l definition of website security is the act/practice of protecting websites from unauthorized access, use, modification, destruction, or disruption. effective website security requires design effort across the whole of the website: in your web application, the configuration of the web server, your policies for creating and renewing passwords, and the client-side code. 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. other attacks can be mitigated through your web server configuration, for example by enabling https. finally, there are publically available vulnerability scanner tools that can help you find...
...o protect your site. note: this is an introductory topic, designed to help you start thinking about website security, but it is not exhaustive. website security threats this section lists just a few of the most common website threats and how they are mitigated. as you read, note how threats are most successful when the web application either trusts, or is not paranoid enough about the data coming from the browser. cross-site scripting (xss) xss is a term used to describe a class of attacks that allow an attacker to inject client-side scripts through the website into the browsers of other users. because the injected code comes to the browser from the site, the code is trusted and can do things like send the user's site authorization cookie to the attacker. when the attacker has the cook...
...And 4 more matches
Introduction to client-side frameworks - Learn web development
tood as a javascript framework. as you read through this module, we will be working with that colloquial understanding. react extends javascript with html-like syntax, known as jsx. start learning react why do frameworks exist? we've discussed the environment that inspired the creation of frameworks, but not really why developers felt the need to make them. exploring the why requires first examining the challenges of software development. 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. this application should allow users to do things like render a list of tasks, add a new task, and delete a task; and it must do this while reliably tracking and updating the data underlying the application. in s...
... iterate over the data to render it; we can add to an object to make a new task; we can use an identifier to find, edit, or delete a task. when we remember that the application has to let the user to do all of these things through the browser, however, some cracks start to show. the real problem is this: every time we change our application’s state, we need to update the ui to match. we can examine the difficulty of this problem by looking at just one feature of our todo list app: rendering a list of tasks. the verbosity of dom changes building html elements and rendering them in the browser at the appropriate time takes a surprising amount of code. let's say that our state is an array of objects structured like this: const state = [ { id: 'todo-0', name: 'learn some framework...
...ore intuitive part of the development process. things to consider when using frameworks being an effective web developer means using the most appropriate tools for the job. javascript frameworks make front-end application development easy, but they are not a silver bullet that will solve all problems. this section talks about some of the things you should consider when using frameworks. bear in mind that you might not need a framework at all — beware that you don't end up using a framework just for the sake of it. familiarity with the tool just like vanilla javascript, frameworks take time to learn and have their quirks. before you decide to use a framework for a project, be sure you have time to learn enough of its features for it to be useful to you rather than it working against you,...
...And 4 more matches
Beginning our React todo list - Learn web development
onent definition and interactivity, which we'll add later. note: if you need to check your code against our version, you can find a finished version of the sample react app code in our todo-react repository. for a running live version, see https://mdn.github.io/todo-react-build/. prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. objective: to introduce our todo list case study, and get the basic app structure and styling in place. our app's user stories in software development, a user story is an actionable goal from the perspective of the user. defining user stories before we begin our work will help us focus our work. our app should fulfill the following stories: as a user, i ca...
...we'll tackle these stories one-by-one. pre-project housekeeping create-react-app has made a few files we won't be using at all for our project. we're not going to write per-component stylesheets, so first delete the app.css import from the top of app.js. we are also not going to be using the logo.svg file, so remove that import too. then, copy and paste the following commands into your terminal to delete some unneeded files. make sure you’re starting in the app's root directory! # move into the src directory of your project cd src # delete a few files rm -- app.test.js app.css logo.svg serviceworker.js setuptests.js # move back up to the root of the project cd .. notes: two of the files we’re deleting are for testing the application. we will not cover testing here. if you st...
...s. make sure you’re starting in the app's root directory! # move into the src directory of your project cd src # delete a few files rm -- app.test.js app.css logo.svg serviceworker.js setuptests.js # move back up to the root of the project cd .. notes: two of the files we’re deleting are for testing the application. we will not cover testing here. if you stopped your server to do the terminal tasks mentioned above, you’ll have to start it again using npm start. project starter code as a starting point for this project, we're going to provide two things: an app() function to replace the one you have now, and some css to style your app. the jsx copy the following snippet to your clipboard, then paste it into app.js so that it replaces the existing app() function: function app(...
...And 4 more matches
Styling Vue components with CSS - Learn web development
previous overview: client-side javascript frameworks next the time has finally come to make our app look a bit nicer. in this article we'll explore the different ways of styling vue components with css. prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. vue components are written as a combination of javascript objects that manage the app's data and an html-based template syntax that maps to the underlying dom structure. for installation, and to use some of the more advanced features of vue (like single file components or render functions), you'll need a terminal with node + npm installed. objective: to learn about styling vue components. styling vue components with css b...
... the reset styles should be applied to the app now. the images below show the look of the app before and...
...und-color: #000; } .btn-group { display: flex; justify-content: space-between; } .btn-group > * { flex: 1 1 auto; } .btn-group > * + * { margin-left: 0.8rem; } .label-wrapper { margin: 0; flex: 0 0 100%; text-align: center; } [class*="__lg"] { display: inline-block; width: 100%; font-size: 1.9rem; } [class*="__lg"]:not(:last-child) { margin-bottom: 1rem; } @media screen and (min-width: 620px) { [class*="__lg"] { font-size: 2.4rem; } } .visually-hidden { position: absolute; height: 1px; width: 1px; overflow: hidden; clip: rect(1px 1px 1px 1px); clip: rect(1px, 1px, 1px, 1px); clip-path: rect(1px, 1px, 1px, 1px); white-space: nowrap; } [class*="stack"] > * { margin-top: 0; margin-bottom: 0; } .stack-small > * + * { margin-top: 1.25rem; } .stac...
...And 4 more matches
Implementing feature detection - Learn web development
prerequisites: familiarity with the core html, css, and javascript languages; an idea of the high-level principles of cross-browser testing. objective: to understand what the concept of feature detection is, and be able to implement suitable solutions in css and javascript. the concept of feature detection the idea behind feature detection is that you can run a test to determine whether a feature is supported in the current browser, and then conditionally run code to provide an acceptable experience both in browsers that do support the feature, and browsers that don't. 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. let's recap and look at the...
... for now. start by making local copies of our css-feature-detect.html, flex-layout.css, float-layout.css, and basic-styling.css files. save them in a new directory. we will add the html5 shiv to our example too so that the html5 semantic elements will style properly in older versions of ie. ...
... making local copies of our css-feature-detect.html, flex-layout.css, float-layout.css, and basic-styling.css files. save them in a new directory. we will add the html5 shiv to our example too so that the html5 semantic elements will style properly in older versions of ie. ...
...And 4 more matches
Introduction to cross browser testing - Learn web development
ot your users — just because your site works on your macbook pro or high-end galaxy nexus, doesn't mean it will work for all your users — there's a whole lot of testing to be done! note: make the web work for everyone provides more useful perspective on the different browsers people use, their market share, and related cross browser compatibility issues. we should explain a few bits of terminology here. to start with, when we talk about sites "working cross browser", we are really saying that they should provide an acceptable user experience across different browsers. it is potentially ok for a site to not deliver the exact same experience on all browsers, as long as the core functionality is accessible in some way. on modern browsers you might get something animated, 3d and shiny, wh...
... already fixed out bugs in your code (see debugging html, debugging css, and what went wrong? troubleshooting javascript from previous topics to refresh your memory if needed). cross browser issues commonly occur because: sometimes browsers have bugs, or implement features differently. this situation is a lot less bad than it used to be; back when ie4 and netscape 4 were competing to be the dominant browser in the 1990s, browser companies deliberately implemented things differently to each other to try to gain competitive advantage, which made life hell for developers. browsers are much better at following standards these days, but differences and bugs still creep through sometimes. some browsers may have different levels of support for technology features than others. this is inevitable...
...be hard to read on a mobile device. if your site includes a load of big animations, it might be ok on a high spec tablet, but might be sluggish or jerky on a low end device. and more reasons besides. in later articles, we'll explore common cross browser problems, and look at solutions to those. workflows for cross browser testing all of this cross browser testing business may sound time consuming and scary, but it needn't be — you just need to plan carefully for it, and make sure you do enough testing in the right places to make sure you don't run into unexpected problems. if you are working on a large project, you should be testing it regularly, to make sure that new features work for your target audience, and that new additions to the code don't break old features that were previousl...
...And 4 more matches
Package management basics - Learn web development
l> <html lang="en-us"> <head> <meta charset="utf-8"> <title>my test page</title> </head> <body> <script src="./index.js"></script> </body> </html> next, we need to add an index.js file in the same directory as index.html. for now index.js can be empty; it just needs to exist. create this now. having fun with parcel now we’ll run our newly installed parcel tool. in your terminal, run the following command: parcel index.html you should see something like this printed to your terminal: server running at http://localhost:1234 ✨ built in 193ms. note: if you have trouble with the terminal returning a "command not found" type error, try running the above command with the npx utility, i.e. npx parcel index.html. now we're ready to benefit from the full javascript p...
...has also added the files required for someone else to pick up this project and install any dependencies that we’ve used. if you take a look in the directory you ran the parcel command in, you’ll find a number of new files; the most interesting of which are: node_modules: the dependency files of parcel and date-fns. dist: the distribution directory — these are the automatically packaged, minified files parcel has built for us, and the files it is serving at localhost:1234. these are the files you would upload to your web server when releasing the site online for public consumption. so long as we know the package name, we can use it in our code and parcel will go off, fetch, and install (actually "copy") the package into our local directory (under node_modules). building our code f...
... name the tool slightly differently. to install parcel 1.x you have to install parcel-bundler, but parcel 2.x is simply called parcel. there's a lot of tools available and the javascript package ecosystem is growing at an unprecedented rate, which has pros and cons. there's improvements being made all the time and the choice, for better or worse, is constantly increasing. faced with the overwhelming choice of tooling, probably the most important lesson is to learn what the tool you select is capable of. a rough guide to package manager clients this tutorial installed the parcel package using npm, but as mentioned earlier on there are some alternatives and it's worth at least knowing they exist and having some vague idea of the common commands across the tools. you've already seen some in ...
...And 4 more matches
mach
test/general/browser_pinnedtabs.js you run mach from the source directory, so you should be able to use your shell's tab completion to tab-complete paths to tests. mach figures out how to execute the tests for you! check out the linting and analysis tools: $ ./mach lint $ ./mach static-analysis mach and mozconfigs it's possible to use mach with multiple mozconfig files. mach's logic for determining which mozconfig to use is effectively the following: if a .mozconfig file (some say it is the file mozconfig without the dot) exists in the current directory, use that. if the mozconfig environment variable is set, use the file pointed to in that variable. if the current working directory mach is invoked with is inside an object directory, the mozconfig used when creating that object dire...
...etter and more unified developer experience for working on mozilla projects. if you don't use mach, you have to find another solution for the following problems: discovering what commands or make targets are available (mach exposes everything through mach help while inside "mozilla-central" , else you'll just get a cryptic error message) making more sense out of command output (mach offers terminal colorization and structured logging) getting productive tools in the hands of others (mach "advertises" tools to people through mach help (unless it actually just gives you a cryptic error message) - in the former case, people don't need to discover your tool from a blog post, wiki page, or word of mouth). so this 3rd point does not make much sense, does it? are there any known issues? yes,...
... you a cryptic error message) - in the former case, people don't need to discover your tool from a blog post, wiki page, or word of mouth). so this 3rd point does not make much sense, does it? are there any known issues? yes, of course several! mach is still relatively young ("born" in 2012) and there are a number of bugs and numerous areas for improvement. some larger known issues include: mintty (alternative terminal emulator on windows) doesn't work. text encoding issues (especially on windows where latin-1 is not the default system encoding). failed commands spew lots of extra error output, e.g. you will see a big mach error message when all that happened was an invoked command returned a non-0 exit code - possibly expectedly so in mozilla! generally, mach is known to work prett...
...And 4 more matches
Storage access policy: Block cookies from trackers
this article explains how the policy works and how you can test it. ...
...website broken as a result of this change, file a bug under the tracking protection component within the firefox product on bugzilla. alternatively you can report broken sites directly in firefox by clicking "report a problem" in the content blocking section of the control center (this shortcut may not be available in all versions of firefox). tracking protection explained how does firefox determine which resources are tracking resources? firefox uses the tracking protection list to determine which resources are tracking resources. the tracking protection list is maintained by disconnect. when the list is applied in firefox, we make two important changes: first, we only use the "basic protection" version of the list, which excludes some categories of trackers. in the future, we may expa...
... list, which excludes some categories of trackers. in the future, we may expand our protections to use the "strict protection" version of the list. second, firefox uses an additional "entity list", which prevents domains from being classified as trackers when they are loaded on a top-level site owned by the same organization. firefox uses the built-in tracking protection url classifier to determine which resources match the tracking protection list. domains are matched against the list in accordance with the safebrowsing v4 specification. specifically, we check the exact hostname of the resource against the list, as well as the last four hostnames formed by starting with the last five components and successively removing the leading component. consider the following examples: hos...
...And 4 more matches
OS.File for the main thread
sessionstore = os.path.join(os.constants.path.profiledir, "sessionstore.js"); // under linux, this is generally "$home/.firefox/profiles/$profilename/sessionstore.js" // under macos, this is generally "$home/library/application support/firefox/$profilename/sessionstore.js" // under windows, this is generally "%appdata%\local\temp\%profilename%"\sessionstore.js // etc. ...
..."sessionstore.js"); // under linux, this is generally "$home/.firefox/profiles/$profilename/sessionstore.js" // under macos, this is generally "$home/library/application support/firefox/$profilename/sessionstore.js" // under windows, this is generally "%appdata%\local\temp\%profilename%"\sessionstore.js // etc. ...
... } }, function onfailure(reason) { if (reason instanceof os.file.error && reason.becausenosuchfile) { // the file does not exist } else { // some other error throw reason; } } ); example: copy a file by chunks the following snippet writes a (presumably large) buffer by chunks. note that this snippet is useful as a demonstration of complex asynchronous programming with os.file – in most cases, function os.file.writeatomic is a better choice. let writestream = function writestream(data, outfile, chunksize) { let view = new uint8array(data); let loop = function loop(pos) { // define a recursive asynchronous loop. if (pos <= view.bytelength) { // note: should this be pos >= view.bytelength ? return p...
...And 4 more matches
MathML Torture Test
ont" id="mathfont"> <option value="default" selected="selected">default fonts</option> <option value="asana">asana</option> <option value="cambria">cambria</option> <option value="dejavu">dejavu</option> <option value="latinmodern">latin modern</option> <option value="libertinus">libertinus</option> <option value="lucidabright">lucida bright</option> <option value="minion">minion</option> <option value="stixtwo">stix two</option> <option value="texgyrebonum">tex gyre bonum</option> <option value="texgyrepagella">tex gyre pagella</option> <option value="texgyreschola">tex gyre schola</option> <option value="texgyretermes">tex gyre termes</option> <option value="xits">xits</option> </select> <br/> </p> <table> <tr> <td></td> ...
...> <msup> <mo>&part;</mo> <mn>2</mn> </msup> <mrow> <mo>&part;</mo> <msup> <mi>y</mi> <mn>2</mn> </msup> </mrow> </mfrac> <mo>)</mo> </mrow> <msup> <mrow> <mo minsize="150%">|</mo> <mi>&#x3c6; <!-- \varphi --></mi> <mo stretchy="false">(</mo> <mi>x</mi> <mo>+</mo> <mi mathvariant="normal">i</mi> <mi>y</mi> <mo stretchy="false">)</mo> <mo minsize="150%">|</mo> </mrow> <mn>2</mn> </msup> <mo>=</mo> ...
...frac><msqrt><mrow><mn>2</mn><mi>π</mi><mi>n</mi></mrow></msqrt><mrow><mi>n</mi><mo>!</mo></mrow></mfrac><msup><mrow><mo>(</mo><mfrac><mi>n</mi><mi>e</mi></mfrac><mo>)</mo></mrow><mi>n</mi></msup></mrow><mo>=</mo><mn>1</mn></math></td> </tr> <tr> <td>30</td> <td><img src="https://udn.realityripple.com/samples/d5/2cf8356a09.png" width="194" height="58" alt="leibniz formula for the determinant" /></td> <td><math display="block" xmlns="http://www.w3.org/1998/math/mathml"><mrow><mrow><mo lspace="0em" rspace="0em">det</mo><mo stretchy="false">(</mo><mi>a</mi><mo stretchy="false">)</mo></mrow><mo>=</mo><munder><mo>∑</mo><mrow><mi>σ</mi><mo>∊</mo><msub><mi>s</mi><mi>n</mi></msub></mrow></munder><mrow><mi>ϵ</mi><mo stretchy="false">(</mo><mi>σ</mi><mo stretchy="false">)</mo></m...
...And 4 more matches
NSS 3.22 release notes
distribution information the hg tag is nss_3_22_rtm. nss 3.22 requires nspr 4.11 or newer. nss 3.22 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_22_rtm/src/ new in nss 3.22 new functionality rsa-pss signatures are now supported (bug 1215295) new functions pk11_signwithmechanism() and pk11_signwithmechanism() are provided to allow rsa keys to be used with pss. ...
...ased on hashes other than sha-1 are now supported with pbkdf (bug 554827). pk11_createpbev2algorithmid() now supports sec_oid_pkcs5_pbkdf2 with cipheralgtag and prfalgtag set to sec_oid_hmac_sha256, sec_oid_hmac_sha224, sec_oid_hmac_sha384, or sec_oid_hmac_sha512. 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. a complete list can be found in nss config options. new functions in pk11pub.h pk11_signwithmechanism - this function is an extended version pk11_sign(). pk11_verifywithmechanism - this function is an extended version of pk11_verify(). th...
... sec_oid_tls_ecdh_rsa sec_oid_tls_ecdh_anon sec_oid_tls_rsa_export sec_oid_tls_dhe_rsa_export sec_oid_tls_dhe_dss_export sec_oid_tls_dh_rsa_export sec_oid_tls_dh_dss_export sec_oid_tls_dh_anon_export sec_oid_apply_ssl_policy in sslt.h ssl_signed_cert_timestamp_xtn is added to sslextensiontype. ...
...And 4 more matches
Creating JavaScript jstest reftests
t standard for example, the exact definition of pi or some details of array sorting. you should not add tests of the following type: tests of the jit test of jit correctness belong in the jit-test suite, read more here. performance tests or stress tests tests of spidermonkey's comformance to the ecmascript standard a brief history: in 2017, spidermonkey started comsuming test262, a comprehensive tests suite for ecmascript implementations. 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. test262 tests test262 is the implementation conformance test suite for the latest drafts of ecmascript language specification, as well as internatio...
...a different approach is to use the expectexitcode(exitcode) function which outputs a string: --- note: i...
...a different approach is to use the expectexitcode(exitcode) function which outputs a string: --- note: in this testcase, we expect ex...
...And 4 more matches
Animated PNG graphics
Mozilla › Tech › APNG
for simple animated images that have traditionally used the gif format, while adding support for 24-bit images and 8-bit transparency. apng is a simpler alternative to mng, providing a spec suitable for the most common usage of animated images on the internet. apng is backwards-compatible with png; any png decoder should be able to ignore the apng-specific chunks and display a single image. terminology the default image is the image described by the standard 'idat' chunks, and is the image that is displayed by decoders that do not support apng. the canvas is the area on the output device on which the frames are to be displayed. the contents of the canvas are not necessarily available to the decoder. as per the png specification, if a 'bkgd' chunk exists it may be used to fill the canvas ...
... 8 height unsigned int height of the following frame. 12 x_offset unsigned int x position at which to render the following frame. 16 y_offset unsigned int y position at which to render the following frame. 20 delay_num unsigned short frame delay fraction numerator. 22 delay_den unsigned short frame delay fraction denominator. 24 dispose_op byte type of frame area disposal to be done after rendering this frame. 25 blend_op byte type of frame area rendering for this frame. the frame must be rendered within the region defined by x_offset, y_offset, width, and height. the offsets must be non-negative, the dimensions must be positive, and the region may not fall outside of th...
...-negative, the dimensions must be positive, and the region may not fall outside of the default image. constraints on frame regions: x_offset >= 0 y_offset >= 0 width > 0 height > 0 x_offset + width <= 'ihdr' width y_offset + height <= 'ihdr' height the delay_num and delay_den parameters together specify a fraction indicating the time to display the current frame, in seconds. ...
...And 4 more matches
nsIContentViewer
boolean permitunload([optional] in boolean acallercloseswindow); boolean requestwindowclose(); void resetclosewindow(); void setbounds([const] in nsintrectref abounds); native code only! void setdocumentinternal(in nsidocumentptr adocument, in boolean aforcereuseinnerwindow); native code only! ...
...oad([optional] in boolean acallercloseswindow); boolean requestwindowclose(); void resetclosewindow(); void setbounds([const] in nsintrectref abounds); native code only! void setdocumentinternal(in nsidocumentptr adocument, in boolean aforcereuseinnerwindow); native code only! ...
...al] in boolean acallercloseswindow); boolean requestwindowclose(); void resetclosewindow(); void setbounds([const] in nsintrectref abounds); native code only! void setdocumentinternal(in nsidocumentptr adocument, in boolean aforcereuseinnerwindow); native code only! ...
...And 4 more matches
Debugger - Firefox Developer Tools
to a debug event handler, breakpoint handler, or similar function throws some exception, which we refer to asdebugger-exception here. exceptions thrown in the debugger are not propagated to debuggee code; instead, spidermonkey calls this function, passingdebugger-exception as its sole argument and the debugger instance as the this value. this function should return a resumption value, which determines how the debuggee should continue. if the uncaught exception hook itself throws an exception,uncaught-hook-exception, spidermonkey throws a new error object,confess-to-debuggee-exception, to the debuggee whose message blames the debugger, and includes textual descriptions ofuncaught-hook-exception and the originaldebugger-exception. if uncaughtexceptionhook’s value is null, spidermonkey th...
...obal object designated byglobal to the set of global objects this debugger instance is debugging. if the designated global is already a debuggee, this has no effect. return this debugger’s debugger.object instance referring to the designated global. the valueglobal may be any of the following: a global object. an html5 windowproxy object (an “outer window”, in firefox terminology), which is treated as if the window object of the browsing context’s active document (the “inner window”) were passed. a cross-compartment wrapper of an object; we apply the prior rules to the wrapped object. a debugger.object instance belonging to this debugger instance; we apply the prior rules to the referent. any other sort of value is treated as a typeer...
...if the object is not a global object, then the global in whose scope it was allocated is used. note that the result may include sources that can no longer ever be used by the debuggee: say, eval code that has finished running, or source for unreachable functions. whether such sources appear can be affected by the garbage collector’s behavior, so this function’s result is not entirely deterministic. findscripts([query]) return an array of debugger.script instances for all debuggee scripts matchingquery. each instance appears only once in the array.query is an object whose properties restrict which scripts are returned; a script must meet all the criteria given byquery to be returned. ifquery is omitted, we return the debugger.script instances for all debuggee scripts. querymay ...
...And 4 more matches
AudioNode - Web APIs
Web › API › AudioNode
cessing module (e.g. ...
...ing module (e.g. ...
... the web audio api will up-mix or down-mix the number of channels as required; check the web audio spec for details. for a list of all audio nodes, see the web audio api homepage. creating an audionode there are two ways to create an audionode: via the constuctor and via the factory method. ...
...And 4 more matches
Introduction to the DOM - Web APIs
the document object model (dom) is the data representation of the objects that comprise the structure and content of a document on the web. in this guide, we'll briefly introduce the dom. we'll look at how the dom represents an html or xml document in memory and how you use apis to create web content and applications. what is the dom? the document object model (dom) is a programming interface for html and xml documents. it represents the page so that programs can change the document structure, style, and content. the dom represents the document as nodes and objects. that way, programming languages can connect to the page. a web page is a document. this document can be either displayed in the browser window or as the html source. but it is the same document in both cases. the docume...
...d by other apis that add new features and capabilities to the dom. for example, the html dom api adds support for representing html documents to the core dom. dom and javascript the short example above, like nearly all of the examples in this reference, is javascript. that is to say, it's written in javascript, but it uses the dom to access the document and its elements. the dom is not a programming language, but without it, the javascript language wouldn't have any model or notion of web pages, html documents, xml documents, and their component parts (e.g. elements). 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 ...
...the dom and a scripting language like javascript. in the beginning, javascript and the dom were tightly intertwined, but eventually, they evolved into separate entities. ...
...And 4 more matches
HTMLMediaElement - Web APIs
ities that are common to audio and video. the htmlvideoelement and htmlaudioelement elements both inherit this interface. ...
...s that are common to audio and video. the htmlvideoelement and htmlaudioelement elements both inherit this interface. ...
...autoplay html attribute, indicating whether playback should automatically begin as soon as enough media is available to do so without interruption. note: automatically playing audio when the user doesn't expect or desire it is a poor user experience and should be avoided in most cases, though there are exceptions. see the autoplay guide for media and web audio apis for more information. keep in mind that browsers may ignore autoplay requests, so you should ensure that your code isn't dependent on autoplay working. htmlmediaelement.buffered read only returns a timeranges object that indicates the ranges of the media source that the browser has buffered (if any) at the moment the buffered property is accessed. htmlmediaelement.controller is a mediacontroller object that represents the ...
...And 4 more matches
Using IndexedDB - Web APIs
on returns an idbopendbrequest object with a result (success) or error value that you handle as an event. most other asynchronous functions in indexeddb do the same thing - return an idbrequest object with the result or error. the result for the open function is an instance of an idbdatabase. the second parameter to the open method is the version of the database. the version of the database determines the database schema — the object stores in the database and their structure. if the database doesn't already exist, it is created by the open operation, then an onupgradeneeded event is triggered and you create the database schema in the handler for this event. if the database does exist but you are specifying an upgraded version number, an onupgradeneeded event is triggered straight away, al...
...o "success") is fired with request as its target. once it is fired, the onsuccess() function on request is triggered with the success event as its argument. otherwise, if there was any problem, an error event (that is, a dom event whose type property is set to "error") is fired at request. this triggers the onerror() function with the error event as its argument. the indexeddb api is designed to minimize the need for error handling, so you're not likely to see many error events (at least, not once you're used to the api!). in the case of opening a database, however, there are some common conditions that generate error events. the most likely problem is that the user decided not to give your web app permission to create a database. one of the main design goals of indexeddb is to allow large a...
...attempts to open an indexeddb for storage. the user could choose to allow or deny access. also, indexeddb storage in browsers' privacy modes only lasts in-memory until the incognito session is closed (private browsing mode for firefox and incognito mode for chrome, but in firefox this is not implemented yet as of april 2020 so you can't use indexeddb in firefox private browsing at all). now, assuming that the user allowed your request to create a database, and you've received a success event to trigger the success callback; what's next? the request here was generated with a call to indexeddb.open(), so request.result is an instance of idbdatabase, and you definitely want to save that for later. your code might look something like this: var db; var request = indexeddb.open("mytestdatabase");...
...And 4 more matches
PerformanceEntry - Web APIs
a performance entry can be directly created by making a performance mark or measure (for example by calling the mark() method) at an explicit point in an application. performance entries are also created in indirect ways such as loading a resource (such as an image). performanceentry instances will always be one of the following subtypes: performancemark performancemeasure performanceframetiming performancenavigationtiming performanceresourcetiming performancepainttiming note: this feature is available in web workers. properties performanceentry.name read only a value that further specifies the value returned by the performanceentry.entrytype property. the value of both depends on the subtype. see property page for valid values. performanceentry.entrytype read only a domst...
... < properties.length; i++) { // check each property var supported = properties[i] in perfentry; if (supported) { var value = perfentry[properties[i]]; console.log("... " + properties[i] + " = " + value); } else { console.log("... ...
... var supported = properties[i] in perfentry; if (supported) { var value = perfentry[properties[i]]; console.log("... " + properties[i] + " = " + value); } else { console.log("... ...
...And 4 more matches
WebGLRenderingContext.blendFunc() - Web APIs
be described like this: color(rgba) = (sourcecolor * sfactor) + (destinationcolor * dfactor). the rbga values are between 0 and 1. constant factor description gl.zero 0,0,0,0 multiplies all colors by 0. gl.one 1,1,1,1 multiplies all colors by 1. gl.src_color rs, gs, bs, as multiplies all colors by the source colors. gl.one_minus_src_color 1-rs, 1-gs, 1-bs, 1-as multiplies all colors by 1 minus each source color. gl.dst_color rd, gd, bd, ad multiplies all colors by the destination color. gl.one_minus_dst_color 1-rd, 1-gd, 1-bd, 1-ad multiplies all colors by 1 minus each destination color. gl.src_alpha as, as, as, as multiplies all colors by the source alpha value. ...
...r 1-rs, 1-gs, 1-bs, 1-as multiplies all colors by 1 minus each source color. gl.dst_color rd, gd, bd, ad multiplies all colors by the destination color. gl.one_minus_dst_color 1-rd, 1-gd, 1-bd, 1-ad multiplies all colors by 1 minus each destination color. gl.src_alpha as, as, as, as multiplies all colors by the source alpha value. gl.one_minus_src_alpha 1-as, 1-as, 1-as, 1-as multiplies all colors by 1 minus the source alpha value. gl.dst_alpha ad, ad, ad, ad multiplies all colors by the destination alpha value. gl.one_minus_dst_alpha 1-ad, 1-ad, 1-ad, 1-ad multiplies all colors by 1 minus the destination alpha value. gl.constant_color rc, gc, bc, ac multiplies all colors by a consta...
..., 1-as, 1-as multiplies all colors by 1 minus the source alpha value. gl.dst_alpha ad, ad, ad, ad multiplies all colors by the destination alpha value. gl.one_minus_dst_alpha 1-ad, 1-ad, 1-ad, 1-ad multiplies all colors by 1 minus the destination alpha value. gl.constant_color rc, gc, bc, ac multiplies all colors by a constant color. gl.one_minus_constant_color 1-rc, 1-gc, 1-bc, 1-ac multiplies all colors by 1 minus a constant color. gl.constant_alpha ac, ac, ac, ac multiplies all colors by a constant alpha value. gl.one_minus_constant_alpha 1-ac, 1-ac, 1-ac, 1-ac multiplies all colors by 1 minus a constant alpha value. ...
...And 4 more matches
WebGLRenderingContext.blendFuncSeparate() - Web APIs
) + (destinationcolor * dstrgb) color(a) = (sourcealpha * srcalpha) + (destinationalpha * dstalpha) constant rgb factor alpha factor description gl.zero 0,0,0 0 multiplies all colors by 0. gl.one 1,1,1,1 1 multiplies all colors by 1. gl.src_color rs, gs, bs as multiplies all colors by the source colors. gl.one_minus_src_color 1-rs, 1-gs, 1-bs 1-as multiplies all colors by 1 minus each source color. gl.dst_color rd, gd, bd ad multiplies all colors by the destination color. gl.one_minus_dst_color 1-rd, 1-gd, 1-bd 1-ad multiplies all colors by 1 minus each destination color. gl.src_alpha as, as, as as multiplies all colors by the source alpha colo...
...s, 1-gs, 1-bs 1-as multiplies all colors by 1 minus each source color. gl.dst_color rd, gd, bd ad multiplies all colors by the destination color. gl.one_minus_dst_color 1-rd, 1-gd, 1-bd 1-ad multiplies all colors by 1 minus each destination color. gl.src_alpha as, as, as as multiplies all colors by the source alpha color. gl.one_minus_src_alpha 1-as, 1-as, 1-as 1-as multiplies all colors by 1 minus the source alpha color. gl.dst_alpha ad, ad, ad ad multiplies all colors by the destination alpha color. gl.one_minus_dst_alpha 1-ad, 1-ad, 1-ad 1-ad multiplies all colors by 1 minus the destination alpha color. gl.constant_color rc, gc, bc ac multiplies all colors by ...
... 1-as multiplies all colors by 1 minus the source alpha color. gl.dst_alpha ad, ad, ad ad multiplies all colors by the destination alpha color. gl.one_minus_dst_alpha 1-ad, 1-ad, 1-ad 1-ad multiplies all colors by 1 minus the destination alpha color. gl.constant_color rc, gc, bc ac multiplies all colors by a constant color. gl.one_minus_constant_color 1-rc, 1-gc, 1-bc 1-ac multiplies all colors by 1 minus a constant color. gl.constant_alpha ac, ac, ac ac multiplies all colors by a constant alpha value. gl.one_minus_constant_alpha 1-ac, 1-ac, 1-ac 1-ac multiplies all colors by 1 minus a constant alpha value. ...
...And 4 more matches
Introduction to the Real-time Transport Protocol (RTP) - Web APIs
ined in rfc 3550, is an ietf standard protocol to enable real-time connectivity for exchanging data that needs real-time priority. this article provides an overview of what rtp is and how it functions in the context of webrtc. note: webrtc actually uses srtp (secure real-time transport protocol) to ensure that the exchanged data is secure and authenticated as appropriate. ...
...rtp is a data transport protocol, whose mission is to move data between two endpoints as efficiently as possible under current conditions. ...
...top udp for its performance as well as its multiplexing and checksum features. rtp supports multicast; while this isn't yet important for webrtc, it's likely to matter in the future, when webrtc is (hopefully) enhanced to support multi-user conversations. rtp isn't limited to use in audiovisual communication. it can be used for any form of continuous or active data transfer, including data streaming, active badges or status display updates, or control and measurement information transport. things rtp doesn't do rtp itself doesn't provide every possible feature, which is why other protocols are also used by webrtc. some of the more noteworthy things rtp doesn't include: editor's note: we should add information about where these deficiencies are compensated for, if they are at all. rtp...
...And 4 more matches
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
ity to insert a human into a virtual environment. to accomplish this, software needs the ability to not only track the locations, orientation, and movements of objects in the virtual world, but the user's location, orientation, and movement as well. but webxr goes beyond that by adding the ability to track the location, orientation, and motion of the input devices which generate data used to determine the position and movement of individual parts of the viewer's body (with appropriate equipment). the location and movement of the user's headset represent their head's position and orientation in the virtual environment. hand controllers represent their hands in the same manner. other hardware elements can be used similarly to represent other parts of the body, providing additional data to use ...
...rt among the coordinate systems, perform operations affecting these spaces and their corresponding objects, and so forth. describing a position relative to a space there are two scenarios in which you may need to describe a position and/or orientation relative to a space. the first is described above: applying a reference space to an offset (or vice-versa, since the result is the same) to determine the transform matrix that represents the resulting location in the space's coordinate system. poses once your reference space or spaces are established for the various key objects in the scene, you will have times when you need to describe another position relative to the origin of a particular reference space. this is done using poses. a pose, simply put, describes a position and orientation ...
...scribes a position and orientation relative to the origin of the reference space from which it was created. in webxr, a pose is represented by an xrpose object, whose transform property is an xrrigidtransform defining the transform matrix that, applied to any coordinate, vector, or matrix in the original space, converts it to the target space. thus a pose can be used to not only convert and determine positions, but also rotational information. there is only one way to create an xrpose, and that's using the getpose() method on an animation frame as given using an xrframe object. this means that most frequently, you'll be using poses within your frame rendering code, which is executed as a callback from the xrframe method requestanimationframe(). getpose() computes the position of an xrrefer...
...And 4 more matches
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
local symbols in the context where settimeout() was called will not be available when the string is evaluated as code. reasons for delays longer than specified there are a number of reasons why a timeout may take longer to fire than anticipated. this section describes the most common reasons. timeouts throttled to ≥ 4ms in modern browsers, settimeout()/setinterval() calls are throttled to a minimum of once every 4 ms when successive calls are triggered due to callback nesting (where the nesting level is at least a certain depth), or after certain number of successive intervals. take this example: function cb() { f(); settimeout(cb, 0); } settimeout(cb, 0); setinterval(f, 0); in chrome and firefox, the 5th successive callback call is clamped; safari clamps on the 6th call; in edge its ...
...lready did this with settimeout(); see below). historically some browsers implemented this throttling behaviour a bit differently (e.g. firefox) — on setinterval() calls made from anywhere, or when a nested settimeout() is called where the nesting level is at least a certain depth. to implement a 0 ms timeout in a modern browser, you can use window.postmessage() as described here. note: the minimum delay, dom_min_timeout_value, is 4 ms (stored in a preference in firefox: dom.min_timeout_value), with a dom_clamp_timeout_nesting_level of 5. note: 4 ms is specified by the html5 spec and is consistent across browsers released in 2010 and onward. prior to (firefox 5.0 / thunderbird 5.0 / seamonkey 2.2), the minimum timeout value for nested timeouts was 10 ms. timeouts in inactive tabs t...
... firefox 50 no longer throttles background tabs if a web audio api audiocontext is actively playing sound. ...
...And 4 more matches
Web applications and ARIA FAQ - Accessibility
upport aria. 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. browsers aria is supported in the following browsers: browser minimum version notes firefox 3.0+ works with nvda, jaws 10+, and orca chrome latest screen reader support still experimental as of chrome 15 safari 4+ safari 5 support is much improved. live region support requires safari 5 with voiceover on ios5 or os x lion opera 9.5+ requires voiceover on os x. tbd: how well does this currently wo...
...a. no live region support in nvda. ie9 support is much improved. in some cases, earlier versions may support only some features of aria. more detailed browser compatibility charts are available from multiple sources: caniuse.com the paciello group assistive technologies assistive technologies are increasingly adopting aria. some of them include: assistive technology minimum version for basic aria minimum version for live region and alert support nvda 2010.2 (nvda is always a free upgrade) 2011.1 for firefox, no live region support in ie as of 2011.2. orca ? (tbd) ? (tbd) voiceover osx 10.5, ios 4 os x 10.7 ios 5 jaws 8 10 window-eyes 7 no live region support currently ...
...infusion google closure google web toolkit bbc glow yahoo! user interface library (yui) for more information about javascript toolkit accessibility: steve faulkner's wai-aria implementation in javascript ui libraries can you show me an example of aria in action? sure. 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. unfortunately, there isn't a more semantic tag available to developers in html 4, so we need to include aria roles and properties. these are specified by adding attributes to the element. in this example, the role="progressbar" attribute informs the browser that this element is actually a javascri...
...And 4 more matches
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
"say what you see" kinds of features. on microsoft windows, these kinds of assistive technology acquire this necessary information via a combination of hacks, msaa and proprietary doms. msaa is supposed to be the "right way" for accessibility aids to get information, but sometimes the hacks are more effective. for example, screen readers look for screen draws of a vertical blinking line, to determine the location of the caret. without doing this, screen readers would not be able to let the user know where there caret has moved to in most programs, because so many applications do not use the system caret (gecko does not). this is so commonly done, that no one even bothers to support the msaa caret, after all the hack is general solution works with pretty much all applications. msaa provides ...
...rs, you can get everyone to agree on a different solution, and you're sure that you won't be needing to support other assistive technologies later. deciding which msaa features to support msaa methods - cheat sheet for developers the iaccessible interface is used in a tree of iaccessible's, each one representing a data node, similar to a dom. here are the methods supported in iaccessible - a minimal implementation would contain those marked "[important]": get_accparent: get the parent of an iaccessible. [important] get_accchildcount: get the number of children of an iaccessible. [important] get_accchild: get the child of an iaccessible. [important] get_accname: get the "name" of the iaccessible, for example the name of a button, checkbox or menu item. try to use unique names for ea...
...movesizestart event_system_movesizeend event_system_contexthelpstart event_system_contexthelpend event_system_dragdropstart event_system_dragdropend event_system_dialogstart event_system_dialogend event_system_scrollingstart event_system_scrollingend [possibly important, talk to at vendor] event_system_switchstart event_system_switchend event_system_minimizestart event_system_minimizeend event_object_create [don't implement, watching system generated versions of this event causes assistive technology crashes] event_object_destroy [don't implement, watching system generated versions of this event causes assistive technology crashes] event_object_show [can be important, depending on project] event_object_hide [can be important, ...
...And 4 more matches
Perceivable - Accessibility
existing audio does not convey the full meaning expressed by the video. 1.2.6 provide sign language equivalent to prerecorded audio (aaa) an equivalent sign language video should be provided for any prerecorded content containing audio. 1.2.7 provide extended video with audio descriptions (aaa) where audio descriptions cannot be provided (see 1.2.5) due to video timing issues (e.g., there are no suitable pauses in the content in which to insert the audio descriptions), an alternative version of the video should be provided that includes inserted pauses (and audio descriptions). 1.2.8 provide an alternative for prerecorded media (aaa) for all content that features video, a descriptive text transcript should be provided, for example a script of t...
...eate content that can be presented in different ways this guideline refers to the ability of content to be consumed by users in multiple ways, accomodating their differing needs. success criteria how to conform to the criteria practical resource 1.3.1 info and relationships (a) any content structure—or visual relationship made between content—can also be determined programmatically, or be inferred from text description. the main situations in which this is relevant are: text labels and the form elements they describe. these are associated unambiguously using the <label> element, which can be picked up by screenreaders, etc. image alt text. content images should have text available that clearly describes the image's contents, which can be p...
...ee the image. lists. if the order of list items is important, use an ordered list (<ol>). the whole of html: a good basis for accessibility is packed with information about this, but you should particularly refer to good semantics, ui controls, and text alternatives. 1.3.2 meaningful content sequence (a) a sensible, logical reading order should be easy to determine for any content, even if it is visually presented in an unusual way. the order should be made obvious by use of correct semantic elements (e.g., headings, paragraphs), with css being used to create any unusual layout styles, irrespective of the markup. again, refer to html: a good basis for accessibility. 1.3.3 sensory characteristics (a) instructions for operating controls o...
...And 4 more matches
width - CSS: Cascading Style Sheets
Web › CSS › @viewport › width
syntax /* an example with one viewport value: */ @viewport { width: 320px; } /* an example with two viewport values: */ @viewport { width: 320px, 120px; } values auto the used value is calculated from the other css descriptors' values. <length> a non-negative absolute or relative length. ...
... syntax /* an example with one viewport value: */ @viewport { width: 320px; } /* an example with two viewport values: */ @viewport { width: 320px, 120px; } values auto the used value is calculated from the other css descriptors' values. <length> a non-negative absolute or relative length. ...
...d value is calculated from the other css descriptors' values. <length> a non-negative absolute or relative length. <percentage> a percentage value relative to the width or height of the initial viewport at zoom factor 1.0, for horizontal and vertical lengths respectively. must be non-negative. ...
...And 4 more matches
Border-radius generator - CSS: Cascading Style Sheets
ta-topic="bottom-left-h" data-unit=" px" data-sensivity="2"></div> </div> </div> </div> </div> <div id="controls" class="group section"> <div class="group section"> <div id="dimensions"> <div class="ui-input-slider" data-topic="width" data-info="width" data-unit=" px" data-min="150" data-max="700" data-sensivity="1"></div> <div class="ui-input-slider" data-topic="height" data-info="height" data-unit=" px" data-min="75" data-max="350" data-sensivity="1"></div> </div> <div id="output"></div> </div> <div class="group section"> <div id="radius-lock"> <div class="info"...
...ght { bottom: 0; right: 0; } #bottom-right .radius { border-bottom-right-radius: 100%; bottom: 0; right: 0; } /* bottom left */ #bottom-left { bottom: 0; left: 0; } #bottom-left .radius { border-bottom-left-radius: 100%; bottom: 0; } /* input sliders */ #preview .ui-input-slider { margin: 10px; position: absolute; z-index: 10; } #radius-ui-sliders { width: 100%; height: 100%; min-height: 75px; min-width: 150px; padding: 20px 50px; top: -20px; left: -50px; position: relative; } #tlr { top: -30px; left: -50px; display: none; } #tlw { top: -30px; left: 30px; } #tlh { top: 20px; left: -50px; } #trr { top: -30px; right: -50px; display: none; } #trw { top: -30px; right: 30px; } #trh { top: 20px; right: -50px; } #brr { bottom: -30px; right: -50px; di...
...("mousemove", slidermotion); document.body.style.cursor = "auto"; slider.style.cursor = "pointer"; }); var slidermotion = function slidermotion(e) { slider.style.cursor = "e-resize"; var delta = (e.clientx - startx) / obj.sensivity | 0; var value = delta * obj.step + start_value; setvalue(obj.topic, value); } return slider; } var inputslider = function(node) { var min = node.getattribute('data-min') | 0; var max = node.getattribute('data-max') | 0; var step = node.getattribute('data-step') | 0; var value = node.getattribute('data-value') | 0; var topic = node.getattribute('data-topic'); var unit = node.getattribute('data-unit'); var name = node.getattribute('data-info'); var sensivity = node.getattribute('data-sensivity') | 0; this.min = mi...
...And 4 more matches
Using multi-column layouts - CSS: Cascading Style Sheets
and width two css properties control whether and how many columns will appear: column-count and column-width. the column-count property sets the number of columns to a particular number. e.g., example 1 html <div id="col"> <p> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p> <p> ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p> <p> duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </p> <p> excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </div> css #col { column-count: 2;...
...ehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </p> <p> excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ...
... duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. ...
...And 4 more matches
Relationship of grid layout to other layout methods - CSS: Cascading Style Sheets
her specifications, including grid layout. in the future, they may well apply to other layout methods as well. in a later guide in this series, i’ll be taking a proper look at box alignment and how it works in grid layout. for now, here is a comparison between simple examples of flexbox and grid. in the first example, which uses flexbox, i have a container with three items inside. the wrapper min-height is set, so it defines the height of the flex container. i have set align-items on the flex container to flex-end so the items will line up at the end of the flex container. i have also set the align-self property on box1 so it will override the default and stretch to the height of the container and on box2 so it aligns to the start of the flex container. * {box-sizing: border-box;} .wra...
...this time we are using the box alignment properties as they apply to a grid layout. so we align to start and end rather than flex-start and flex-end. in the case of a grid layout, we are aligning the items inside their grid ar...
...ox3">three</div> </div> .wrapper { display: grid; grid-template-columns: repeat(3,1fr); align-items: end; grid-auto-rows: 200px; } .box1 { align-self: stretch; } .box2 { align-self: start; } the fr unit and flex-basis we have already seen how the fr unit works to assign a proportion of available space in the grid container to our grid tracks. the fr unit, when combined with the minmax() function can give us very similar behavior to the flex properties in flexbox while still enabling the creation of a layout in two dimensions. if we look back at the example where i demonstrated the difference between one and two-dimensional layouts, you can see there is a difference between the way of the two layouts work responsively. with the flex layout, if we drag our window wider and s...
...And 4 more matches
max-block-size - CSS: Cascading Style Sheets
tion is vertical, max-block-size is the same as max-width. the other dimension's maximum length is specified using the max-inline-size property. this is useful because the max-width is always used for horizontal sizes and max-height is always used for vertical sizes, and if you need to set lengths based on the size of your text content, you need to be able to do so with the writing direction in mind. any time you would normally use max-height or max-width, you should instead use max-block-size to set the maximum "height" of the content (even though this may not be a vertical value) and max-inline-size to set the maximum "width" of the content (although this may instead be vertical rather than horizontal). see the example in writing-mode, which shows the different writing modes in action. ...
...le is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax /* <length> values */ max-block-size: 300px; max-block-size: 25em; /* <percentage> values */ max-block-size: 75%; /* keyword values */ max-block-size: auto; max-block-size: max-content; max-block-size: min-content; max-block-size: fit-content(20em); /* global values */ max-block-size: inherit; max-block-size: initial; max-block-size: unset; values the max-block-size property's value can be any value that's legal for the max-width and max-height properties: <length> defines the max-width as an absolute value. <percentage> defines the max-width as a percentage of the containing block's widt...
...s value can be any value that's legal for the max-width and max-height properties: <length> defines the max-width as an absolute value. <percentage> defines the max-width as a percentage of the containing block's width. auto the browser will calculate and select a max-width for the specified element. none no limit on the size of the box. max-content the intrinsic preferred max-width. min-content the intrinsic minimum max-width. fit-content(<length-percentage>) uses the fit-content formula with the available space replaced by the specified argument, i.e. min(max-content, max(min-content, argument)). how writing-mode affects directionality the values of writing-mode affect the mapping of max-block-size to max-width or max-height as follows: values of writing-mode ...
...And 4 more matches
max-height - CSS: Cascading Style Sheets
the max-height css property sets the maximum height of an element. it prevents the used value of the height property from becoming larger than the value specified for max-height. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. max-height overrides height, but min-height overrides max-height. ...
...b repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. max-height overrides height, but min-height overrides max-height. syntax /* <length> value */ max-height: 3.5em; /* <percentage> value */ max-height: 75%; /* keyword values */ max-height: none; max-height: max-content; max-height: min-content; max-height: fit-content(20em); /* global values */ max-height: inherit; max-height: initial; max-height: unset; values <length> defines the max-height as an absolute value. <percentage> defines the max-height as a percentage of the containing block's height. auto the browser will calculate and select a max-height for the specified element. none no limit on the size of the bo...
...lues */ max-height: inherit; max-height: initial; max-height: unset; values <length> defines the max-height as an absolute value. <percentage> defines the max-height as a percentage of the containing block's height. auto the browser will calculate and select a max-height for the specified element. none no limit on the size of the box. max-content the intrinsic preferred max-height. min-content the intrinsic minimum max-height. fit-content(<length-percentage>) uses the fit-content formula with the available space replaced by the specified argument, i.e. min(max-content, max(min-content, argument)). accessibility concerns ensure that elements set with a max-height are not truncated and/or do not obscure other content when the page is zoomed to increase text size. mdn un...
...And 4 more matches
max() - CSS: Cascading Style Sheets
Web › CSS › max
n a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. in the first above example, the width will be at least 400px, but will be wider if the the viewport is more than 2000px wide (in which case 1vw would be 20px, so 20vw would be 400px). think of the max() value as providing the minimum value a property can have. syntax the max() function takes one or more comma-separated expressions as its parameter, with the largest (most positive) expression value used as the value of the property to which it is assigned. the expressions can be math expressions (using arithmetic operators), literal values, or other expressions, such as attr(), that evaluate to a valid argument type (li...
...n have. syntax the max() function takes one or more comma-separated expressions as its parameter, with the largest (most positive) expression value used as the value of the property to which it is assigned. 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. you can use different units for each value in your expression. you may also use parentheses to establish computation order when needed. notes math expressions involving percentages for widths and heights on table columns, table column groups, table rows, table row groups, and table cells in both auto and fixed layout tables may be treated as if auto had been specified.
...ou can use different units for each value in your expression. you may also use parentheses to establish computation order when needed. notes math expressions involving percentages for widths and heights on table columns, table column groups, table rows, table row groups, and table cells in both auto and fixed layout tables may be treated as if auto had been specified. it is permitted to nest min() and other max() functions as expression values. 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. make sure to put a ...
...And 4 more matches
repeat() - CSS: Cascading Style Sheets
Web › CSS › repeat
list, allowing a large number of columns or rows that exhibit a recurring pattern to be written in a more compact form. this function can be used in the css grid properties grid-template-columns and grid-template-rows. ...
...unction can be used in the css grid properties grid-template-columns and grid-template-rows. ...
... [col-end]) repeat(4, [col-start] 60% [col-end]) repeat(4, [col-start] 1fr [col-end]) repeat(4, [col-start] min-content [col-end]) repeat(4, [col-start] max-content [col-end]) repeat(4, [col-start] auto [col-end]) repeat(4, [col-start] minmax(100px, 1fr) [col-end]) repeat(4, [col-start] fit-content(200px) [col-end]) repeat(4, 10px [col-start] 30% [col-middle] auto [col-end]) repeat(4, [col-start] min-content [col-middle] max-content [col-end]) /* <auto-repeat> values */ repeat(auto-fill, 250px) repeat(auto-fit, 250px) repeat(auto-fill, [col-start] 250px [col-end]) repeat(auto-fit, [col-start] 250px [col-end]) repeat(auto-fill, [col-start] minmax(100px, 1fr) [col-end]) repeat(auto-fill, 10px [col-start] 30% [col-middle] 400px [col-end]) /* <fixed-repeat> values */ repeat(4, 250px) repeat(4, ...
...And 4 more matches
Content Security Policy (CSP) - HTTP
Web › HTTP › CSP
security-policy" content="default-src 'self'; img-src https://*; child-src 'none';"> threats mitigating cross site scripting a primary goal of csp is to mitigate and report xss attacks. xss attacks exploit the browser's trust of the content received from the server. malicious scripts are executed by the victim's browser because the browser trusts the source of the content, even when it's not coming from where it seems to be coming from. csp makes it possible for server administrators to reduce or eliminate the vectors by which xss can occur by specifying the domains that the browser should consider to be valid sources of executable scripts. a csp compatible browser will then only execute scripts loaded in source files received from those allowlisted domains, ignoring all other script (inc...
...trict inline styles from being applied from a <style> element or a style attribute. there are specific directives for a wide variety of types of items, so that each type can have its own policy, including fonts, frames, images, audio and video media, scripts, and workers. examples: common use cases this section provides examples of some common security policy scenarios. ...
...h type can have its own policy, including fonts, frames, images, audio and video media, scripts, and workers. examples: common use cases this section provides examples of some common security policy scenarios. ...
...And 4 more matches
Index - HTTP
Web › HTTP › Headers › Index
and informs the client of its choice with the content-encoding response header. 5 accept-language content negotiation, http, http header, reference, request header the accept-language request http header advertises which languages the client is able to understand, and which locale variant is preferred. (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. browsers set adequate values for this header according to their user interface language and even if a user can change it, this happens rarely (and is frowned upon as it leads to fingerprinting). 6 accept-ranges ...
...ransmitted as the result of content negotiation. 27 content-range http, http header, reference, response header, header the content-range response http header indicates where in a full body message a partial message belongs. 28 content-security-policy csp, http, reference, security, header the http content-security-policy response header allows web site administrators to control resources the user agent is allowed to load for a given page. with a few exceptions, policies mostly involve specifying server origins and script endpoints. this helps guard against cross-site scripting attacks (xss). 29 csp: base-uri csp, directive, document directive, http, security the http content-security-policy base-uri directive restricts the urls w...
...being loaded is going to want to perform a large allocation. it is currently only implemented in firefox, but is harmless to send to every browser. 85 last-modified http, http header, reference, response header the last-modified response http header contains the date and time at which the origin server believes the resource was last modified. it is used as a validator to determine if a resource received or stored is the same. less accurate than an etag header, it is a fallback mechanism. conditional requests containing if-modified-since or if-unmodified-since headers make use of this field. 86 location http, http header, reference, response header the location response header indicates the url to redirect a page to. it only provides a meaning when ser...
...And 4 more matches
Introduction - JavaScript
« previousnext » this chapter introduces javascript and discusses some of its fundamental concepts. what you should already know this guide assumes you have the following basic background: a general understanding of the internet and the world wide web (www). good working knowledge of hypertext markup language (html). some programming experience. if you are new to programming, try one of the tutorials linked on the main page about javascript. where to find javascript information the javascript documentation on mdn includes the following: learn web development provides information for beginners and introduces basic concepts of programming and the internet. javascript guide (this guide) provides an overview about the javascript language and its objects. javascri...
... webpage (dom) looks. and, likewise, node.js javascript on the server can respond to custom requests from code written in the browser. javascript and java javascript and java are similar in some ways but fundamentally different in some others. the javascript language resembles java but does not have java's static typing and strong type checking. javascript follows most java expression syntax, naming conventions and basic control-flow constructs which was the reason why it was renamed from livescript to javascript. in contrast to java's compile-time system of classes built by declarations, javascript supports a runtime system based on a small number of data types representing numeric, boolean, and string values. javascript has a prototype-based object model instead of the more common class-...
...s, executing as loosely typed methods. javascript is a very free-form language compared to java. you do not have to declare all variables, classes, and methods. you do not have to be concerned with whether methods are public, private, or protected, and you do not have to implement interfaces. variables, parameters, and function return types are not explicitly typed. java is a class-based programming language designed for fast execution and type safety. type safety means, for instance, that you can't cast a java integer into an object reference or access private memory by corrupting java bytecodes. java's class-based model means that programs consist exclusively of classes and their methods. java's class inheritance and strong typing generally require tightly coupled object hierarchies. thes...
...And 4 more matches
String.prototype.indexOf() - JavaScript
the indexof() method returns the index within the calling string object of the first occurrence of the specified value, starting the search at fromindex. returns -1 if the value is not found. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. note: for the array method, see array.prototype.indexof(). syntax str.indexof(searchvalue [, fromindex]) parameters searchvalue the string value to search for. if no string is explicitly provided, searchvalue will be coerced to "undefined", and this value will be searched for in str. so, for example: 'undefined'.indexof() will return 0, as undefined is found at posi...
...ters searchvalue the string value to search for. if no string is explicitly provided, searchvalue will be coerced to "undefined", and this value will be searched for in str. so, for example: 'undefined'.indexof() will return 0, as undefined is found at position 0 in the string undefined. 'undefine'.indexof() however will return -1, as undefined is not found in the string undefine. fromindex optional an integer representing the index at which to start the search. defaults to 0. for fromindex values lower than 0, or greater than str.length, the search starts at index 0 and str.length, respectively. for example, 'hello world'.indexof('o', -5) will return 4, as it starts at position 0, and o is found at position 4. on the other hand, 'hello world'.indexof('o', 11) (and with an...
...ptional an integer representing the index at which to start the search. defaults to 0. for fromindex values lower than 0, or greater than str.length, the search starts at index 0 and str.length, respectively. for example, 'hello world'.indexof('o', -5) will return 4, as it starts at position 0, and o is found at position 4. on the other hand, 'hello world'.indexof('o', 11) (and with any fromindex value greater than 11) will return -1, as the search is started at position 11, a position after the end of the string. return value the index of the first occurrence of searchvalue, or -1 if not found. an empty string searchvalue produces strange results. ...
...And 4 more matches
WebAssembly - JavaScript
. webassembly.runtimeerror() error type that is thrown whenever webassembly specifies a trap. webassembly.table() an array-like structure representing a webassembly table, which stores function references. static methods webassembly.instantiate() the primary api for compiling and instantiating webassembly code, returning both a module and its first instance. ...
...iating webassembly code, returning both a module and its first instance. webassembly.instantiatestreaming() compiles and instantiates a webassembly module directly from a streamed underlying source, returning both a module and its first instance. webassembly.compile() compiles a webassembly.module from webassembly binary code, leaving instantiation as a separate step. webassembly.compilestreaming() compiles a webassembly.module directly from a streamed underlying source, leaving instantiation as a separate step. webassembly.validate() validates a given typed array of webassembly binary code, returning whether the bytes are valid webassembly code (true) or not (false). ...
...ming() compiles a webassembly.module directly from a streamed underlying source, leaving instantiation as a separate step. webassembly.validate() validates a given typed array of webassembly binary code, returning whether the bytes are valid webassembly code (true) or not (false). examples stream a .wasm module then compile and instantiate it the following example (see our instantiate-streaming.html demo on github, and view it live also) directly streams a .wasm module from an underlying source then compiles and instantiates it, the promise fulfilling with a resultobject. ...
...And 4 more matches
Critical rendering path - Web Performance
ndering path includes the document object model (dom), css object model (cssom), render tree and layout. the document object model is created as the html is parsed. the html may request javascript, which may, in turn, alter the dom. the html includes or makes requests for styles, which in turn builds the css object model. the browser engine combines the two to create the render tree. layout determines the size and location of everything on the page. once layout is determined, pixels are painted to the screen. optimizing the critical rendering path improves the time to first render. understanding and optimizing the critical rendering path is important to ensure reflows and repaints can happen at 60 frames per second, to ensure performant user interactions and avoid jank. understanding crp ...
...has to walk up the dom to check if .foo has an ancestor .bar. the more specific tag requires more work from the browser, but this penalty is not likely worth optimizing. if you measure the time it takes to parse css, you'll be amazed at how fast browsers truly are. the more specific rule is more expensive because it has to traverse more nodes in the dom tree - but that extra expense is generally minimal. measure first. optimize as needed. specificity is likely not your low hanging fruit. when it comes to css, selector performance optimization, improvements will only be in microseconds. there are other ways to optimize css, such as minification, and separating defered css into non-blocking requests by using media queries. render tree the render tree captures both the content and the styles:...
... the render tree only captures visible content. the head section (generally) doesn't contain any visible information, and is therefore not included in the render tree. if there's a display: none; set on an element, neither it, nor any of its descendants, are in the render tree. ...
...And 4 more matches
Performance fundamentals - Web Performance
pside down, starving your brain of inputs to create the illusion of discrete reality). on a computer display, a higher framerate simply makes for a more faithful imitation of reality. note: humans usually cannot perceive differences in framerate above 60hz. that's why most modern electronic displays are designed to refresh at that rate. a television probably looks choppy and unrealistic to a hummingbird, for example. memory usage memory usage is another key metric. unlike responsiveness and framerate, users don't directly perceive memory usage, but memory usage closely approximates "user state". an ideal system would maintain 100% of user state at all times: all applications in the system would run simultaneously, and all applications would retain the state created by the user the last t...
...ice, no system can maintain all user states. intelligently allocating memory to user state is an important concern that we go over in more detail below. power usage the final metric discussed here is power usage. like memory usage, users perceive power usage only indirectly, by how long their devices can maintain all other upp goals. in service of meeting upp goals, the system must use only the minimum power required. the remainder of this document will discuss performance in terms of these metrics. platform performance optimizations this section provides a brief overview of how firefox/gecko contributes to performance generally, below the level of all applications. from a developer's or user's perspective, this answers the question, "what does the platform do for you?" web technologies...
...nes — and in some cases even close to "native code". the graphics pipeline in gecko that underpins html, css, and canvas is optimized in several ways. the html/css layout and graphics code in gecko reduces invalidation and repainting for common cases like scrolling; developers get this support "for free". pixel buffers painted by both gecko "automatically" and applications to canvas "manually" minimize copies when being drawn to the display framebuffer. this is done by avoiding intermediate surfaces where they would create overhead (such as per-application "back buffers" in many other operating systems), and by using special memory for graphics buffers that can be directly accessed by the compositor hardware. complex scenes are rendered using the device's gpu for maximum performance. to im...
...And 4 more matches
Index - XPath
Web › XPath › Index
found 57 pages: # page tags and summary 1 xpath css selectors, dom, jxon, landing, path, xml, xpath, xslt xpath stands for xml path language. it uses a non-xml syntax to provide a flexible way of addressing (pointing to) different parts of an xml document. it can also be used to test addressed nodes within a document to determine whether they match a pattern or not. 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. also see the 'axes' section in the xpath spec. 3 ancestor axe, xpath no summary! 4 ancestor-or-self axe, x...
...lf axis indicates the context node itself. it can be abbreviated as a single period (.). 16 comparison of css selectors and xpath css, draft, needscontent, reference, selectors, xpath this article seeks to document the difference between css selectors and xpath for web developers to be able to better choose the right tool for the right job. 17 functions transforming_xml_with_xslt, xpath, xpath_reference, xslt, xslt_reference no summary! 18 boolean xslt, xslt_reference the boolean function evaluates an expression and returns true or false. 19 ceiling xslt, xslt_reference the ceiling function evaluates a decimal number and returns the smallest integer greater than or equal to the decimal number. 20 ...
...n or equal to the decimal number. 20 choose function, xpath, xslt the choose function returns one of the specified objects based on a boolean parameter. 21 concat xslt, xslt_reference the concat function concatenates two or more strings and returns the resulting string. 22 contains xslt, xslt_reference the contains function determines whether the first argument string contains the second argument string and returns boolean true or false. 23 count xslt, xslt_reference the count function counts the number of nodes in a node-set and returns an integer. 24 current xslt, xslt_reference the current function can be used to get the context node in an xslt instruction. 25 documen...
...And 4 more matches
Compiling a New C/C++ Module to WebAssembly - WebAssembly
e we'll look at, whereby you get emscripten to generate everything you need to run your code, as webassembly, in the browser. first we need an example to compile. 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. if we don’t specify this, emscripten will just output asm.js, as it does by default. -o h...
...u’ve just compiled c to webassembly and run it in your browser! using a custom html template sometimes you will want to use a custom html template. let's look at how we can do this. ...
...e following c code in a file called hello2.c, in a new directory: #include <stdio.h> int main(int argc, char ** argv) { printf("hello world\n"); } search for the file shell_minimal.html in your emsdk repo. copy it into a sub-directory called html_template inside your previous new directory. ...
...And 4 more matches
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
eviews. follow every step methodically and you'll probably be alright. focus on the fact that once you get the build working, it'll probably work effortlessly from then on. maybe. on other platforms on other platforms, namely linux and macos, the process is much easier. all the tools for building are available built-in, and therefore all you have to do is run some commands in the terminal. you can find full instructions for almost any os here. structuring your project mozilla includes a number of complex extensions that are integrated into its build process. it has thus been necessary to solve all of the issues involved in creating and registering xpcom components, building jar files and manifests, installing the lot into the firefox extensions/ directory and so fo...
...sion="1.0"?> <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest"> <em:id>myextension@mycompany.com</em:id> <em:version>0.1</em:version> <em:targetapplication> <!-- firefox --> <description> <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> <em:minversion>1.0+</em:minversion> <em:maxversion>1.0+</em:maxversion> </description> </em:targetapplication> <!-- front-end metadata --> <em:name>my first extension</em:name> <em:description>just an example.</em:description> <em:creator>allpeers.com</em:creator> <em:homepageurl>http://www.allpeers.com/blog/</em:homepageurl> </description> </rdf> there's a...
...ry to register these components, as described in the next section. registering your components this article explains how to register xpcom components in gecko 2.0 and later. building it as mentioned above, you'll probably want to build your extension immediately after creating your idl files in order to generate the c++ stubs for your component implementations. i'm assuming that you've already built firefox successfully. if not, return immediately to the beginning of this article and don't come back til you have a functioning firefox.exe. do not pass go. do not collect $200. still here? okay, now we have to modify your .mozconfig (in the /mozilla/ root directory) so that your extension is built along with mozilla. add the following line at the end of the fil...
...And 3 more matches
Install Manifests - Archive of obsolete content
it contains metadata identifying the add-on, providing information about who created it, where more information can be found about it, which versions of what applications it is compatible with, how it should be updated, and so on. the format of the install manifest is rdf/xml. the file must be called install.rdf and live at the top level of an add-on's xpi file. ...
...d>{daf44bf7-a45e-4450-979c-91cf07434c3d}</em:id> name the name of the add-on; intended for display in the ui. examples <em:name>my extension</em:name> targetapplication an object specifying an application targeted by this add-on. this means that the add-on will work with the application identified by the id property (<em:id>) specified (for a comprehensive list of application ids and valid min/maxversions for them see valid application versions for add-on developers), from the minimum version (<em:minversion>) up to and including the maximum version (<em:maxversion>). however, while <em:maxversion> is a required property, it is ignored unless you also set <em:strictcompatibility> in the main <description> of your install.rdf (i.e. not in <em:targetapplication>). these version strings a...
...equired property, it is ignored unless you also set <em:strictcompatibility> in the main <description> of your install.rdf (i.e. not in <em:targetapplication>). these version strings are formatted in the same fashion as the version property and will be compared to the application version; this allows the extension author to specify which versions of firefox an extension has been tested with. id, minversion, and maxversion are all required. note: extensions compatible with firefox 3.5 should specify a maxversion of 3.5.*, so that they are automatically compatible with security and stability updates. for firefox 3.0, a maxversion of 3.0.* should be used. extensions compatible only with firefox or thunderbird 2 should specify a maxversion of 2.0.0.*. the install manifest must specify at lea...
...And 3 more matches
The Essentials of an Extension - Archive of obsolete content
or firefox 2, localizing this file is a little more complicated. we'll discuss localization further ahead in this section. <em:type>2</em:type> this specifies that the add-on being installed is an extension. you can read about different possible types in the install.rdf specification. <em:targetapplication> <description> <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> <em:minversion>4.0</em:minversion> <em:maxversion>10.*</em:maxversion> </description> </em:targetapplication> this node specifies the target application and target versions for the extension, specifically firefox, from version 4 up to version 10. the uuid is firefox's unique id. other mozilla and mozilla-based applications such as thunderbird and seamonkey have their own. you can have an extens...
...irefox, from version 4 up to version 10. the uuid is firefox's unique id. other mozilla and mozilla-based applications such as thunderbird and seamonkey have their own. you can have an extension that works on multiple applications and versions. for example, if you create a firefox extension, it would normally take little effort to port it to seamonkey, which has very similar features and ui. the min and max version specify the version range in which the extension can be installed. here's more about the version format. if the application or version range don't match, you won't be allowed to install the extension, or the extension will be installed in a disabled state. users can disable version checks through preferences or installing add-ons like the add-on compatibility reporter. beginning w...
... has a unique id, which you should have on most elements in your xul. the second attribute is the namespace, which is something you should always define in your xul root element. it says that this node and all child nodes are xul. you only need to change namespace declarations when you mix different types of content in the same document, such as xul with html or svg. you may have noticed the naming we use on several places, such as the id xulschoolhello-browser-overlay. this is the namespacing standard that we use to avoid conflicts with firefox and other extensions, as well as making some development tasks easier. we namespace all ids and style classes in overlay elements because they will be mixed with other elements in the main browser window. if we used generic ids like container or in...
...And 3 more matches
List of Mozilla-Based Applications - Archive of obsolete content
celtx media tool cenzic hailstorm vulnerability assessment and management ...
...web browser uses most of the firefox 55 source code batik java-based toolkit uses mozilla rhino bitbox security focused browser seemingly based on firefox blackbird browser for african american community bluegriffon wysiwyg editor next generation version of composer buzzbird twitter client built on xulrunner camino browser 2.5m downloads and ~400,000 active users ... celtx media tool cenzic hailstorm vulnerability assessment and management tool uses gecko chatzilla irc client standalone version (xulrunner) chromium and google chrome web browser uses mozilla nss and npapi libraries chromeless browser with html-based interface ...
...r based on chromium uses mozilla nss and npapi libraries emusic download manager music downloader for emusic emusic remote music manager enlis genome personal 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...
...And 3 more matches
JavaScript Client API - Archive of obsolete content
to any of our trademarks. before starting before you start learning the javascript api, you should spend some time on http://docs.services.mozilla.com/ reading about how the sync service operates. this will help fundamental understanding significantly. api location the sync javascript client api is defined in files in the services/sync/ directory of mozilla-central or similar repository. terminology syncengine the main sync client object. it's what starts all the magic. engine governs the synchronizing of a specific set of information. e.g. there is an engine for bookmarks, tabs, history, preferences, etc. record piece of information that gets synchronized. records are transformed to wbo's, uploaded to a collection in a sync server and eventually downloaded by other sync clients...
...r.prototype, _logname: "record.foo", ttl: foo_ttl // optional }; utils.defergetset(foorec, "cleartext", ["bar", "baz"]); the store object the store object (which extends store, as defined in services/sync/modules/engines.js) has the job of creating and maintaining a set of record objects from the underlying data. the store must also make updates to the underlying data itself based on incoming record objects. the majority of the code you write for syncing a new data type will most likely be in the store implementation. each record that the store keeps track of must be identified by a unique id (unique among all records in the store) called guid. depending of what type of data you're working with, you might already have guids built into your data that you can make use of (note that gu...
... createrecord the createrecord( id, collection ) method gets called by the engine to request a new record for an item with a given guid. it's your store's responsibility to instantiate a record object, assign the given guid, and return it. itemexists(guid) should simply return true if an item with the given gui...
...And 3 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
) blocks throughout the code to differentiate between the browsers. the following code shows blocks designated for internet explorer: . . . var elm; if (ns4) elm = document.layers["myid"]; else if (ie4) elm = document.all["myid"] the above code isn't extensible, so if you want it to support a new browser, you must update these blocks throughout the web application. the easiest way to eliminate the need to recode for a new browser is to abstract out functionality. rather than multiple if() else() blocks, you increase efficiency by taking common tasks and abstracting them out into their own functions. not only does this make the code easier to read, it simplifies adding support for new clients: var elm = getelmbyid("myid"); function getelmbyid(aid){ var element = null; if (ismo...
... however, does not comply with the w3c web standards and simply returns a regular document. javascript differences most differences between mozilla and internet explorer are usually blamed on javascript. however, the issues usually lie in the apis that a browser exposes to javascript, such as the dom hooks. the two browsers possess few core javascript differences; issues encountered are often timing related. javascript date differences the only date difference is the getyear method. as per the ecmascript specification (which is the specification javascript follows), running new date().getyear() in 2004 will return "104". per the ecmascript specification, getyear returns the year minus 1900, originally meant to return "98" for 1998. getyear was deprecated in ecmascript version 3 and replac...
...(i.e. for 1999, getyear() returns 99, for 2000, it returns 2000). javascript execution differences different browsers execute javascript differently. ...
...And 3 more matches
Anonymous Content - Archive of obsolete content
e. anonymous content introduces the concept of scope to nodes within a document. because anonymous content elements can also have bindings attached that generate their own anonymous content, this scoping can be taken to an arbitrary level of nesting. explicit content is said to be at the document-level scope. anonymous content nodes are in their own binding-level scopes. binding scopes are determined by the bound element that contains the binding responsible for the generation of the anonymous nodes. the scope of an element can be determined using the getbindingparent method on the documentxbl interface. see section 3 for more information. this method returns the bound element in the enclosing scope that is responsible for the anonymous node. if invoked on an element at the document-level ...
...are at the document-level scope. content generation rules for generation whenever bindings are attached to an element, anonymous content will potentially be generated or destroyed. when a new binding is attached, the bindings in its explicit 'inherits' chain are checked to see if any have anonymous content templates. the most derived binding in the chain with a template is the one used to determine if anonymous content should be generated. anonymous content is only generated from a template if there are insertion points defined within the template for all of the explicit content found underneath the bound element at the time the check for generation is made. if the binding specifies no insertion points for explicit content, then anonymous content will only be constructed if the bound elem...
...nerated. anonymous content is only generated from a template if there are insertion points defined within the template for all of the explicit content found underneath the bound element at the time the check for generation is made. if the binding specifies no insertion points for explicit content, then anonymous content will only be constructed if the bound element has no explicit children. assuming that all explicit children have valid insertion points, the anonymous content is generated underneath the bound element. the binding responsible for the generation is referred to as the primary generating binding. whenever the primary generating binding changes on a bound element, all anonymous nodes in the scope of the bound element are destroyed. attribute forwarding attributes on anonymous ...
...And 3 more matches
RDF Modifications - Archive of obsolete content
in the new data but were there before are removed. this means that the observer will be called only for the triples that differ between the new and old version of the data. if the reloaded datasource hasn't changed, the builder won't receive any notifications. this saves a lot of extra work. the rdf observer also has two methods onbeginupdatebatch and onendupdatebatch. these are called when performing a lot of operations on a datasource. when changing the datasource, the changes are surrounded by begin and end batch calls. then, rather than notify on every change, the datasource will send one notification when the changes are finished. the template builder then rebuilds the template completely when done. this is useful when making a large amount of changes to avoid having to keep recalculatin...
...ntainer="?start" child="?photo"/> <triple subject="?photo" predicate="http://purl.org/dc/elements/1.1/title" object="?title"/> <triple subject="?photo" predicate="http://purl.org/dc/elements/1.1/description" object="?description"/> </query> these query statements will cause any photos with both a title and a description to be displayed. assuming that the 'obelisk' photo doesn't have a description already, adding the triple listed above should cause a new result to be available for this photo. the builder scans through the query statements one by one. the content tag can safely be skipped at this part of the process, so the builder moves onto the member statement. this type of statement can only cause a change when an item is being added...
...y backwards through the statements, in order to fill in the remaining variables. it does this in a similar manner as it does when it generates results, but traverses the statements in the opposite order. the previous triple will fill in a value for the ?title variable, since we now have a value for the ?photo variable referred to by the triple's subject attribute. next, the member statement is examined, and, in this situation, the builder fills in the known ?photo variable, and looks for a parent container containing this value. there is a container 'http://www.xulplanet.com/rdf/myphotos', so the ?start variable will be filled in with this value. now, the potential result so far is: (?photo = http://www.xulplanet.com/ndeakin/images/t/obelisk.jpg, ?description = 'one of the thirty or so egyp...
...And 3 more matches
Custom toolbar button - Archive of obsolete content
description="my custom toolbar button" em:creator="my name" em:id="custom-toolbar-button@example.com" em:version="1.0" em:homepageurl="http://developer.mozilla.org/en/docs/custom_toolbar_button" em:iconurl="chrome://custombutton/content/icon.png" > <em:targetapplication><!-- firefox --> <description em:id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}" em:minversion="1.4" em:maxversion="*" /> </em:targetapplication> <em:targetapplication><!-- thunderbird --> <description em:id="{3550f703-e582-4d05-9a08-453d09bdfdc6}" em:minversion="1.5" em:maxversion="51.0" /> </em:targetapplication> <em:targetapplication><!-- sunbird --> <description em:id="{718e30fb-e89b-41dd-9da7-e25a45638b28}" ...
...change the text between double-quote characters on these three lines. opti...
...llowing content, and paste it into the new file: custombutton = { 1: function () { alert("just testing") }, } there is nothing to customize for now. save the file. the next section in this tutorial contains examples of code that you can use to make your button do something useful. explanation: this file specifies what happens when you press the button. it uses the javascript programming language, together with features provided by the application. 9. download the button image. get a context menu for the image that you see here (for example, by right-clicking it). choose save image as... from the context menu, and save it in the same chrome directory as the files you have just created. ensure that the name of the saved file is: button-1.png explanation: the image is in fou...
...And 3 more matches
Numeric Controls - Archive of obsolete content
ype attribute to the value number. this type of textbox may only be used to enter numbers. other characters are not allowed and are just ignored if typed. in addition, arrow buttons appear beside the textbox to allow the user to cycle through the values. as with other textboxes, the default value can be specified with the value attribute. naturally, this value should be a number. ...
... only be used to enter numbers. other characters are not allowed and are just ignored if typed. in addition, arrow buttons appear beside the textbox to allow the user to cycle through the values. as with other textboxes, the default value can be specified with the value attribute. naturally, this value should be a number. however, the minimum and maximum values can also be specified using the min and max attributes. ...
.... as with other textboxes, the default value can be specified with the value attribute. naturally, this value should be a number. however, the minimum and maximum values can also be specified using the min and max attributes. if these are set, you can control the range of values that the textbox may be set to. if the user enters a value less or greater than this value, it will be reset to the minimum or maximum value as necessary. for instance, the following numeric textbox has a range between 1 and 20. <textbox type="number" min="1" max="20"/> as the default value isn't specified, it will default to 1, the minimum value. ...
...And 3 more matches
Progress Meters - Archive of obsolete content
« previousnext » in this section, we'll look at creating progress meters. adding a progress meter a progress meter is a bar that indicates how much of a task has been completed. you typically see it when downloading files or when performing a lengthy operation. xul has a progressmeter element which can be used to create these. there are two types of progress meters: determinate and indeterminate. determinate progress meters are used when you know the length of time that an operation will take. the progress meter will fill up and, once full, the operation should be finished. this can be used for the download file dialog as the size of the file is known. indeterminate progress meters are used when you do not know the length of time of an operation. the progress meter will ...
.... the progress meter will fill up and, once full, the operation should be finished. this can be used for the download file dialog as the size of the file is known. indeterminate progress meters are used when you do not know the length of time of an operation. the progress meter will have an animation such as a spinning barber pole or a sliding box, depending on the platform and theme used. ...
...p and, once full, the operation should be finished. this can be used for the download file dialog as the size of the file is known. indeterminate progress meters are used when you do not know the length of time of an operation. the progress meter will have an animation such as a spinning barber pole or a sliding box, depending on the platform and theme used. determinate progress meter: indeterminate progress meter: the progress meter has the following syntax: <html:progress id="identifier" mode="determined" value="50" max="100"/> the attributes are as follows: id the unique identifer of the progress meter mode the type of the progress meter. if this is set to determined, the progress meter is a determinate progress meter where it fills up as the task completes. ...
...And 3 more matches
Mozilla release FAQ - Archive of obsolete content
take a look at mozilla.org's npl area for details. what are all of the codenames given to various netscape/mozilla projects? gecko (formerly raptor) is the new html rendering engine in mozilla. it features speed improvements, a more modular nature, and significantly less platform-dependant code. it is more suitable for being embedded in other applications than the previous rendering engine. ...
...to get a cvs update of the source? you should be at the top of the source (the directory with the top-level makefile). if you wish only to refresh a certain area of the tree, you can go to that area and do a cvs update there. ...
...ase send your specs in to me) removed because the tree has changed enough that we'll probably need new times for all the builds. please send stats to me in the following format: cpu/mhz, architecture, ram, disk type, os version, compiler version, build type, tree date -- build time example: 21164/533, alpha, 512m edo, ultra2 scsi, linux kernel 2.2.11, gcc 2.95, non-debug, 19 august 1999 cvs -- 25 minutes how do i run the binary on unix? i get library errors in dist/bin there's a script called mozilla. use that to launch mozilla for you -- it sets ld_library_path automatically. to launch other binaries from dist/bin with the correct environment, use run-mozilla.sh ./your_binary features, patches what platforms is mozilla available for? mozilla is currently targeted for win32, macos, and unix/x...
...And 3 more matches
Adobe Flash - Archive of obsolete content
ash has exposed the scriptability feature in netscape gecko browsers since flash 6r49 and later. versions of flash prior to flash 6r49 (such as flash 5) are not scriptable in netscape gecko browsers. thus client-side detection for the right version of flash is an important aspect of creating a scripted flash experience. 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. until macromedia changes this from within the flash plugin, scriptability can not be used on mac os x browsers based on gecko. the example below shows a detection heuristic in action. example 1: verifying the flash p...
...bility can not be used on mac os x browsers based on gecko. the example below shows a detection heuristic in action. example 1: verifying the flash plugin version below, javascript identifies the version of flash, and whether it is scriptable in netscape gecko: can we have javascript in a wiki page? <script type="text/javascript">identifyflash();</script> typically, javascript code that determines what version of the plugin is installed looks at the mimetypes array that is part of the navigator object. every plugin exposes a description string that typically includes the plugin's name and version number. the flash plugin's description string uses a standard versioning nomenclature that can then be parsed for meaningful information. for example, the current flash plugin version is flash 6...
...ach-o browsers based on netscape gecko expose this information in their user-agent string. an algorithmic approach to detecting flash plugin version might be: var plugin = navigator.mimetypes["application/x-shockwave-flash"].enabledplugin; var description = plugin.description; // 1. tokenize description string to its constituent parts var versionarray = description.match(/[\d.]+/g); // 2. ...
...And 3 more matches
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
engines for javascript such as v8 from google and squirrelfish for webkit, these engines are raising the bar on performance and help to maintain a competitive environment that will hopefully direct competitive focus on the performance aspect of all the major javascript implementations. there are currently two main javascript engines used server-side and both are from the minds at mozilla: mozilla rhino and mozilla spidermonkey. rhino is a javascript interpreter written in java that can also bridge javascript to java server-side. steve yegge of google has been doing interesting work with this engine. spidermonkey on the other hand is the javascript engine (written in c) in the highly popular mozilla firefox browser. spidermonkey is what will evolve to become tracemonk...
...abase driver for mysql is loaded and the connection string to a database named rhino on my local machine is configured using the user account urhino with the password of prhino. the sql statement is prepared, executed, and printed with the help of the metadata obtained from the resultset. sample output is shown in listing 2. id: 1 first_name: sammy last_name: hamm department: it title: network administrator ---------- id: 2 first_name: nigel last_name: bitters department: finance title: accounting manager ... it’s clear to see that with just a few lines of code, we can easily take advantage of sql data stores in javascript. the sample script in listing 1 could be factored out to it’s own function to retrieve the set of employee information, or abstracted further...
...listing 1 could be factored out to it’s own function to retrieve the set of employee information, or abstracted further into a more generic data handler class. next we’ll take a look at another powerful feature in rhino, e4x processing. e4x (ecmascript for xml) is an extension of javascript which provides direct support for xml, greatly simplifying the process of consuming xml via javascript. rhino’s support of this important standard eliminates the pain of using dom or sax based parsers in java. listing 3 below details a script used to process an rss feed from the mozilla website. importpackage( java.net ); // connect to the remote resource var u = new url( "http://www.mozilla.org/news.rdf" ); var c = u.openconnection(); c.connect(); // read in the raw data ...
...And 3 more matches
Plug-in Development Overview - Gecko Plugin API Reference
l file of that mime type, or from the server. the server looks for the mime type registered by a plug-in, based on the file extension, and starts sending the file to the browser. the browser looks up the media type, and if it finds a plug-in registered to that type, loads the plug-in software. when it starts up, the browser checks for plug-in modules for the platform and registers them. it determines which plug-ins are installed and which types they support through a combination of user preferences that are private to the browser, the contents of the plug-ins directory, or the registry on windows. a mime type is made up of a major type (such as application or image) and a minor type, for example, image/jpeg. if you define a new mime type for a plug-in, you must register it with ietf (inter...
...xtensions (mime) part two: media types" rfc-4288: "media type specifications and registration procedures" there are some variations to how plug-ins are handled on different platforms. the following sections describe platform-specific discovery and registration: ms windows unix mac os x ms windows on windows, plug-ins are found according to the section how gecko finds plug-ins. 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. but when the plug-in is loaded from a well-known directory, a different method must be used. in this case to ensure the plug-in file will be loaded, it should have a name in the form of "np*.dll". also, the...
...wser normally uses the content of the registry entries for the plug-in described below in installation using the registry. but when the plug-in is loaded from a well-known directory, a different method must be used. in this case to ensure the plug-in file will be loaded, it should have a name in the form of "np*.dll". also, the windows version information for the plug-in dll will be used to determines the mime types, file extensions, file open template, plug-in name, and description. for this the version stamp of the embedded resource of the plug-in dll should contain the following set of string/value pairs: mimetype: for mime types fileextents: for file extensions fileopenname: for file open template productname: for plug-in name filedescription: for description language: for langu...
...And 3 more matches
How CSS is structured - Learn web development
previous overview: first steps next now that you are beginning to understanding the purpose and use of css, let's examine the structure of css. prerequisites: basic computer literacy, basic software installed, basic knowledge of working with files, html basics (study introduction to html), and an idea of how css works. objective: to learn css's fundamental syntax structures in detail. applying css to html first, let's examine three methods of applying css to a document: with an external stylesheet, with an internal stylesheet, and with inline styles. external stylesheet an external stylesheet contains css in a separate file with a .css extension. this is the most common and useful method of bringing css to a document. you can link a single css file...
....</div></div> .outer { border: 5px solid black; } .box { padding: 10px; width: calc(90% - 30px); background-color: rebeccapurple; color: white; } this renders as: a function consists of the function name, and parentheses to enclose the values for the function. in the case of the calc() example above, the values define the width of this box to be 90% of the containing block width, minus 30 pixels. the result of the calculation isn't something that can be computed in advance and entered as a static value. another example would be the various values for transform, such as rotate(). <div class="box"></div> .box { margin: 30px; width: 100px; height: 100px; background-color: rebeccapurple; transform: rotate(0.8turn) } the output from the above code looks like this: ...
...n @rule that you are likely to encounter is @media, which is used to create media queries. media queries use conditional logic for applying css styling. in the example below, the stylesheet defines a default pink background for the <body> element. however, a media query follows that defines a blue background if the browser viewport is wider than 30em. body { background-color: pink; } @media (min-width: 30em) { body { background-color: blue; } } you will encounter other @rules throughout these tutorials. see if you can add a media query that changes styles based on the viewport width. change the width of your browser window to see the result. shorthands some properties like font, background, padding, border, and margin are called shorthand properties. this is because shorthand...
...And 3 more matches
Images in HTML - Learn web development
covered in getting started with html.) objective: to learn how to embed simple images in html, annotate them with captions, and how html images relate to css background images. how do we put an image on a webpage? in order to put a simple image on a webpage, we use the <img> element. this is an empty element (meaning that it has no text content or closing tag) that requires a minimum of one attribute to be useful — src (sometimes spoken as its full title, source). the src attribute contains a path pointing to the image you want to embed in the page, which can be a relative or absolute url, in the same way as href attribute values in <a> elements. note: you should read a quick primer on urls and paths to refresh your memory on relative and absolute urls before continui...
... the image url. set the image's correct width and height (hint: it is 200px wide and 171px high), then experiment with other values to see what the effect is. set a title on the image. if you make a mistake, you can always reset it using the reset button. ...
...ke a mistake, you can always reset it using the reset button. ...
...And 3 more matches
Choosing the right approach - Learn web development
previous overview: asynchronous to finish this module off, we'll provide a brief discussion of the different coding techniques and features we've discussed throughout, looking at which one you should use when, with recommendations and reminders of common pitfalls where appropriate. we'll probably add to this resource as time goes on. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals. objective: to be able to make a sound choice of when to use different asynchronous programming techniques. asynchronous callbacks generally found in old-style apis, involves a function being passed into another function as a parameter, which is then invoked when an asynchronous operation has been completed, so that the callback c...
...rt 2.0nodejs full support 0.12legend full support full support no support no supportsee implementation notes.see implementation notes. further information graceful asynchronous programming with promises using promises promise reference promise.all() a javascript feature that allows you to wait for multiple promises to complete before then running a further operation based on the results of all the other promises. useful for... single delayed operation repeating operation multiple sequential operations multiple simultaneous operations no no n...
...led from version 7.0.0: this feature is behind the --harmony runtime flag.legend full support full support no support no supportuser must explicitly enable this feature.user must explicitly enable this feature. ...
...And 3 more matches
Introduction to events - Learn web development
previous overview: building blocks next events are actions or occurrences that happen in the system you are programming, which the system tells you about so you can respond to them in some way if desired. for example, if the user selects a button on a webpage, you might want to respond to that action by displaying an information box. in this article, we discuss some important concepts surrounding events, and look at how they work in browsers. this won't be an exhaustive study; just what you need to know at this stage. prerequisites: basic computer literacy, a basic understanding of html and css, javascript first steps. ...
...pts surrounding events, and look at how they work in browsers. this won't be an exhaustive study; just what you need to know at this stage. prerequisites: basic computer literacy, a basic understanding of html and css, javascript first steps. objective: to understand the fundamental theory of events, how they work in browsers, and how events may differ in different programming environments. a series of fortunate events as mentioned above, events are actions or occurrences that happen in the system you are programming — the system produces (or "fires") a signal of some kind when an event occurs, and provides a mechanism by which an action can be automatically taken (that is, some code running) when the event occurs. for example, in an airport, when the runway...
...n anonymous function containing code that generates a random rgb color and sets the <body> background-color equal to it. this code is run whenever the click event fires on the <button> element, that is, whenever a user selects it. the example output is as follows: it's not just web pages another thing worth mentioning at this point is that events are not unique to javascript — most programming languages have some kind of event model, and the way the model works often differs from javascript's way. in fact, the event model in javascript for web pages differs from the event model for javascript as it is used in other environments. for example, node.js is a very popular javascript runtime that enables developers to use javascript to build network and server-side applications. the node.j...
...And 3 more matches
Looping code - Learn web development
previous overview: building blocks next programming languages are very useful for rapidly completing repetitive tasks, from multiple basic calculations to just about any other situation where you've got a lot of similar items of work to complete. here we'll look at the loop structures available in javascript that handle such needs. prerequisites: basic computer literacy, a basic understanding of html and css, javascript first steps. objective: to understand how to use loops in javascript. keep me in the loop loops, loops, loops. as well as being associated with popular breakfast cereals, roller coasters, and musical production, they are also a critical concept in programming. ...
......
...'s consider the case of a farmer that is making sure he has enough food to feed his family for the week. he might use the following loop to achieve this: a loop usually has one or more of the following features: a counter, which is initialized with a certain value — this is the starting point of the loop ("start: i have no food", above). a condition, which is a true/false test to determine whether the loop continues to run, or stops — usually when the counter reaches a certain value. this is illustrated by "have i got enough food?", above. let's say he needs 10 portions of food to feed his family. an iterator, which generally increments the counter by a small amount on each successive loop, until the condition is no longer true. we haven't explicitly illustrated this above, but...
...And 3 more matches
Useful string methods - Learn web development
ll then need to write a conditional test of the form operand1 operator operand2. is the thing on the left equal to the thing on the right? or in this case, does the method call on the left return the result on the right? hint: in this case it is probably more useful to test whether the method call isn't equal to a certain result. ...
...e. store the result of this replace procedure in another new variable. change the value of the result variable to equal to the final result, not the input. note: a hint — the parameters of the string methods don't have to be string literals; they can also be variables, or even variables with a method being invoked on them. ...
...put</h2> <div class="output" style="min-height: 125px;"> <ul> </ul> </div> <h2>editable code</h2> <p class="a11y-label">press esc to move focus away from the code area (tab inserts a tab character).</p> <textarea id="code" class="playable-code" style="height: 250px; width: 95%"> const list = document.queryselector('.output ul'); list.innerhtml = ''; let cities = ['london', 'manchester', 'birmingham', 'liverpool']; for (let i = 0; i < cities.length; i++) { let input = cities[i]; // write your code just below here let result = input; let listitem = document.createelement('li'); listitem.textcontent = result; list.appendchild(listitem); } </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="reset"> <input id="solution" type="button" value="sh...
...And 3 more matches
Ember interactivity: Events, classes and state - Learn web development
ide javascript frameworks next at this point we'll start adding some interactivity to our app, providing the ability to add and display new todo items. 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. prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line. a deeper understanding of modern javascript features (such as classes, modules, etc), will be extremely beneficial, as ember makes heavy use of them. objective: to learn how to create component classes and use events to control inter...
...component. one component's this will be different from another component's this. we can define what is available inside this by generating a component class to go along with your component. this is a vanilla javascript class and has no special meaning to ember, other than extending from the component super-class. to create a header class to go with your header component, type this in to your terminal: ember generate component-class header this will create the following empty class file — todomvc/app/components/header.js: import component from '@glimmer/component'; export default class headercomponent extends component { } inside this file we will implement the event handler code. update the content to the following: import component from '@glimmer/component'; import { action } from...
...rapper function, which wraps and calls other functions or properties, providing additional functionality along the way. for example, the @tracked decorator (see slightly later on) runs code it is applied to, but additionally tracks it and automatically updates the app when values change. read javascript decorators: what they are and when to use them for more general information on decorators. coming back to our browser tab with the app running, we can type whatever we want, and when we hit enter we'll be greeted with an alert message telling us exactly what we typed. with the interactivity of the header input out of the way, we need a place to store todos so that other components can access them. storing todos with a service ember has built-in application-level state management that we...
...And 3 more matches
Ember app structure and componentization - Learn web development
previous overview: client-side javascript frameworks next in this article we'll get right on with planning out the structure of our todomvc ember app, adding in the html for it, and then breaking that html structure into components. prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line. a deeper understanding of modern javascript features (such as classes, modules, etc), will be extremely beneficial, as ember makes heavy use of them. objective: to learn how to structure an ember app, and then break that structure into components. planning out the layout of the todomvc app in the last article we set up a new ember proje...
...than it being inside the "main" section. 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. let’s create the header component first. ...
...onents 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. let’s create the header component first. to do so: stop the server running by going to the terminal and pressing ctrl + c. ...
...And 3 more matches
Getting started with React - Learn web development
next in this article we will say hello to react. we'll discover a little bit of detail about its background and use cases, set up a basic react toolchain on our local computer, and create and play with a simple starter app — learning a bit about how react works in the process. prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. react uses an html-in-javascript syntax called jsx (javascript and xml). familiarity with both html and javascript will help you to learn jsx, and better identify whether bugs in your application are related to javascript or to the more specific domain of react. objective: to set up a local react development environment, create a start app, and understand the ...
...y applications; and there are other possibilities besides. to build for the web, developers use react in tandem with reactdom. react and reactdom are often discussed in the same spaces as — and utilized to solve the same problems as — other true web development frameworks. when we refer to react as a "framework", we’re working with that colloquial understanding. react's primary goal is to minimize the bugs that occur when developers are building uis. it does this through the use of components — self-contained, logical pieces of code that describe a portion of the user interface. these components can be composed together to create a full ui, and react abstracts away much of the rendering work, leaving you to concentrate on the ui design. use cases unlike the other frameworks covere...
...m support (lts) version. node includes npm (the node package manager), and npx (the node package runner). you may also use the yarn package manager as an alternative, but we'll assume you are using npm in this set of tutorials. see package management basics for more information on npm and yarn. ...
...And 3 more matches
Starting our Svelte Todo list app - Learn web development
g everything ready to start developing our to-do list app features, which we'll go on to in subsequent articles. we want our users to be able to browse, add and delete tasks, and also to mark them as complete. this will be the basic functionality that we'll be developing in this tutorial series, plus we'll look at some more advanced concepts along the way too. prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line. you'll need a terminal with node + npm installed to compile and build your app. objective: to learn how to create a svelte component, render it inside another component, pass data into it using props, and save its state. code ...
...group"> <label for="todo-1" class="todo-label"> new name for 'create a svelte starter app' </label> <input type="text" id="todo-1" autocomplete="off" class="todo-text" /> </div> <div class="btn-group"> <button class="btn todo-cancel" type="button"> cancel <span class="visually-hidden">renaming create a svelte starter app</span> </button> <button class="btn btn__primary todo-edit" type="submit"> save <span class="visually-hidden">new name for create a svelte starter app</span> </button> </div> </form> </div> </li> <!-- todo-2 --> <li class="todo"> <div class="stack-small"> ...
...ocus-inner { border: 0; } button, input, optgroup, select, textarea { font-family: inherit; font-size: 100%; line-height: 1.15; margin: 0; } button, input { overflow: visible; } input[type="text"] { border-radius: 0; } body { width: 100%; max-width: 68rem; margin: 0 auto; font: 1.6rem/1.25 arial, sans-serif; background-color: #f5f5f5; color: #4d4d4d; } @media screen and (min-width: 620px) { body { font-size: 1.9rem; line-height: 1.31579; } } /*end resets*/ /* global styles */ .form-group > input[type="text"] { display: inline-block; margin-top: 0.4rem; } .btn { padding: 0.8rem 1rem 0.7rem; border: 0.2rem solid #4d4d4d; cursor: pointer; text-transform: capitalize; } .btn.toggle-btn { border-width: 1px; border-color: #d3d3d3; } .btn.toggle-...
...And 3 more matches
Getting started with Vue - Learn web development
ks. in this article we'll look at a little bit of vue background, learn how to install it and create a new project, study the high-level structure of the whole project and an individual component, see how to run the project locally, and get it prepared to start building our example. prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. vue components are written as a combination of javascript objects that manage the app's data and an html-based template syntax that maps to the underlying dom structure. for installation, and to use some of the more advanced features of vue (like single file components or render functions), you'll need a terminal with node + npm installed. objective: to setup ...
...rating an existing project using a library like jquery to vue. with this method, you can use a lot of the core features of vue, such as the attributes, custom components, and data-management. development script (unoptimized, but includes console warnings. great for development <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> production script (optimized version, minimal console warnings. it is recommended that you specify a version number when including vue on your site so that any framework updates do not break your live site without you knowing.) <script src="/static/external/29/29296ccacaa9ed35ed168fc51e36f54fd6f8db9c7786bbf38cc59a27229ba5c2.svg"></script> however, this approach has some limitations. to build more complex apps, you’ll want to use...
...ures of vue and take advantage of bundlers like webpack. to make building apps with vue easier, there is a cli to streamline the development process. to use the npm package & the cli you will need: node.js 8.11+ installed. npm or yarn. note: if you don't have the above installed, find out more about installing npm and node.js here. to install the cli, run the following command in your terminal: npm install --global @vue/cli or if you'd prefer to use yarn: yarn global add @vue/cli once installed, to initialize a new project you can then open a terminal in the directory you want to create the project in, and run vue create <project-name>. the cli will then give you a list of project configurations you can use. there are a few preset ones, and you can make your own. these options le...
...And 3 more matches
Strategies for carrying out testing - Learn web development
re statcounter these are both very north america-centric, and not particularly accurate, but they can give you an idea of broad trends. for example, let's go to netmarketshare. you can see that opera is listed as having small but visible usage figures, so we should add it to our support chart too as grade c. ie8 is listed as being significant too, but it is older and no longer capable. opera mini is also significant, but it isn't very capable in terms of running complex javascript at runtime, etc (see opera mini and javascript for more details). we should put this into grade b as well. 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 browser...
...ur final support chart will end up looking like so: a grade: chrome and firefox for windows/mac, safari for mac, edge and ie for windows (last two versions of each), ios safari for iphone/ipad, android stock browser (last two versions) on phone/tablet, chrome and firefox for android (last two versions) on phone tablet. accessibility passing common tests. b grade: ie 8 and 9 for windows, opera mini. c grade: opera, other niche modern browsers. what are you going to test? when you've got a new addition to your codebase that needs testing, before you start testing you should write out a list of testing requirements that need to pass to be accepted. these requirements can be visual or functional — both combine to make a usable web site feature. consider the following example (see the s...
...ions (see implementing feature detection, later on in the course). you might also notice that the button isn't usable using only the keyboard — this also needs to be remedied. maybe we could use some javascript to implement a keyboard control for the toggle, or use some other method entirely? these test criteria are useful, because: they give you a set of steps to follow when you are performing tests. they can be easily turned into sets of instructions for user groups to follow when carrying out tests (e.g. "try to active the button using your mouse, and then the keyboard...") — see user testing, below. they can also provide a basis for writing automated tests. it is easier to write such tests if you know exactly what you want to test, and what the success conditions are (see using...
...And 3 more matches
Setting up your own test automation environment - Learn web development
ays, but the best way to use selenium is via webdriver, a powerful api that builds on top of selenium and makes calls to a browser to automate it, carrying out actions such as "open this web page", "move over this element on the page", "click this link", "see whether the link opens this url", etc. this is ideal for running automated tests. how you install and use webdriver depends on what programming environment you want to use to write and run your tests. 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. see setting up a selenium-webdriver project for more details of selenium setups for different languages. diffe...
...n your .bash_profile (or .bashrc) file (if you can't see hidden files, you'll need to display them, see show/hide hidden files in mac os x or show hidden folders in ubuntu). paste the following into the bottom of your file (updating the path as it actually is on your machine): #add webdriver browser drivers to path export path=$path:/users/bob save and close this file, then restart your terminal/command prompt to reapply your bash configuration. check that your new paths are in the path variable by entering the following into your terminal: echo $path you should see it printed out in the terminal. to set your path variable on windows, follow the instructions at how can i add a new folder to my system path? ok, let's try a quick test to make sure everything is working. creat...
...webdriver will then wait for 2 seconds; the document title is then accessed, and if it is "webdr...
...And 3 more matches
Learn web development
in coding, you'll want to move on to javascript or server-side development. begin with our javascript first steps and server-side first steps modules. ...
...ascript or server-side development. begin with our javascript first steps and server-side first steps modules. frameworks and tooling: after mastering the essentials of vanilla html, css, and javascript, you should learn about client-side web development tools, and then consider digging into client-side javascript frameworks, and server-side website programming. note: our glossary provides terminology definitions. ...
...you should learn about client-side web development tools, and then consider digging into client-side javascript frameworks, and server-side website programming. note: our glossary provides terminology definitions. besides, if you have a specific question about web development, our common questions section may have something to help you. random glossary entry semantics in programming, semantics refers to the meaning of a piece of code — for example "what effect does running that line of javascript have?", or "what purpose or role does that html element have" (rather than "what does it look like?".) topics covered the following is a list of all the topics we cover in the mdn learning area. getting started with the web provides a practical introduction to web devel...
...And 3 more matches
Accessibility/LiveRegionDevGuide
learn about aria live region markup and the live region api support document for the latest firefox api with regards to live regions. as always, we're open to questions and suggestions for changes in community forums. priority queue the heart of any live region support module is the priority queue. it is responsible for queuing messages derived from live region events, where priority is determined by chronological order and the live politeness properties. in addition to the standard priority queue methods, additional methods will need to be implemented that purge the queue based on one of the priority criterion. the "purge by timestamp" method will be used to remove old messages that are no longer deemed relevant while "purge by politeness" is used to satisfy the aria live politeness sp...
...n iaccessible2, iaccessibletext::get_oldtext and iaccessibletext::get_newtext are used to acquire the text and offsets. filtering events text changed events certain web page mutation events, such as adding to a list, trigger both an object changed and a text changed event. both events should not be acted upon or double announcements would result. instead, all text changed events should be examined for the presence of an embed character. if one is present, the text changed event should be discarded because an object changed event will follow. filtering user actions this paragraph describes object properties and event naming schemes that are used to help an at determine if an event is an actual live region event or is the result of user action. filtering for performance the most sig...
...operties and event naming schemes that are used to help an at determine if an event is an actual live region event or is the result of user action. filtering for performance the most significant difference between at-spi and iaccessible2 is that at-spi is an inter-process communication service while iaccessible2 runs in process. as a result, care must be taken in an at-spi based application to minimize performance degradation by only acting on events that are truly live regions. these "non-live" events may be events originating from the chrome, user interaction in the chrome or document, document loading events, or real live region events from hidden tabs. with the goal of eliminating the "non-live" events, some sort of event filtering logic must be employed. the following is a list of pot...
...And 3 more matches
Software accessibility: Where are we today?
s seen drastic improvements over the past two decades. this article reviews the progress and technology as it has developed. where are we today? up until this point, the largest driving force behind desktop computing environments has been microsoft, first with ms dos, followed by variants of microsoft windows. these operating systems were not designed with the needs of people with disabilities in mind. many, including those who were blind or physically disabled, were unable to use applications which were written for microsoft operating systems. these applications assumed that computer users could: read and react to text and images displayed on the screen. type on a standard keyboard. select text, pictures, and other information using a mouse react to sounds played. this tends to be s...
...ogy could be useful to mainstream users, on portable information appliances, or to access information when the eyes are busy elsewhere. magnification enlarges the screen's contents: for those with low vision, it may suffice to use a larger font, a built-in high contrast theme, or even just an an extra large screen. otherwise, screen magnification programs may be used, which allow zooming in to portions of the screen, while following the mouse or the current focus. screen magnifiers also have some built-in text-to-speech and the ability to filter text and images through various color palettes, such as black on yellow for high contrast, or green on blue for low contrast. the optacon provides access to printed words, graphics and on-screen information by means of an a...
...to-speech and the ability to filter text and images through various color palettes, such as black on yellow for high contrast, or green on blue for low contrast. the optacon provides access to printed words, graphics and on-screen information by means of an array vibrating pins the size of an index finger. the user uses one hand to read the vibrating pins, and the other hand moves a mini-camera over the material to be read. unfortunately, the unit is not currently produced, although there is occasional talk of resurrecting this useful device. braille a solution used for quiet reading, for detailed work, and by deaf-blind users. this can come in the form of hard copy braille printed on braille embossers, or from a refreshable braille display (see below). these techn...
...And 3 more matches
What to do and what not to do in Bugzilla
bugs: leave comments with the information you'd like to be able to edit into the bug, and that will help you get the editbugs permissions quickly. canconfirm privilege the canconfirm privilege allows you to confirm bugs and also to start your bug reports in the confirmed state (new). it also governs which bug entry form you are presented with first (either the guided or advanced forms). confirming unconfirmed bugs a useful general guide for confirming unconfirmed bugs. a guide for confirming layout bugs (bugs in web page rendering) reporting new bugs you should report a bug in the new state after going through the triaging process as described in the two above-mentioned guides. you should look at all the open bugs you've reported (see the "my bugs" link at the bottom of every bugz...
... we have to work around and bugs that involve certain core gecko modules. bugs covered by this exception should not be invalidated by anyone other than the module owner or module peer; for bugs involving modules like layout or content, attach a test case to the bug and then cc one of the owners or peers. reports of problems with specific websites that result from bad coding practices already determined to be “tech evangelism” cases by the module owner or peer, or problems that result from the use of proprietary technology, should be be moved to the tech evangelism product rather than being resolved as invalid. resolving bugs as fixed resolve a bug as fixed if the bug has been fixed by a checkin into the mozilla mercurial code repository. bugs which can no longer be reproduced should be ...
...another hardware platform like mac or dec is also affected, change hardware to all. severity this field describes the impact of a bug. ...
...And 3 more matches
Command line options
ral, the syntax is as follows: application -option -option "argument" -option argument examples the following examples show the use of the "-profilemanager" command, which will open the profile manager prior to starting firefox or thunderbird: windows select run from windows start menu. enter the following command: firefox -profilemanager mac os x go to applications > utilities. ...
...indows select run from windows start menu. enter the following command: firefox -profilemanager mac os x go to applications > utilities. open terminal and enter the following command: cd /applications/firefox.app/contents/macos ./firefox -profilemanager if you use firefox nightly, you can enter: cd /applications/firefoxnightly.app/contents/macos ./firefox -profilemanager linux open terminal and enter the following command: cd thunderbird installation directory ./thunderbird -profilemanager the example above invokes the "-profilemanager" command line option with mozilla's thunderbird mail client. user profile -allow-downgrade firefox 67's downgrade protection prevents accidentally starting firefox in a profile running a later version of firefox. depending on changes between t...
...er ubuntu for firefox 20 and later, confirmed to work in 14.04. -private-window opens a new private browsing window in an existing instance of firefox. firefox 20 and later only. -private-window url open url in a new private browsing window. if a private browsing window is already open, a new tab is opened in the existing window. firefox 29 and later only. does not work in firefox 31 on linux mint 17 nor on firefox 48 on windows 7. url opens in a non-private window. -search term search term with your default search engine. firefox and seamonkey 2.1 and later only. -setdefaultbrowser set the application as the default browser. firefox only. -url url open url in a new tab or window, depend on the browser option. -url can be omitted. you may list multiple urls, separated by spaces. fir...
...And 3 more matches
Eclipse CDT Manual Setup
, silenced, or that fails to identify the directory that the compiler is being run from, then it will mess up the compiler options that eclipse associates with your files, and that in turn will significantly degrade the quality of the code assistance that eclipse will provide after it next re-indexes the code. these requirements aren't a very good fit with the typical mozilla developer's wish to minimize build times, implying parallelized, silenced builds. the consequences of the above observations are this: it is strongly recommended that you invoke your normal (re)builds from the command line, externally of eclipse. below we will configure eclipse's build step so that you use it only occasionally to manually trigger a special "build" (actually a fast script that fakes a build) purely...
...e)builds from the command line, externally of eclipse. below we will configure eclipse's build step so that you use it only occasionally to manually trigger a special "build" (actually a fast script that fakes a build) purely for the purposes of setting/updating the compiler options that eclipse associates with each source file. (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. see the building from eclipse section below if you're interested in what you lose. if you're interested in future improvements to eclipse that would allow parallel builds to be run from inside eclipse while still allowing it to obtain the compiler options, see the faq isn't there a better meth...
...ssing a build log from a full, clean build made using -j1 -w. since such a non-parallel, full build would take a very long time, we're going to cheat and set eclipse's "build" action to run jwatt's just-print-mozilla-build.py script instead. this script will complete in about 30 seconds on a warm tree (files cached in ram) if your object directory is up to date, although eclipse will take several minutes to process the "build output" that it produces. download just-print-mozilla-build.py and change its permissions to make it executable ('chmod a+x just-print-mozilla-build.py'). if you don't put just-print-mozilla-build.py somewhere in your path, then go back to the initial project properties section where you set just-print-mozilla-build.py and specify its absolute path instead of just its ...
...And 3 more matches
Multiple Firefox profiles
available browser development channels there are four available browser channels, each at a different level of stability and development. the four channels are release, beta, developer edition, and nightly. the release channel is recommended for most users, as it is the "official release" channel. however, for those more adventurous, you can try one of the other three channels to see what is coming in firefox and play around with emerging features. the beta channel contains the features that are expected to be in the next release of firefox and are in final stages of testing. aurora contains experimental features, which are not yet at beta quality. nightly contains the latest code from firefox developers and is the least stable channel. third-party tools in addition to the built-in profi...
...om firefox developers and is the least stable channel. third-party tools in addition to the built-in profile manager and the external profile manager, there are a few third-party tools that make working with multiple profiles easy. this list is by no means exhaustive. please add any helpful tools you discover to the list! mac os x multifirefox by dave martorana profile management determining the profile while firefox is running to determine the profile of a currently-running firefox instance in windows, macos or linux, type about:profiles into the browser url search bar. the page presents a list of all of your profiles, each beginning with "profile: " followed by its name. the one being run by this firefox instance will include the bold text "this is the profile in use" for ...
...efox instance will include the bold text "this is the profile in use" for example, if you find that text beneath the entry for "profile: suzie", then you are running in a profile named suzie. launching firefox into a desired profile although it is possible in some cases to have multiple instances of firefox running in different profiles, to avoid confusion, you might want to first exit/quit/terminate all running instances of firefox, firefox developer edition or nightly. then follow the instructions below, applicable to your operating system. from profile manager inside firefox if you already have firefox instance running, you can open another profile from the integrated profile manager on any platform: type about:profiles into the browser url search bar. find the profile you want to...
...And 3 more matches
Performance best practices for Firefox front-end engineers
avoid the main thread where possible the main thread is where we process user events and do painting. it's also important to note that most of our javascript runs on the main thread, so it's easy for script to cause delays in event processing or painting. ...
...te line 2 though - we’re asking for the height of some dom node. this means that gecko needs to synchronously calculate layout (and styles) using an uninterruptible reflow in order to answer the question that javascript is asking (“what is the clientheight of div1?”). it’s possible for our example to avoid this synchronous, uninterruptible reflow by moving lines 2 and 4 above line 1. assuming there weren’t any style changes requiring size or position recalculation above line 1, the clientheight information should be cached since the last reflow, and will not result in a new layout calculation. if you can avoid querying for the size or position of things in javascript, that’s the safest option—especially because it’s always possible that something earlier in this tick of java...
...ing for web content by setting nglayout.debug.paint_flashing to true. after enabling these, exercise your function and see what’s painting. see a lot of flashing / colors? that means a lot of painting is going on. the worst case is called over-painting. this is when you draw multiple times over the same space. unless transparency is involved, all but the last painting will be overwritten, becoming unnecessary. if you can find ways to avoid doing this, you can save substantial time. keep in mind that painting occurs on the main thread. remember, too, that the goal is to have as little happen on the main thread as possible. that means that finding and removing (when possible) over-painting is a good place to start reducing your burden on the main thread, which will in turn improve performa...
...And 3 more matches
HTML parser threading
nizer calls into the tree builder which outputs nshtml5treeoperation objects (tree ops) into a queue. each tree op represents a small operation, such as element creation or appending a node into another, that can later be performed on the main thread. note that mtokenizermutex is being held by the parser thread for the entire time that the tokenizer runs. parseavailabledata() checks for parser termination or interruption from time to time. the termination and interruption indicators are guarded by a more narrowly scoped mterminatedmutex, so parseavailabledata() has the opportunity to receive an order to terminate or interrupt even while the parser thread is holding mterminatedmutex. the tree op queue is flushed to the main thread from time to time. there's a timer that calls timerflush() (whi...
...l5treeoperation. hence, data gets copied to and from these arrays. executing tree ops when the executor flushing runnable fires on the main thread, it calls nshtml5treeopexecutor::runflushloop(). this method returns immediately if another invocation of it is already on the call stack (nested event loop case). the method then enters a loop that has a bunch of return conditions (including parser termination). the loop first flushes speculative loads (creation discussed later). if the executor is reading from a stage (i.e. the ops are coming from the parser thread), the executor moves the tree ops from the staging queue into its own queue. (again, here we get to move a bunch of tree ops by obtaining a mutex once instead of having to synchronize thread on a per-tree op basis.) if the executor isn...
...a bunch of tree ops by obtaining a mutex once instead of having to synchronize thread on a per-tree op basis.) if the executor isn't reading from a stage, it calls nshtml5parser::parseuntilblocked() to parse potential document.write()-generated data into tree ops. the outer loop then has an inner loop that iterates over the tree ops in the executor's queue and calls perform on each one. parser termination is checked before each tree op for an early return, because, unfortunately, gecko expects parsers to be able to terminate immediately. after each tree op except the last one in the queue, the clock time is checked to see if runflushloop() has spent too much time without returning to the event loop. if too much time has been spent, a runnable for calling runflushloop() again is dispatched and...
...And 3 more matches
HTTP Cache
the entry again as "new", the cycle repeats. this applies in general, writers throwing away the cache entry means a failure to write the cache entry and a new writer is being looked for again, the cache entry remains empty (a.k.a. "new"). the writer stored all necessary meta data in the cache entry and called metadataready on it: other consumers now get the entry and may examine and potentially modify the meta data and read the data (if any) of the cache entry. when the writer has data (i.e. the response payload) to write to the cache entry, it must open the output stream on it before it calls metadataready. when the writer still keeps the cache entry and has open and keeps open the output stream on it, other consumers may open input streams on the entry. the d...
... when the writer is interrupted, the first concurrent reader in line does a range request for the rest of the data - and becomes that way a new writer. the rest of the readers are still concurrently reading the content since output stream for the cache entry is again open and kept by the current writer. lifetime of an existing entry with only a partial content such a cache entry is first examined in the nsicacheentryopencallback.oncacheentrycheck callback, where it has to be checked for completeness. in this case, the content-length (or different indicator) header doesn't equal to the data size reported by the cache entry. the consumer then indicates the cache entry needs to be revalidated by returning entry_needs_revalidation from oncacheentrycheck. this consumer, from the point of ...
...erver and attempt to load the rest of the data. when the server responds positively (in case of an http server with a 206 response code) the writer (in this order) opens the output stream on the cache entry and calls setvalid to unblock other pending openers. concurrent read/write is engaged. lifetime of an existing entry that doesn't pass server revalidation such a cache entry is first examined in the nsicacheentryopencallback.oncacheentrycheck callback, where the consumer finds out it must be revalidated with the server before use. the consumer then indicates the cache entry needs to be revalidated by returning entry_needs_revalidation from oncacheentrycheck. this consumer, from the point of view the cache, takes a role of the writer. other parallel consumers, if any, are blocked ...
...And 3 more matches
Investigating leaks using DMD heap scan mode
e release that causes the leaked object to go away. prerequisites a debug dmd build of firefox. this page describes how to do that. this should probably be an optimized build. non-optimized dmd builds will generate better stack traces, but they can be so slow as to be useless. the build is going to be very slow, so you may need to disable some shutdown checks. first, in toolkit/components/terminator/nsterminator.cpp, delete everything in runwatchdog but the call to ns_setcurrentthreadname. this will keep the watch dog from killing the browser when shut down takes multiple minutes. secondly, you may need to comment out the call to moz_crash("nss_shutdown failed"); in xpcom/build/xpcominit.cpp, as this also seems to trigger when shutdown is extremely slow. you need the cycle collector ana...
...aster. the allowed values here are the same as those returned by xre_getprocesstype(), so adjust as needed. finally, the --dmd option need to be passed in so that dmd will be run. --mode=scan is needed so that when we get a dmd log the entire contents of each block of memory is saved for later analysis. with that command line in hand, you can start firefox. be aware that this may take multiple minutes if you have optimization disabled. once it has started, go through the steps you need to reproduce your leak. if your leak is a ghost window, it can be handy to get an about:memory report and write down the pid of the leaking process. you may want to wait 10 or so seconds after this to make sure as much as possible is cleaned up. next, exit the browser. this will cause a lot of logs to be w...
...ce some output. you'll want to save a copy of this output for later. the output will look something like this, after a message about loading progress: 0x7f0882fe3230 [fragmentorelement (xhtml) script https://www.example.com] --[[via hash] mlistenermanager]--> 0x7f0899b4e550 [eventlistenermanager] --[mlisteners event=onload listenertype=3 [i]]--> 0x7f0882ff8f80 [callbackobject] --[mincumbentglobal]--> 0x7f0897082c00 [nsglobalwindowinner # 2147483662 inner https://www.example.com] root 0x7f0882fe3230 is a ref counted object with 1 unknown edge(s). known edges: 0x7f08975a24c0 [fragmentorelement (xhtml) head https://www.example.com] --[mattrsandchildren[i]]--> 0x7f0882fe3230 0x7f08967e7b20 [js object (htmlscriptelement)] --[unwrapdomobject(obj)]--> 0x7f088...
...And 3 more matches
NSS 3.19.1 release notes
in the "bugs fixed" section below. distribution information the hg tag is nss_3_19_1_rtm. nss 3.19.1 requires nspr 4.10.8 or newer. nss 3.19.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_19_1_rtm/src/ security fixes in nss 3.19.1 bug 1138554 / cve-2015-4000 - the minimum strength of keys that libssl will accept for finite field algorithms (rsa, diffie-hellman, and dsa) have been increased to 1023 bits. new in nss 3.19.1 new functionality no new functionality is introduced in this release. this patch release includes a fix for the recently published logjam attack. notable changes in nss 3.19.1 nss reports the bit length of keys more accurately. thus, ...
...se. this patch release includes a fix for the recently published logjam attack. notable changes in nss 3.19.1 nss reports the bit length of keys more accurately. thus, the seckey_publickeystrength and seckey_publickeystrengthinbits functions could report smaller values for values that have leading zero values. this affects the key strength values that are reported by ssl_getchannelinfo. ...
...e changes in nss 3.19.1 nss reports the bit length of keys more accurately. thus, the seckey_publickeystrength and seckey_publickeystrengthinbits functions could report smaller values for values that have leading zero values. this affects the key strength values that are reported by ssl_getchannelinfo. ...
...And 3 more matches
NSS tools : certutil
e specify a file that will automatically supply the password to include in a certificate or to access a certificate database. this is a plain-text file containing one password. be sure to prevent unauthorized access to this file. -g keysize set a key size to use when generating new public and private key pairs. the minimum is 512 bits and the maximum is 16384 bits. the default is 2048 bits. any size between the minimum and maximum is allowed. -h tokenname specify the name of a token to use or act on. unless specified otherwise the default token is an internal slot. -i input_file pass an input file to the command. depending on the ...
... setting a value of -2 would subtract 2 from the default and create a validity period of one month. -w offset-months set an offset from the current system time, in months, for the beginning of a certificate's validity period. use when creating the certificate or adding it to a database. express the offset in integers, using a minus sign (-) to indicate a negative offset. if this argument is not used, the validity period begins at the current system time. the length of the validity period is set with the -v argument. -x force the key and certificate database to open in read-write mode. this is used with the -u and -l command options. -...
...ey for the database, instead of the default value of 65537. the available alternate values are 3 and 17. -z noise-file read a seed value from the specified file to generate a new private and public key pair. this argument makes it possible to use hardware-generated seed values or manually create a value from the keyboard. the minimum file size is 20 bytes. -0 sso_password set a site security officer password on a token. -1 | --keyusage keyword,keyword set a netscape certificate type extension in the certificate. there are several available keywords: + digital signature + nonrepudiation + keyencipherment + dataencipherment...
...And 3 more matches
sslintro.html
rs chosen by user preference. optional. initializing caches ssl peers frequently reconnect after a relatively short time has passed. to avoid the overhead of repeating the full ssl handshake in situations like this, the ssl protocol supports the use of a session cache, which retains information about each connection, such as the master secret generated during the ssl handshake, for a predetermined length of time. if ssl can locate the information about a previous connection in the local session cache, it can reestablish the connection much more quickly than it can without the connection information. by default, ssl allocates one session cache. this default cache is called the client session id cache, (also known as the client session cache, or simply the client cache). the client cache ...
...e the new ssl socket with the same configuration state as the model. it is also possible for an application to import a socket into ssl after the tcp connection on that socket has already been established. in this case, initial configuration takes place in the same way: pass the existing nspr file descriptor to ssl_importfd and perform any additional configuration that has not already been determined by the model file descriptor. configuration functions control the configuration of an individual socket. pr_getsocketoption. retrieves the socket options currently set for a specified socket. optional. pr_setsocketoption. sets the socket options for a specified socket., including making it blocking or nonblocking. optional. ssl_optionset. sets a single configuration parameter of a s...
...son with the url specified by the server certificate. required for clients. callbacks and helper functions allow you to specify such things as how authentication is accomplished and what happens if it fails. ssl_setpkcs11pinarg. sets the argument passed to the pkcs #11 password callback function. required. ssl_authcertificatehook. specifies a callback function used to authenticate an incoming certificate (optional for servers, necessary for clients to avoid "man-in-the-middle" attacks). optional. if not specified, ssl uses the default callback function, ssl_authcertificate. ssl_badcerthook. specifies a callback function to deal with a situation where authentication has failed. optional. ssl_getclientauthdatahook. specifies a callback function for ssl to use when the server asks...
...And 3 more matches
certutil
assword-file specify a file that will automatically supply the password to include in a certificate or to access a certificate database. this is a plain-text file containing one password. be sure to prevent unauthorized access to this file. -g keysize set a key size to use when generating new public and private key pairs. the minimum is 512 bits and the maximum is 8192 bits. the default is 1024 bits. any size between the minimum and maximum is allowed. -h tokenname specify the name of a token to use or act on. unless specified otherwise the default token is an internal slot (specifically, internal slot 2). this slot can also be explicitly named with the ...
... example, setting a value of -2 would subtract 2 from the default and create a validity period of one month. -w offset-months set an offset from the current system time, in months, for the beginning of a certificate's validity period. use when creating the certificate or adding it to a database. express the offset in integers, using a minus sign (-) to indicate a negative offset. if this argument is not used, the validity period begins at the current system time. the length of the validity period is set with the -v argument. -x force the key and certificate database to open in read-write mode. this is used with the -u and -l command options. -x use certuti...
... public key for the database, instead of the default value of 65537. the available alternate values are 3 and 17. -z noise-file read a seed value from the specified file to generate a new private and public key pair. this argument makes it possible to use hardware-generated seed values or manually create a value from the keyboard. the minimum file size is 20 bytes. -0 sso_password set a site security officer password on a token. -1 | --keyusage keyword,keyword set a netscape certificate type extension in the certificate. there are several available keywords: o digital signature o nonrepudiation o keyencipherment o dataenciphermen...
...And 3 more matches
Secure Development Guidelines
a/b : 0; } writing secure code: memory management string handling c-style strings are byte arrays that end with a \0 byte some string handling functions won’t perform any kind of length checking, so don’t use them ensu...
... bbv: stack overflow example: void foo(char *bar) { char c[12]; strcpy(c, bar); } int main(int argc, char **argv) { foo(argv[1]); } bbv: stack overflow before th...
... lock(lockb); lock(locka); ... do something ... ...
...And 3 more matches
mozIThirdPartyUtil
netwerk/base/public/mozithirdpartyutil.idlscriptable utility functions for determining whether a given uri, channel, or window hierarchy is third party with respect to a known uri. 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview boolean isthirdpartychannel(in nsichannel achannel, [optional] in nsiuri auri); boolean isthirdpartyuri(in nsiuri afirsturi, in nsiuri aseconduri); boolean isthirdpartywindow(in nsidomwindow awindow, [optional] in nsiuri auri); methods isthirdpartychannel() determine whether the given channel and its content window hierarchy is third party. this is done as follows: if achannel is an nsihttpchannel and has the 'forceallowthirdpart...
...if so, return. ...
...if so, return. obtain the bottommost nsidomwindow, and its same-type parent if it exists, from the channel's notification callbacks. then: if the parent is the same as the bottommost window, and the channel has the load_document_uri flag set, return false. ...
...And 3 more matches
nsIIOService
inherits from: nsisupports last changed in gecko 1.2 this interface duplicates many of the nsiprotocolhandler methods in a protocol handler independent way (for example newuri() inspects the scheme in order to delegate creation of the new uri to the appropriate protocol handler). ...
...absolute url, this parameter is ignored. aloadingnode the loadingdocument of the channel. this is the document/element that will get access to the result of this request. for example for an image load, it's the document in which the image will be loaded. and for a css stylesheet it's the document whose rendering will be affected by the stylesheet. if possible, pass in the element which is performing the load. but if the load is coming from a js api (such as xmlhttprequest) or if the load might be coalesced across multiple elements (such as for ) then pass in the document node instead. for loads that are not related to any document, such as loads coming from addons or internal browser features, use null here. aloadingprincipal the loadingprincipal of the channel. the principal of the docum...
...nsiuri auri, in nsidomnode aloadingnode, in nsiprincipal aloadingprincipal, in nsiprincipal atriggeringprincipal, in unsigned long asecurityflags, in unsigned long acontentpolicytype ); please note, if you provide both a loadingnode and a loadingprincipal, then loadingprincipal must be equal to loadingnode->nodeprincipal(). but less error prone is to just supply a loadingnode. keep in mind that uris coming from a webpage should never use the systemprincipal as the loadingprincipal. parameters auri an nsiuri from which to make a channel. aloadingnode the loadingdocument of the channel. the element or document where the result of this request will be used. this is the document/element that will get access to the result of this request. for example for an image load, it's the...
...And 3 more matches
nsIScreen
read only. pixeldepth long the screen's pixel depth; this is the number of bits used to represent a ...
...read only. pixeldepth long the screen's pixel depth; this is the number of bits used to represent a pixel. read only. rotation unsigned long the screen's ...
... getrect() returns a rectangle indicating the entire screen's coordinate space. void getrect( out long left, out long top, out long width, out long height ); parameters left the left edge of the screen's rectangle. top the top edge of the screen's rectangle. width the width of the screen's rectangle. height the height edge of the screen's rectangle. ...
...And 3 more matches
nsIXULTemplateQueryProcessor
ntax is opaque to the template builder and defined by a query processor. the query is expected to consist of either text or dom nodes that, when executed by a call to the generateresults() method, will allow the generation of a list of results. ...
...some queries may not need the reference variable if the syntax or the form of the data implies the value. for instance, a datasource that holds a table that can only produce one set of results. ...
...a result, outside of those defined within the query. these bindings are always optional, in that they will never affect the results generated. this function will never be called after generateresults(). any bindings that were added should be applied to each result when the result's rulematched method is called, since the bindings are different for each rule. the reference aref may be used to determine the reference when calculating the value for the binding, for example when a value should depend on the value of another variable. the syntax of the expression aexpr is defined by the query processor. if the syntax is invalid, the binding should be ignored. only fatal errors should be thrown, or ns_error_unexpected if generateresults() has already been called. as an example, if the reference are...
...And 3 more matches
Xptcall Porting Guide
pieces of functionality: invoke and stubs... the invoke functionality requires the implementation of the following on each platform (from xptcall/public/xptcall.h): xptc_public_api(nsresult) ns_invokebyindex(nsisupports* that, pruint32 methodindex, pruint32 paramcount, nsxptcvariant* params); calling code is expected to supply an array of nsxptcvariant structs. these are discriminated unions describing the type and value of each parameter of the target function. the platform specific code then builds a call frame and invokes the method indicated by the index methodindex on the xpcom interface that. here are examples of this implementation for win32 and linux x86, netbsd x86, and freebsd. these implementations use the basic strategy of: figure out how much stack space is n...
...nheritor of this class. // return a refcounted pointer to the interfaceinfo for this object // note: on some platforms this must not fail or we crash! ns_imethod getinterfaceinfo(nsiinterfaceinfo** info) = 0; // call this method and return result ns_imethod callmethod(pruint16 methodindex, const nsxptmethodinfo* info, nsxptcminivariant* params) = 0; }; code that wishes to make use of this stubs functionality (such as xpconnect) implement a class which inherits from nsxptcstubbase and implements the getinterfaceinfo and callmethod to let the platform specific code know how to get interface information and how to dispatch methods once their parameters have been pulled out of the platform specific calling frame. porters o...
...methods that fill the vtbl for this class. the idea here is that the class has a vtbl full of a large number of generic stubs. all instances of this class share that vtbl and the same stubs. the stubs forward calls to a platform specific method that uses the interface information supplied by the overridden getinterfaceinfo to extract the parameters and build an array of platform independent nsxptcminivariant structs which are in turn passed on to the overridden callmethod. the platform dependent code is responsible for doing any cleanup and returning. the stub methods are declared in xptcall/public/xptcstubsdecl.inc. these are '#included' into the declaration of nsxptcstubbase. a similar include file (xptcall/public/xptcstubsdef.inc) is expanded using platform specific macros to define the st...
...And 3 more matches
Address Book examples
address book interfaces provides an overview of the related interfaces. see an overview of thunderbird components for a general description of the thunderbird user interface and related programmatic interfaces. ...
...ectory); if (addressbook instanceof components.interfaces.nsiabdirectory) { // or nsiabitem or nsiabcollection // alert ("directory name:" + addressbook.dirname); ... } } how do i get one address book? address books are uniquely identified by a uri. this can be obtained via nsiabdirectory.uri. the code stores uris in various places (e.g. preferences, in address book trees etc). ...
... well. how do i search for multiple contacts? formulate a boolean search string (see nsiabcard for built-in property names): var searchquery = "(or(primaryemail,bw,@v)(nickname,bw,@v)(and(ismaillist,=,true)(notes,bw,@v)))"; searchquery = searchquery.replace(/@v/g, encodeuricomponent("mystr") the search queries use lisp syntax with operators enumerated in nsabquerystringtoexpression.cpp. ...
...And 3 more matches
Activity Manager examples
g a process into the activity manager const nsiap = components.interfaces.nsiactivityprocess; const nsiae = components.interfaces.nsiactivityevent; const nsiam = components.interfaces.nsiactivitymanager; let gactivitymanager = components.classes["@mozilla.org/activity-manager;1"].getservice(nsiam); let process = components.classes["@mozilla.org/activity-process;1"].createinstance(nsiap); // assuming folder is an instance of nsimsgfolder interface // localization is omitted, initiator is not provided process.init("processing folder: " + folder.prettiestname, null); // note that we don't define a custom icon, default process icon // will be used process.contexttype = "account"; // group this activity by account process.contextobj = folder.server; // account in question gac...
...ious one by providing an nsiactivitycancelhandler to allow the user to cancel the process. // step 1: create a nsiactivitycancelhandler implementation function canceljunkprocess() { // user stuff here.. } canceljunkprocess.prototype = { cancel: function(aactivity) { let initiator = aactivity.initiator; if (initiator) { let folder = aactivity.getsubjects({})[0]; .... ...
...g for given folder if (initiator.cancelfolderop(folder)) { aactivity.state = components.interfaces.nsiactivityprocess.state_canceled; gactivitymanager.removeactivity(aactivity.id); return cr.ns_success; } } return cr.ns_failure; } } // step 2: modify the previous sample to add initiator, subject // and associate a nsiactivitycancelhandler component ... // assuming that gjunkprocessor is the entity initiating the junk processing // activity, and it has cancelfolderop method that cancels the operations on folders process.init("processing folder: " + folder.prettiestname, gjunkprocessor); // folder is being filtered/processed process.addsubject(folder); process.cancelhandler = new canceljunkprocess(); ... since nsiactivitycancelhandler is pro...
...And 3 more matches
Plug-in Development Overview - Plugins
l file of that mime type, or from the server. the server looks for the mime type registered by a plug-in, based on the file extension, and starts sending the file to the browser. the browser looks up the media type, and if it finds a plug-in registered to that type, loads the plug-in software. when it starts up, the browser checks for plug-in modules for the platform and registers them. it determines which plug-ins are installed and which types they support through a combination of user preferences that are private to the browser, the contents of the plug-ins directory, or the registry on windows. a mime type is made up of a major type (such as application or image) and a minor type, for example, image/jpeg. if you define a new mime type for a plug-in, you must register it with ietf (inter...
...xtensions (mime) part two: media types" rfc-4288: "media type specifications and registration procedures" there are some variations to how plug-ins are handled on different platforms. the following sections describe platform-specific discovery and registration: ms windows unix mac os x ms windows on windows, plug-ins are found according to the section how gecko finds plug-ins. 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. but when the plug-in is loaded from a well-known directory, a different method must be used. in this case to ensure the plug-in file will be loaded, it should have a name in the form of "np*.dll". also, the...
...wser normally uses the content of the registry entries for the plug-in described below in installation using the registry. but when the plug-in is loaded from a well-known directory, a different method must be used. in this case to ensure the plug-in file will be loaded, it should have a name in the form of "np*.dll". also, the windows version information for the plug-in dll will be used to determines the mime types, file extensions, file open template, plug-in name, and description. for this the version stamp of the embedded resource of the plug-in dll should contain the following set of string/value pairs: mimetype: for mime types fileextents: for file extensions fileopenname: for file open template productname: for plug-in name filedescription: for description language: for langu...
...And 3 more matches
How to - Firefox Developer Tools
links for various how to's can be found here. these links describe in depth the how to techniques. ...
... links for various how to's can be found here. these links describe in depth the how to techniques. ...
... links for various how to's can be found here. these links describe in depth the how to techniques. ...
...And 3 more matches
Page Inspector - Firefox Developer Tools
use the page inspector to examine and modify the html and css of a page. you can examine pages loaded in the local copy of firefox or in a remote target such as firefox for android. see remote debugging to learn how to connect the developer tools to a remote target. user interface tour to find your way around the inspector, here's a quick tour of the ui. you can split the rules view out into its own pane, separate from the other tabs on the css pane — this is called 3-pane mode. ...
...arn how to connect the developer tools to a remote target. user interface tour to find your way around the inspector, here's a quick tour of the ui. you can split the rules view out into its own pane, separate from the other tabs on the css pane — this is called 3-pane mode. ...
...developer tools to a remote target. user interface tour to find your way around the inspector, here's a quick tour of the ui. you can split the rules view out into its own pane, separate from the other tabs on the css pane — this is called 3-pane mode. ...
...And 3 more matches
Basic animations - Web APIs
hr - 12 : hr; ctx.fillstyle = 'black'; /...
...otate(math.pi / 6); ctx.moveto(100, 0); ctx.lineto(120, 0); ctx.stroke(); } ctx.restore(); // minute marks ctx.save(); ctx.linewidth = 5; for (i = 0; i < 60; i++) { if (i % 5!= 0) { ctx.beginpath(); ctx.moveto(117, 0); ctx.lineto(120, 0); ctx.stroke(); } ctx.rotate(math.pi / 30); } ctx.restore(); var sec = now.getseconds(); var min = now.getminutes(); var hr = now.gethours(); hr = hr >= 12 ? ...
... (i % 5!= 0) { ctx.beginpath(); ctx.moveto(117, 0); ctx.lineto(120, 0); ctx.stroke(); } ctx.rotate(math.pi / 30); } ctx.restore(); var sec = now.getseconds(); var min = now.getminutes(); var hr = now.gethours(); hr = hr >= 12 ? ...
...And 3 more matches
HTMLFormElement - Web APIs
llows access to—and, in some cases, modification of—aspects of the form, as well as access to its component elements. ...
...s access to—and, in some cases, modification of—aspects of the form, as well as access to its component elements. ...
... you can then use any of the following syntaxes to get an individual form: document.forms[index] returns the form at the specified index into the array of forms. document.forms[id] returns the form whose id is id. document.forms[name] returns the form whose name attribute's value is name. accessing the form's elements you can access the list of the form's data-containing elements by examining the form's elements property. this returns an htmlformcontrolscollection listing all of the form's user data entry elements, both those which are descendants of the <form> and those which are made members of the form using their form attributes. you can also get the form's element by using its name attribute as a key of the form, but using elements is a better approach—it contains only the ...
...And 3 more matches
HTMLInputElement.stepDown() - Web APIs
ecified, and step defaults to the default value for step if not specified. valid on all numeric, date, and time input types that support the step attribute, includingdate, month, week, time, datetime-local, number, and range. ...
...tep attribute, includingdate, month, week, time, datetime-local, number, and range. given <input id="mytime" type="time" max="17:00" step="900" value="17:00">, invoking mytime.step(3) will change the value to 16:15, decrementing the time by 3 * 900, or 45 minutes. mytime.step(), with no parameter, would have resulted in 16:45, as n defaults to 1. ...
... <!-- decrements by intervals of 12 months (one year) --> <input type="month" max="2019-12" step="12"> the method, when invoked, changes the form control's value by the value given in the step attribute, multiplied by the parameter, within the constraints set within the form control. the default value for the parameter, if not is passed, is 1. the method will not cause the value to go below the min value set or defy the constraints set by the step attribute. a negative value for n will increment the value, but will not increment beyond the max value. if the value before invoking the stepdown() method is invalid, for example, if it doesn't match the constraints set by the step attribute, invoking the stepdown() method will return a value that does match the form controls constraints. if th...
...And 3 more matches
HTMLInputElement.stepUp() - Web APIs
ttribute, or the default step value if the step attribute is not explicitly set. the method, when invoked, increments the value by (step * n), where n defaults to 1 if not specified, and step defaults to the default value for step if not specified. ...
...nts the value by (step * n), where n defaults to 1 if not specified, and step defaults to the default value for step if not specified. ...
...ult value for step if not specified. ...
...And 3 more matches
compareVersion - Web APIs
how to package a plugin as an extension. compareversion compares the version of a file or package with the version of an existing file or package. method of installtrigger object syntax int compareversion ( string registryname, installversion version); int compareversion ( string registryname, string version); int compareversion ( string registryname, int major, int minor, int release, int build); parameters the compareversion method has the following parameters: registryname the pathname in the client version registry for the component whose version is to be compared. this parameter can be an absolute pathname, such as /royalairways/royalsw or a relative pathname, such as plugsin/royalairway/royalsw. note that the registry pathname is not the locat...
...ameter can be an absolute pathname, such as /royalairways/royalsw or a relative pathname, such as plugsin/royalairway/royalsw. note that the registry pathname is not the location of the software on the computer; it is the location of information about the software inside the client version registry. version an installversion object containing version information or a string in the format major.minor.release.build, where major, minor, release, and build are integer values representing version information. returns if the versions are the same or if software installation is not enabled, this method returns 0. if the version of registryname is smaller (earlier) than version, this method returns a negative number. otherwise, this method returns a positive number. in particular, this method r...
...his method returns 0. if the version of registryname is smaller (earlier) than version, this method returns a negative number. otherwise, this method returns a positive number. in particular, this method returns one of the following values: -5 component not present or not registered. -4 registryname has a smaller (earlier) major number than version. -3 registryname has a smaller (earlier) minor number than version. -2 registryname has a smaller (earlier) release number than version. -1 registryname has a smaller (earlier) build number than version. 0 the version numbers are the same; both objects represent the same version. 1 registryname has a larger (newer) build number than version. 2 registryname has a larger (newer) release number than version. 3 registryname has a la...
...And 3 more matches
Media Capabilities API - Web APIs
examples detect audio file support and expected performance this example defines a audio configuration then checks to see if the user agent supports decoding that media configuration, and whether it will perform well in terms of smoothness and power efficiency. ...
... examples detect audio file support and expected performance this example defines a audio configuration then checks to see if the user agent supports decoding that media configuration, and whether it will perform well in terms of smoothness and power efficiency. ...
... new media types are always being developed. with the media capabilities api, developers can ensure each user is getting the best bitrate and storage savings for their browser, device, and os capabilities. whether a device uses hardware or software decoding impacts how smooth and power efficient the video decoding is and how efficient the playback will be. the media capabilities api enables determining which codecs are supported and how performant a media file will be both in terms of smoothness and power efficiency. the media capabilities api provide more powerful features than say mediarecorder.istypesupported() or htmlmediaelement.canplaytype(), which only address general browser support, not performance. the api also provides abilities to access display property information such as sup...
...And 3 more matches
RTCPeerConnection.createOffer() - Web APIs
exclude reception (i.e. set to either "sendonly" or "inactive"). in modern implementations, the presence of this member with a value true, will ensure there is at least one transceiver set to receive audio that has not been stopped, and if there isn't one, one will be created. note: you shouldn't use this legacy property. instead, use rtcrtptransceiver to control whether or not to accept incoming audio. offertoreceivevideo optional (legacy) a legacy boolean option which used to control whether or not to offer to the remote peer the opportunity to try to send video. if this value is false, the remote peer will not be offered to send video data, even if the local side will be sending video data. if this value is true, the remote peer will be offered to send video data, even if the loca...
... exclude reception (i.e. set to either "sendonly" or "inactive"). in modern implementations, the presence of this member with a value true, will ensure there is at least one transceiver set to receive video that has not been stopped, and if there isn't one, one will be created. note: you shouldn't use this legacy property. instead, use rtcrtptransceiver to control whether or not to accept incoming video. voiceactivitydetection optional some codecs and hardware are able to detect when audio begins and ends by watching for "silence" (or relatively low sound levels) to occur. this reduces network bandwidth used for audio by only sending audio data when there's actually something to broadcast. however, in some cases, this is unwanted. for example, in the case of music or other non-voice t...
...sessiondescription object describing the newly-created offer. errorcallback an rtcpeerconnectionerrorcallback which will be passed a single domexception object explaining why the request to create an offer failed. options optional an optional rtcofferoptions dictionary providing options requested for the offer. return value a promise whose fulfillment handler will receive an object conforming to the rtcsessiondescriptioninit dictionary which contains the sdp describing the generated offer. that received offer should be delivered through the signaling server to a remote peer. exceptions these exceptions are returned by rejecting the returned promise. your rejection handler should examine the received exception to determine which occurred. invalidstateerror the rtcpeerconnection ...
...And 3 more matches
RTCRemoteOutboundRtpStreamStats.localId - Web APIs
e rtcremoteoutboundrtpstreamstats), it should also have a corresponding inbound-rtp object. both of these provide information about the same batch of packets being transmitted from the remote peer to the local device. the difference is that remote-outbound-rtp describes statistics about the transmission(s) from the perspective of the remote peer, while inbound-rtp offers statistics about the incoming data from the local peer's perspective. you can examine, try out, and experiment with this example on glitch. example in this example, we have a pair of functions: the first, networkteststart(), captures an initial report, and the second, networkteststop(), captures a second report, then uses the two reports to output some information about the network conditions... xxx ... networkteststart(...
... { if (pc) { startreport = await pc.getstats(); } } given an rtcpeerconnection, pc, this calls its getstats() method to obtain a statistics report object, which it stores in startreport for use once the end-of-test data has been collected by networkteststop(). networkteststop() the networkteststop() function obtains a second report, endreport, then uses the two reports together to determine several... xxx ... finding paired statistics each statistics record of type remote-outbound-rtp (describing a remote peer's statistics about sending data to the local peer) has a corresponding record of type inbound-rtp which describes the local peer's perspective on the same data being moved between the two peers. let's create a utility function to help us look up the value of a key in the pa...
... of type remote-outbound-rtp (describing a remote peer's statistics about sending data to the local peer) has a corresponding record of type inbound-rtp which describes the local peer's perspective on the same data being moved between the two peers. let's create a utility function to help us look up the value of a key in the paired statistics object. the findreportentry() function shown below examines an rtcstatsreport, returning the rtcstats-based statistics record which contains the specified key — and for which the key has the specified value. if no match is found (or the statistics report has no record corresponding to the statistics category indicated by key. function findreportentry(report, key, value) { for (const stats of report.values()) { if (stats[key] === value) { ...
...And 3 more matches
Using server-sent events - Web APIs
this is one-way connection, so you can't send events from a client to a server. ...
...e interface; to open a connection to the server to begin receiving events from it, create a new eventsource object with the url of a script that generates the events. for example: const evtsource = new eventsource("ssedemo.php"); if the event generator script is hosted on a different origin, a new eventsource object should be created with both the url and an options dictionary. ...
... you can also listen for events with addeventlistener(): evtsource.addeventlistener("ping", function(event) { const newelement = document.createelement("li"); const time = json.parse(event.data).time; newelement.innerhtml = "ping at " + time; ...
...And 3 more matches
ServiceWorkerGlobalScope - Web APIs
an active service worker is automatically restarted to respond to events, such as serviceworkerglobalscope.onfetch or serviceworkerglobalscope.onmessage. ...
...an active service worker is automatically restarted to respond to events, such as serviceworkerglobalscope.onfetch or serviceworkerglobalscope.onmessage. ...
...an active service worker is automatically restarted to respond to events, such as serviceworkerglobalscope.onfetch or serviceworkerglobalscope.onmessage. ...
...And 3 more matches
Lighting in WebGL - Web APIs
most commonly used lighting model or if you'd like to see a webgl based explanation see this artcle. there are three basic types of lighting: ambient light is the light that permeates the scene; it's non-directional and affects every face in the scene equally, regardless of which direction it's facing. directional light is light that is emitted from a specific direction. this is light that's coming from so far away that every photon is moving parallel to every other photon. sunlight, for example, is considered directional light. point light is light that is being emitted from a point, radiating in all directions. this is how many real-world light sources usually work. a light bulb emits light in all directions, for example. for our purposes, we're going to simplify the lighting model by ...
...ray to a shader attribute so the shader code can get access to it: // tell webgl how to pull out the normals from // the normal buffer into the vertexnormal attribute. ...
.... ...
...And 3 more matches
WebRTC API - Web APIs
ng, and because each browser has different levels of support for codecs and webrtc features, you should strongly consider making use of the adapter.js library provided by google before you begin to write your code. adapter.js uses shims and polyfills to smooth over the differences among the webrtc implementations across the environments supporting it. adapter.js also handles prefixes and other naming differences to make the entire webrtc development process easier, with more broadly compatible results. the library is also available as an npm package. to learn more about adapter.js, see improving compatibility using webrtc adapter.js. webrtc concepts and usage webrtc serves multiple purposes; together with the media capture and streams api, they provide powerful multimedia capabilities to ...
...connections. included are interfaces representing peer media connections, data channels, and interfaces used when exchanging information on the capabilities of each peer in order to select the best possible configuration for a two-way media connection. interfaces rtcpeerconnection represents a webrtc connection between the local computer and a remote peer. it is used to handle efficient streaming of data between the two peers. rtcdatachannel represents a bi-directional data channel between two peers of a connection. rtcdatachannelevent represents events that occur while attaching a rtcdatachannel to a rtcpeerconnection. the only event sent with this interface is datachannel. rtcsessiondescription represents the parameters of a session. each rtcsessiondescription consists of a descr...
...ate. rtcrtpsender manages the encoding and transmission of data for a mediastreamtrack on an rtcpeerconnection. rtcrtpreceiver manages the reception and decoding of data for a mediastreamtrack on an rtcpeerconnection. rtctrackevent the interface used to represent a track event, which indicates that an rtcrtpreceiver object was added to the rtcpeerconnection object, indicating that a new incoming mediastreamtrack was created and added to the rtcpeerconnection. rtcsctptransport provides information which describes a stream control transmission protocol (sctp) transport and also provides a way to access the underlying datagram transport layer security (dtls) transport over which sctp packets for all of an rtcpeerconnection's data channels are sent and received. dictionaries rtcco...
...And 3 more matches
Using bounded reference spaces - Web APIs
among the various reference spaces available in the webxr set of apis, the bounded-floor reference space is somehwat unique. not only is it represented by a unique subclass, xrboundedreferencespace, but it's the only one which restricts movement based not upon virtual restrictions but upon limitations imposed by the real world. this article examines bounded reference spaces as represented by xrboundedreferencespace, describing what they are and how they're used. 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. introduction a bounded re...
...inst. as the user grows close to the boundary, you might warn them by displaying a message, flashing a warning indicator, playing an audio warning, or the like. and if the user actually collides with the boundary, don't let them continue past it. <<<--- example --->>> creating a bounded reference space before creating a project that relies on bounded reference spaces, it's important to keep in mind that not all xr devices are capable of creating them. by their very nature, bounded reference spaces have special hardware requirements, since they need to allow for the user to physically move around in space while their movements are tracked. in this section, we'll look at how to safely create a session that will work whether bounded spaces are supported or not. safely creating a bounded-pref...
...atures: ["bounded-floor"] }).then((session) => { xrsession = session; startsessionanimation(); }); } } this function, called when the user clicks on a button to start the xr experience, works as usual, exiting at once if a session is already in place, then requesting a new session using immersive-vr mode. the options specified when requesting the session indicate that at a minimum, the session must be compatible with the local-floor reference space, but that it would be nice if the bounded-floor space were supported as well. once the session has been created, our startsessionanimation() function can try to establish a bounded-floor reference space, and if it fails to do so it can then fall back to requesting a local-floor reference space instead (in which we will have...
...And 3 more matches
Migrating from webkitAudioContext - Web APIs
the api. as the specification evolved and changes were made to the spec, some of the old implementation pieces were not removed from the webkit (and blink) implementations due to backwards compatibility reasons. 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. this article attempts to summarize the areas where developers are likely to encounter these problems and provide examples on how to port such code to standards based audiocontext, which will work across different browser engines. note: there is a library called webkitaud...
...asynchronous, which means that it will return immediately, and then when the decoding finishes, one of the success or failure callback functions will get called depending on whether the audio decoding was successful. this means that you may need to restructure your code to run the part which happened after the createbuffer() call in the success callback, as you can see in the example above. renaming of audioparam.settargetvalueattime the settargetvalueattime() method on the audioparam interface has been renamed to settargetattime(). this is also a simple rename to improve the understandability of the api, and the semantics of the method are the same. if your code is using settargetvalueattime(), you can simply rename it to use settargetattime(). for example, if we have code that looks li...
...op attribute, so you can just use the loop attribute instead. instead of having code like this: var source = context.createbuffersource(); source.looping = true; you can change it to respect the last version of the specification: var source = context.createbuffersource(); source.loop = true; note, the loopstart and loopend attributes are not supported in webkitaudiocontext. changes to determining playback state the playbackstate attribute of audiobuffersourcenode and oscillatornode has been removed. depending on why you used this attribute, you can use the following techniques to get the same information: if you need to compare this attribute to unscheduled_state, you can basically remember whether you've called start() on the node or not. if you need to compare this attribute to...
...And 3 more matches
Using the Web Audio API - Web APIs
take a look at getting started with the web audio api. we'll briefly look at some concepts, then study a simple boombox example that allows us to load an audio track, play and pause it, and change its volume and stereo panning. the web audio api does not replace the <audio> media element, but rather complements it, just like <canvas> coexists alongside the <img> element. your use case will determine what tools you use to implement audio. if you simply want to control playback of an audio track, the <audio> media element provides a better, quicker solution than the web audio api. if you want to carry out more complex audio processing, as well as playback, the web audio api provides much more power and control. a powerful feature of the web audio api is that it does not have a strict "sound ...
...ode: const gainnode = audiocontext.creategain(); now we have to update our audio graph from before, so the input is connected to the gain, then the gain node is connected to the destination: track.connect(gainnode).connect(audiocontext.destination); this will make our audio graph look like this: the default value for gain is 1; this keeps the current volume the same. ...
...you can specify a range's values and use them directly with the audio node's parameters. ...
...And 3 more matches
Privileged features - Web APIs
this page lists the windowfeatures parameter of window.open function that requires chrome-privilege in firefox. this is not for web content. the following features require the chrome-privilege. centerscreen centers the window in relation to its parent's size and position. minimizable this setting can only apply to dialog windows; minimizable requires dialog=yes. if minimizable is on, the new dialog window will have a minimize system command icon in the titlebar and it will be minimizable. ...
...ntent. the following features require the chrome-privilege. centerscreen centers the window in relation to its parent's size and position. minimizable this setting can only apply to dialog windows; minimizable requires dialog=yes. if minimizable is on, the new dialog window will have a minimize system command icon in the titlebar and it will be minimizable. any non-dialog window is always minimizable and minimizable=no will be ignored. dependent if on, the new window is said to be dependent of its parent window. a dependent window closes when its parent window closes. a dependent window is minimized on the windows task bar only when its parent window is minimized. on windows platforms, a dependent window does not show on the task bar. a dependent window also stays in front of the pa...
...content, without any of the browser's interface elements. there will be no context menu defined by default and none of the standard keyboard shortcuts will work. the page is supposed to provide a user interface of its own, usually this feature is used to open xul documents (standard dialogs like the javascript console are opened this way). dialog the dialog feature removes all icons (restore, minimize, maximize) from the window's titlebar, leaving only the close button. mozilla 1.2+ and netscape 7.1 will render the other menu system commands (in ff 1.0 and in ns 7.0x, the command system menu is not identified with the firefox/ns 7.0x icon on the left end of the titlebar: that's probably a bug. you can access the command system menu with a right-click on the titlebar). dialog windows are w...
...And 3 more matches
XMLHttpRequest - Web APIs
xmlhttprequest (xhr) objects are used to interact with servers. you can retrieve data from a url without having to do a full page refresh. this enables a web page to update just part of a page without disrupting what the user is doing. xmlhttprequest is used heavily in ajax programming. ...
... of a page without disrupting what the user is doing. xmlhttprequest is used heavily in ajax programming. ...
...a page without disrupting what the user is doing. xmlhttprequest is used heavily in ajax programming. ...
...And 3 more matches
Cognitive accessibility - Accessibility
language, autism, add/adhd, dyslexia, and dyscalculia. an example of a temporary cognitive impairment could be people affected by substances such as alcohol or drugs. another form it can take is depression, such as when mourning the loss of a loved one, or being momentarily saddened by a tweet or video they just saw online. a third example could be sleep deprivation. it may seem like an overwhelming challenge to address the wide range of cognitive differences, especially when solutions for two different people may be conflicting. one way to handle this is to focus on cognitive skills. cognitive 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 so...
... 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 website authentication as easy as possible without compromising security; and ...
...understood by the software is a good way to help ensure it can be used by alternate presentational modes. time it is important to allow users the time they require to complete tasks. guideline 2.2 states "provide users enough time to read and use content." a time limit is any process that happens without user initiation after a set time or on a periodic basis, such as being logged out after 30 minutes or having 15 minutes to make a purchase. people with cognitive disabilities may require more time to read content, or to perform functions such as filling out forms. solutions include providing users enough additional time to complete tasks or eliminate time constraints altogether. timers options for adjusting time requirements include: allowing the user to turn off or adjust the ...
...And 3 more matches
Using CSS animations - CSS: Cascading Style Sheets
letting the browser control the animation sequence lets the browser optimize performance and efficiency by, for example, reducing the update frequency of animations running in tabs that aren't currently visible. configuring the animation to create a css animation sequence, you style the element you want to animate with the animation property or its sub-properties. this lets you configure the timing, duration, and other details of how the animation sequence should progress. this does not configure the actual appearance of the animation, which is done using the @keyframes at-rule as described in defining the animation sequence using keyframes below. the sub-properties of the animation property are: animation-name specifies the name of the @keyframes at-rule describing the animation’s ...
...he animation, which is done using the @keyframes at-rule as described in defining the animation sequence using keyframes below. the sub-properties of the animation property are: animation-name specifies the name of the @keyframes at-rule describing the animation’s keyframes. animation-duration configures the length of time that an animation should take to complete one cycle. animation-timing-function configures the timing of the animation; that is, how the animation transitions through keyframes, by establishing acceleration curves. animation-delay configures the delay between the time the element is loaded and the beginning of the animation sequence. animation-iteration-count configures the number of times the animation should repeat; you can specify infinite to repeat the ani...
...t the animation should alternate direction on each run through the sequence or reset to the start point and repeat itself. animation-fill-mode configures what values are applied by the animation before and after it is executing. animation-play-state lets you pause and resume the animation sequence. ...
...And 3 more matches
Auto-placement in CSS Grid Layout - CSS: Cascading Style Sheets
* {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; colo...
...or: #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-gap: 10px; grid-auto-rows: 100px; } you can use minmax() in your value for grid-auto-rows enabling the creation of rows that are a minimum size but then grow to fit content if it is taller. * {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; } <div class="wrapper"> <div>one</div> <div>two</div> ...
...8a8; padding: 1em; color: #d9480f; } <div class="wrapper"> <div>one</div> <div>two</div> <div>three</div> <div>four <br>this cell <br>has extra <br>content. <br>max is auto <br>so the row expands. </div> <div>five</div> </div> .wrapper { display: grid; grid-template-columns: repeat(3, 1fr); grid-gap: 10px; grid-auto-rows: minmax(100px, auto); } you can also pass in a track listing, this will repeat. the following track listing will create an initial implicit row track as 100 pixels and a second as 200px. this will continue for as long as content is added to the implicit grid. * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; } .wrapp...
...And 3 more matches
Realizing common layouts using CSS Grid Layout - CSS: Cascading Style Sheets
tems in the implicit grid. .wrapper { display: grid; grid-gap: 20px; grid-template-areas: "header" "nav" "content" "sidebar" "ad" "footer"; } after setting up a mobile layout we will get this single column at all screen sizes, we can now add a media query and redefine our layout for the circumstance of having enough screen real estate to show two columns. @media (min-width: 500px) { .wrapper { grid-template-columns: 1fr 3fr; grid-template-areas: "header header" "nav nav" "sidebar content" "ad footer"; } nav ul { display: flex; justify-content: space-between; } } you can see the layout taking shape in the value of grid-template-areas. the header spans over two column tracks, as does the nav. in the th...
...r two column tracks, as does the nav. in the third row track we have the sidebar alongside the content. in the fourth row track i have chosen to place my ad content – so it appears under the sidebar, then the footer next to it under the content. i’m using a flexbox on the navigation to display it in a row spaced out. i can now add a final breakpoint to move to a three-column layout. @media (min-width: 700px) { .wrapper { grid-template-columns: 1fr 4fr 1fr; grid-template-areas: "header header header" "nav content sidebar" "nav content ad" "footer footer footer" } nav ul { flex-direction: column; } } the three-column layout has two 1fr unit side columns and a middle column that has 4fr as the track size. this means that the availab...
... specify any positioning for them. the sidebar is starting on the first column line named col-start, spanning 3 lines. it goes after row line 3, as the header and navigation are in the first two row tracks. the ad panel is below the sidebar, so starts at grid row line 4. then we have the content and footer starting at col-start 4 and spanning 9 tracks taking them to the end of the grid. @media (min-width: 500px) { .side { grid-column: col-start / span 3; grid-row: 3; } .ad { grid-column: col-start / span 3; grid-row: 4; } .content, .main-footer { grid-column: col-start 4 / span 9; } nav ul { display: flex; justify-content: space-between; } } finally we go to the three-column version of this layout. the header continues to span right across the ...
...And 3 more matches
Logical properties for sizing - CSS: Cascading Style Sheets
ppings between logical and physical properties. these mappings assume that you are in a horizontal-tb writing mode, such as english or arabic, in which case width would be mapped to inline-size. if you were in a vertical writing mode then inline-size would be mapped to height. logical property physical property inline-size width block-size height min-inline-size min-width min-block-size min-height max-inline-size max-width max-block-size max-height width and height example the logical mappings for width and height are inline-size, which sets the length in the inline dimension and block-size, which sets the length in the block dimension. when working in english, replacing width with inline-size an...
...size, which sets the length in the block dimension. when working in english, replacing width with inline-size and height with block-size will give the same layout. in the live example below i have set the writing mode to horizontal-tb. ...
... same layout. in the live example below i have set the writing mode to horizontal-tb. change it to vertical-rl and you will see that the first example — which uses width and height — remains the same size in each dimension, despite the text becoming vertical. the second example — which uses inline-size and block-size — will follow the text direction as if the entire block has rotated. min-width and min-height example there are also mappings for min-width and min-height — these are min-inline-size and min-block-size. ...
...And 3 more matches
Using media queries - CSS: Cascading Style Sheets
ple media queries into a single rule. each query in a comma-separated list is treated separately from the others. thus, if any of the queries in a list is true, the entire media statement returns true. in other words, lists behave like a logical or operator. targeting media types media types describe the general category of a given device. although websites are commonly designed with screens in mind, you may want to create styles that target special devices such as printers or audio-based screenreaders. for example, this css targets printers: @media print { ... } you can also target multiple devices. for instance, this @media rule uses two media queries to target both screen and print devices: @media screen, print { ... } see media types for a list of all media types. because they descr...
...t device, or environment. for instance, you can apply specific styles to widescreen monitors, computers that use mice, or to devices that are being used in low-light conditions. this example applies styles when the user's primary input mechanism (such as a mouse) can hover over elements: @media (hover: hover) { ... } many media features are range features, which means they can be prefixed with "min-" or "max-" to express "minimum condition" or "maximum condition" constraints. for example, this css will apply styles only if your browser's viewport width is equal to or narrower than 12450px: @media (max-width: 12450px) { ... } if you create a media feature query without specifying a value, the nested styles will be used as long as the feature's value is not zero (or none, in level 4). for e...
...pe is used by default when no other type is specified. however, if you use the not or only operators, you must explicitly specify a media type. combining multiple types or features the and keyword combines a media feature with a media type or other media features. this example combines two media features to restrict styles to landscape-oriented devices with a width of at least 30 ems: @media (min-width: 30em) and (orientation: landscape) { ... } to limit the styles to devices with a screen, you can chain the media features to the screen media type: @media screen and (min-width: 30em) and (orientation: landscape) { ... } testing for multiple queries you can use a comma-separated list to apply styles when the user's device matches any one of various media types, features, or states. for...
...And 3 more matches
WebKit CSS extensions - CSS: Cascading Style Sheets
bkit-marquee-repetition -webkit-marquee-speed -webkit-marquee-style -webkit-marquee -webkit-mask-box-image-outset -webkit-mask-box-image-repeat -webkit-mask-box-image-slice -webkit-mask-box-image-source -webkit-mask-box-image-width -webkit-mask-box-image -webkit-mask-repeat-x -webkit-mask-repeat-y -webkit-mask-source-type -webkit-max-logical-height -webkit-max-logical-width -webkit-min-logical-height -webkit-min-logical-width n -webkit-nbsp-mode p -webkit-padding-after** -webkit-padding-before** -webkit-padding-end** -webkit-padding-start** -webkit-perspective-origin-x -webkit-perspective-origin-y -webkit-print-color-adjust r-s -webkit-rtl-ordering -webkit-svg-shadow t -webkit-tap-highlight-color -webkit-text-combine -webkit-text-decoration-skip -...
...should use the unprefixed standard properties instead of the prefixed ones listed below. ...
... -webkit-mask-position-x* -webkit-mask-position-y* * supported unprefixed in firefox, with prefix in safari. supported in fir...
...And 3 more matches
<blend-mode> - CSS: Cascading Style Sheets
fect, while a white layer inverts the other layer's 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: 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. ...
...ay backdrop, having no saturation, will have no effect. ...
... this blend mode is equivalent to color, but with the layers swapped. ...
...And 3 more matches
fit-content() - CSS: Cascading Style Sheets
the fit-content() css function clamps a given size to an available size according to the formula min(maximum size, max(minimum size, argument)). the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. the function can be used as a track size in css grid properties, where the maximum size is defined by max-content and the minimum size by auto, which is calculated similar to auto (i.e., minmax(auto, max-content)), except that the track size is clamped at argument if it is greater than the auto minimum. ...
... syntax the fit-content() function accepts a <length> or a <percentage> as an argument. ...
... syntax the fit-content() function accepts a <length> or a <percentage> as an argument. ...
...And 3 more matches
max-width - CSS: Cascading Style Sheets
Web › CSS › max-width
the max-width css property sets the maximum width of an element. it prevents the used value of the width property from becoming larger than the value specified by max-width. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. max-width overrides width, but min-width overrides max-width. ...
...n a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. max-width overrides width, but min-width overrides max-width. syntax /* <length> value */ max-width: 3.5em; /* <percentage> value */ max-width: 75%; /* keyword values */ max-width: none; max-width: max-content; max-width: min-content; max-width: fit-content(20em); /* global values */ max-width: inherit; max-width: initial; max-width: unset; values <length> defines the max-width as an absolute value. <percentage> defines the max-width as a percentage of the containing block's width. auto the browser will calculate and select a max-width for the specified element. none no limit on the size of the box. max-...
...lobal values */ max-width: inherit; max-width: initial; max-width: unset; values <length> defines the max-width as an absolute value. <percentage> defines the max-width as a percentage of the containing block's width. auto the browser will calculate and select a max-width for the specified element. none no limit on the size of the box. max-content the intrinsic preferred max-width. min-content the intrinsic minimum max-width. fit-content(<length-percentage>) uses the fit-content formula with the available space replaced by the specified argument, i.e. min(max-content, max(min-content, argument)). accessibility concerns ensure that elements set with a max-width are not truncated and/or do not obscure other content when the page is zoomed to increase text size. mdn under...
...And 3 more matches
Constraint validation - Developer guides
html5 introduced new mechanisms for forms: it added new semantic types for the <input> element and constraint validation to ease the work of checking the form content on the client side. ...
...oth of these input types, if the multiple attribute is set, several values can be set, as a comma-separated list, for this input. if any of these do not satisfy the condition described here, the type mismatch constraint violation is triggered. note that most input types don't have intrinsic constraints, as some are simply barred from constraint validation or have a sanitization algorithm transforming incorrect values to a correct default. validation-related attributes in addition to the type attribute described above, the following attributes are used to describe basic constraints: attribute input types supporting the attribute possible values constraint description associated violation pattern text, search, url, tel, email, password a javascript re...
...ts: attribute input types supporting the attribute possible values constraint description associated violation pattern text, search, url, tel, email, password a javascript regular expression (compiled with the ecmascript 5 global, ignorecase, and multiline flags disabled) the value must match the pattern. patternmismatch constraint violation min range, number a valid number the value must be greater than or equal to the value. rangeunderflow constraint violation date, month, week a valid date datetime, datetime-local, time a valid date and time max range, number a valid number the value must be less than or equal to the value rangeoverflow constraint violation date, month,...
...And 3 more matches
The HTML autocomplete attribute - HTML: Hypertext Markup Language
le" a job title, or the title a person has within an organization, such as "senior technical writer", "president", or "assistant troop leader". "organization" a company or organization name, such as "acme widget company" or "girl scouts of america". "street-address" a street address. this can be multiple lines of text, and should fully identify the location of the address within its second administrative level (typically a city or town), but should not include the city name, zip or postal code, or country name. "address-line1", "address-line2", "address-line3" each individual line of the street address. these should only be present if the "street-address" is not present. "address-level4" the finest-grained administrative level, in addresses which have four levels. "address-level3" ...
...vel (typically a city or town), but should not include the city name, zip or postal code, or country name. "address-line1", "address-line2", "address-line3" each individual line of the street address. these should only be present if the "street-address" is not present. "address-level4" the finest-grained administrative level, in addresses which have four levels. "address-level3" the third administrative level, in addresses with at least three administrative levels. "address-level2" the second administrative level, in addresses with at least two of them. in countries with two administrative levels, this would typically be the city, town, village, or other locality in which the address is located. "address-level1" the first administrative level in the address. this is typically the pr...
...age loads. the persistence feature is enabled by default. setting the value of the autocomplete attribute to off disables this feature. this works even when the autocomplete attribute would normally not apply by virtue of its type. see bug 654072. examples <div> <label for="cc-number">enter your credit card number</label> <input name="cc-number" id="cc-number" autocomplete="off"> </div> administrative levels in addresses the four administrative level fields (address-level1 through address-level4) describe the address in terms of increasing levels of precision within the country in which the address is located. each country has its own system of administrative levels, and may arrange the levels in different orders when addresses are written. address-level1 always represents the broad...
...And 3 more matches
Date and time formats used in HTML - HTML: Hypertext Markup Language
tring, followed by a hyphen character ("-", or u+002d), followed by a two-digit day of the month. examples of valid date strings date string full date 1993-11-01 november 1, 1993 1066-10-14 october 14, 1066 0571-04-22 april 22, 571 0062-02-05 february 5, 62 time strings a time string can specify a time with precision to the minute, second, or to the millisecond. specifying only the hour or minute isn't permitted. a valid time string minimally consists of a two-digit hour followed by a colon (":", u+003a), then a two-digit minute. the minute may optionally be followed by another colon and a two-digit number of seconds. milliseconds may be specified, optionally, by adding a decimal point character (".", u+002e) followed b...
...ionally be followed by another colon and a two-digit number of seconds. milliseconds may be specified, optionally, by adding a decimal point character (".", u+002e) followed by one, two, or three digits. there are some additional basic rules: the hour is always specified using the 24-hour clock, with 00 being midnight and 11 pm being 23. no values outside the range 00–23 are permitted. the minute must be a two-digit number between 00 and 59. no values outside that range are allowed. if the number of seconds is omitted (to specify a time accurate only to the minute), no colon should follow the number of minutes. if specified, the integer portion of the number of seconds must be between 00 and 59. you cannot specify leap seconds by using values like 60 or 61. if the number of seconds ...
...n, this is the same string as the previous datetime-local string. the space has been replaced with the "t" character and the trailing zero in the fraction of a second has been removed to make the string as short as possible. note that the normalized form of this date drops the ":00" indicating the number of seconds to be zero, because the seconds are optional when zero, and the normalized string minimizes the length of the string. global date and time strings a global date and time string specifies a date and time as well as the time zone in which it occurs. a valid global date and time string is the same format as a local date and time string, except it has a time zone string appended to the end, following the time. time zone offset string a time zone offset string specifies the offset...
...And 3 more matches
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
Web › HTML › Element › audio
and pause/resume playback. crossorigin this enumerated attribute indicates whether to use cors to fetch the related audio file. cors-enabled resources can be reused in the <canvas> element without being tainted. the allowed values are: anonymous sends a cross-origin request without a credential. in other words, it sends the origin: http header without a cookie, x.509 certificate, or performing http basic authentication. if the server does not give credentials to the origin site (by not setting the access-control-allow-origin: http header), the image will be tainted, and its usage restricted. use-credentials sends a cross-origin request with a credential. in other words, it sends the origin: http header with a cookie, a certificate, or performing http basic authentication. if the s...
...rom the media buffer. other audio may have a media timeline that doesn't start at 0 seconds, so setting currenttime to a time before that would fail. for example, if the audio's media timeline starts at 12 hours, setting currenttime to 3600 would be an attempt to set the current playback position well before the beginning of the media, and would fail. the getstartdate() method can be used to determine the beginning point of the media timeline's reference frame. 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). see this proposed specification for more information. in safari, you can use x-webkit-airplay="deny" as a fal...
...you can use x-webkit-airplay="deny" as a fallback. duration read only a double-precision floating-point value which indicates the duration (total length) of the audio in seconds, on the media's timeline. if no media is present on the element, or the media is not valid, the returned value is nan. if the media has no known end (such as for live streams of unknown duration, web radio, media incoming from webrtc, and so forth), this value is +infinity. loop a boolean attribute: if specified, the audio player will automatically seek back to the start upon reaching the end of the audio. muted a boolean attribute that indicates whether the audio will be initially silenced. its default value is false. preload this enumerated attribute is intended to provide a hint to the browser about what...
...And 3 more matches
<textarea> - HTML: Hypertext Markup Language
Web › HTML › Element › textarea
f this attribute is not specified, the <textarea> element must be a descendant of a form element. this attribute enables you to place <textarea> elements anywhere within a document, not just as descendants of form elements. maxlength the maximum number of characters (utf-16 code units) that the user can enter. if this value isn't specified, the user can enter an unlimited number of characters. minlength the minimum number of characters (utf-16 code units) required that the user should enter. name the name of the control. placeholder a hint to the user of what can be entered in the control. carriage returns or line-feeds within the placeholder text must be treated as line breaks when rendering the hint. note: placeholders should only be used to show an example of the type of data that...
...n the right hand corner, which can be used to alter the size of the element on the page. 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. for example, to give your textarea a different border depending on whether it is valid or invalid: textarea:invalid { border: 2px dashed red; } textarea:valid { border: 2px solid lime; } examples basic example the following example show a very simple textarea, with a set numbers of rows and c...
...your textarea a different border depending on whether it is valid or invalid: textarea:invalid { border: 2px dashed red; } textarea:valid { border: 2px solid lime; } examples basic example the following example show a very simple textarea, with a set numbers of rows and columns and some default content. ...
...And 3 more matches
<video>: The Video Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › video
be removed altogether. in some browsers (e.g. chrome 70.0) autoplay doesn't work if no muted attribute is present. autopictureinpicture a boolean attribute which if true indicates that the element should automatically toggle picture-in-picture mode when the user switches back and forth between this document and another document or application. buffered an attribute you can read to determine the time ranges of the buffered media. this attribute contains a timeranges object. controls if this attribute is present, the browser will offer controls to allow the user to control video playback, including volume, seeking, and pause/resume playback. controlslist the controlslist attribute, when specified, helps the browser select what controls to show on the media element whenever the ...
...cture mode (and the control). crossorigin this enumerated attribute indicates whether to use cors to fetch the related image. cors-enabled resources can be reused in the <canvas> element without being tainted. the allowed values are: anonymous sends a cross-origin request without a credential. in other words, it sends the origin: http header without a cookie, x.509 certificate, or performing http basic authentication. if the server does not give credentials to the origin site (by not setting the access-control-allow-origin: http header), the image will be tainted, and its usage restricted. use-credentials sends a cross-origin request with a credential. in other words, it sends the origin: http header with a cookie, a certificate, or performing http basic authentication. if the s...
...media to that position if the media is currently loaded. if the media is being streamed, it's possible that the user agent may not be able to obtain some parts of the resource if that data has expired from the media buffer. other media may have a media timeline that doesn't start at 0 seconds, so setting currenttime to a time before that would fail. the getstartdate() method can be used to determine the beginning point of the media timeline's reference frame. disablepictureinpicture prevents the browser from suggesting a picture-in-picture context menu or to request picture-in-picture automatically in some cases. disableremoteplayback a boolean attribute used to disable the capability of remote playback in devices that are attached using wired (hdmi, dvi, etc.) and wireless techno...
...And 3 more matches
Array.prototype.includes() - JavaScript
the includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax arr.includes(valuetofind[, fromindex]) parameters valuetofind the value to search for. note: when comparing strings and characters, includes() is case-sensitive. fromindex optional the position in this array at which to begin searching for valuetofind. ...
...ttps://github.com/mdn/interactive-examples and send us a pull request. syntax arr.includes(valuetofind[, fromindex]) parameters valuetofind the value to search for. note: when comparing strings and characters, includes() is case-sensitive. fromindex optional the position in this array at which to begin searching for valuetofind. 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). defaults to 0. ...
... 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). defaults to 0. return value a boolean which is true if the value valuetofind is found within the array (or the part of the array indicated by the index fromindex, if specified). values of zero are all considered to be equal, regardless of sign. (that is, -0 is considered to be equal to both 0 and +0), but false is not considered to be the same as 0. note: technically speaking, includes() uses the samevaluezero algorithm to determine whether the given element is found. examples [1, 2, 3].includes(2) // true [1, 2, 3].includes(4) // false...
...And 3 more matches
Array.prototype.lastIndexOf() - JavaScript
the lastindexof() method returns the last index at which a given element can be found in the array, or -1 if it is not present. the array is searched backwards, starting at fromindex. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax arr.lastindexof(searchelement[, fromindex]) parameters searchelement element to locate in the array. fromindex optional the index at which to start searching backwards. defaults to the array's length minus one (arr.length - 1), i.e. the whole array will be searched. if the index is greater than or equal to the length of the array, the whole array will be searched. if nega...
...). polyfill lastindexof was added to the ecma-262 standard in the 5th edition; as such it may not be present in other implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of lastindexof in implementations which do not natively support it. ...
...n the 5th edition; as such it may not be present in other implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of lastindexof in implementations which do not natively support it. this algorithm is exactly the one specified in ecma-262, 5th edition, assuming object, typeerror, number, math.floor, math.abs, and math.min have their original values. ...
...And 3 more matches
Intl.PluralRules() constructor - JavaScript
fault is "best fit". for information about this option, see the intl page. type the type to use. possible values are: "cardinal" for cardinal numbers (refering to the quantity of things). this is the default value. "ordinal" for ordinal number (refering to the ordering or ranking of things, e.g. "1st", "2nd", "3rd" in english). ...
...is "best fit". for information about this option, see the intl page. type the type to use. possible values are: "cardinal" for cardinal numbers (refering to the quantity of things). this is the default value. "ordinal" for ordinal number (refering to the ordering or ranking of things, e.g. "1st", "2nd", "3rd" in english). ...
...or information about this option, see the intl page. type the type to use. possible values are: "cardinal" for cardinal numbers (refering to the quantity of things). this is the default value. "ordinal" for ordinal number (refering to the ordering or ranking of things, e.g. "1st", "2nd", "3rd" in english). ...
...And 3 more matches
Understanding latency - Web Performance
sts for multiple css, scripts, and media files. the greater the number and size of these requests, the greater the impact of high latency on user experience. on a connection with low latency, requested resources will appear almost immediately. on a connection with high latency, there will be a discernible delay between the time that a request is sent, and the resources are returned. we can determine the amount of latency by measuring the speed with which the data moves from one network location to another. latency can be measured one way, for example, the amount of time it takes to send a request for resources, or the length of the entire round-trip from the browser’s request for a resource to the moment when the requested resource arrives at the browser. network throttling to emulate ...
...the browser. network throttling to emulate the latency of a low bandwidth network, you can use developer tools and switch to a lower end network connection. in the developer tools, under the network table, you can switch the throttling option to 2g, 3g, etc. ...
...rottling to emulate the latency of a low bandwidth network, you can use developer tools and switch to a lower end network connection. in the developer tools, under the network table, you can switch the throttling option to 2g, 3g, etc. ...
...And 3 more matches
Mobile first - Progressive web apps (PWAs)
n progressively enhance browsers higher up the food chain. note: starting with very little and working up as the need arises usually makes more sense than starting with everything and then covering up things if they aren't needed! mobile constraints we have already mentioned the fact that mobiles generally have less memory, processing power and bandwidth than other devices (although bear in mind that smart tvs are also generally pretty low powered.) they also have less viewport size available. therefore, as well as splitting content into different views, and simplifying the interface and content on each view of your application for mobile as much as possible, it is also a good idea to not include visual effects such as shadows, animations, and gradients. you should at least consider it ...
... my sample project using volo create myapp mozilla/mortar-app-stub this creates a sample project inside a directory called myapp. the app's code files are inside the www folder. volo has a number of useful commands available, of which we will just use a couple: volo server: starts a local web server at localhost:8080 and runs your app through it: great for easy testing. volo build: builds a minified code version of your app, ready for production deployment, in a www-built folder. volo build base=www-built: runs the built version through the server instead of the development version. built-in features of the mortar template mortar templates contain a number of built-in features. in this sample app, i have used a couple of the built-in features to: include an install button that wo...
...vely, so they would become the positioning contexts of the absolutely positioned elements (you don't want them to be positioned relative to the <body> element.) adding a mobile first layout the above layout is fine for narrower layouts, but it doesn't work very well when you get wider than about 480px. ...
...And 3 more matches
The building blocks of responsive design - Progressive web apps (PWAs)
// the whole of brick.js goes here! } this causes nothing inside the brick.js file to be run unless the viewport width is 480px or less. problem solved. really wide screens one thing you might notice is that when the viewport gets very wide (such as on a cinema display), the layout stops getting wider, and just centers in the space available. this is pretty simple to achieve. ...
...le to be run unless the viewport width is 480px or less. problem solved. really wide screens one thing you might notice is that when the viewport gets very wide (such as on a cinema display), the layout stops getting wider, and just centers in the space available. this is pretty simple to achieve. ...
... use the mobile first methodology, you will be creating your mobile layout inside your default css, before any media queries have been applied. the media queries then supply css that is only applied to the markup when the viewport is above a certain width. let's look at a quick example: header { height: 300px; width: 100%; background: url(images/small-header.jpg) center; } @media all and (min-width: 480px) { header { background: url(images/large-header.jpg) center; } } this means that mobile browsers only download the mobile background image asset — not the desktop mobile assets — because they fail the media query tests and therefore ignore the media queries. you can also serve a larger graphic to a higher resolution device using a resolution media query, like so: button...
...And 3 more matches
Content type - SVG: Scalable Vector Graphics
ecifically: anything ::= char* where char is the production for a character, as defined in xml 1.0 , section 2.2. clock-value <clock-value> clock values have the same syntax as in smil animation specification. ...
...ction for a character, as defined in xml 1.0 , section 2.2. clock-value <clock-value> clock values have the same syntax as in smil animation specification. ...
...syntax as in smil animation specification. the grammar for clock values is repeated here: clock-val ::= full-clock-val | partial-clock-val | timecount-val full-clock-val ::= hours ":" minutes ":" seconds ("." fraction)? partial-clock-val ::= minutes ":" seconds ("." fraction)? timecount-val ::= timecount ("." fraction)? (metric)? metric ::= "h" | "min" | "s" | "ms" hours ::= digit+; any positive number minutes ::= 2digit; range from 00 to 59 seconds ::= 2digit; range from 00 to 59 fraction ::= digit+ timecount ::= digit+ 2digit ::= digit digit digit ::= [0-9] for timecount values, the default metric suffix is "s" (for seconds). no embedded white space is allowed in cloc...
...And 3 more matches
Paths - SVG: Scalable Vector Graphics
Web › SVG › Tutorial › Paths
plex 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. the shape of a <path> element is defined by one parameter: d. (see more in basic shapes.) the d attribute contains a series of commands and parameters used by those commands. each of the commands is instantiated (for example, creating a class, naming and locating it) by a specific letter. for instance, let's move to the x and y coordinates (10, 10). the "move to" command is called with the letter m. when the parser runs into this letter, it knows it needs to move to a point. so, to move to (10,10) the command to use would be m 10 10. after that, the parser begins reading for the next command. all of the commands also come in two variants. a...
...trol points are shown in red, and the inferred control point in blue. <svg width="190" height="160" xmlns="http://www.w3.org/2000/svg"> <path d="m 10 80 c 40 10, 65 10, 95 80 s 150 150, 180 80" stroke="black" fill="transparent"/> </svg> the other type of bézier curve, the quadratic curve called with q, is actually a simpler curve than the cubic one. it requires one control point which determines the slope of the curve at both the start point and the end point. it takes two parameters: the control point and the end point of the curve. note: the co-ordinate deltas for q are both relative to the previous point (that is, dx and dy are not relative to dx1 and dy1). q x1 y1, x y (or) q dx1 dy1, dx dy <svg width="190" height="160" xmlns="http://www.w3.org/2000/svg"> <path d="m 10...
...hat goes diagonally across the page. at its center, two elliptical arcs have been cut out (x radius = 30, y radius = 50). in the first one, the x-axis-rotation has been left at 0, so the ellipse that the arc travels around (shown in gray) is oriented straight up and down. for the second arc, though, the x-axis-rotation is set to -45 degrees. this rotates the ellipse so that it is aligned with its minor axis along the path direction, as shown by the second ellipse in the example image. for the unrotated ellipse in the image above, there are only two different arcs and not four to choose from because the line drawn from the start and end of the arc goes through the center of the ellipse. in a slightly modified example the two ellipses that form the four different arcs can be seen: <svg xmln...
...And 3 more matches
Index - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Index
no summary! 12 setting parameters xslt while running transformations using precoded .xsl and .xml files is quite useful, configuring the .xsl file from javascript may be even more useful. for example, javascript and xslt could be used to sort xml data and then display it. the sorting would have to alternate between ascending and descending sorting. 13 transforming xml with xslt needsmigration, transforming_xml_with_xslt, xml, xslt the separation of content and presentation is a key design feature of xml. the structure of an xml document is designed to reflect and clarify important relationships among the individual aspects of the content itself, unhindered by a need to provide any indication about how this data should eventually be presented. th...
...onships among the individual aspects of the content itself, unhindered by a need to provide any indication about how this data should eventually be presented. this intelligent structuring is particularly important as more and more data transfers are automated and take place between highly heterogeneous machines linked by a network. ...
... transforming_xml_with_xslt, xml, xslt the extensible stylesheet language/transform is a very powerful language, and a complete discussion of it is well beyond the scope of this article, but a brief discussion of some basic concepts will be helpful in understanding the description of netscape's capabilities that follows. ...
...And 3 more matches
Creating annotations - Archive of obsolete content
mple button, try the action button or toggle button apis, and for a more complex widget try the toolbar or sidebar apis. we'll use two objects to create annotations: a page-mod to find page elements that the user can annotate, and a panel for the user to enter the annotation text itself. selector page-mod selector content scripts the content script for the selector page-mod uses jquery to examine and manipulate the dom. its main job is to maintain a matched element: this is the page element that is the current candidate for an annotation. the matched element is highlighted and has a click handler bound to it which sends a message to the main add-on code. the selector page mod can be switched on and off using a message from the main add-on code. it is initially off: var matchedelement ...
...ave this code in a new file called selector.js in your add-on's data directory. because this code uses jquery, you'll need to download that as well, and save it in data. ...
...mo-review-process/. you should see the highlight appearing when you move the mouse over certain elements: click on the highlight and you should see something like this in the console output: info: show info: http://blog.mozilla.com/addons/2011/02/04/overview-amo-review-process/, post-2249,when you submit a new add-on, you will have to choose between 2 review tracks: full review and preliminary review. annotation editor panel so far we have a page-mod that can highlight elements and send information about them to the main add-on code. next we will create the editor panel, which enables the user to enter an annotation associated with the selected element. we will supply the panel's content as an html file, and will also supply a content script to execute in the panel's context. s...
...And 2 more matches
JavaScript Daemons Management - Archive of obsolete content
here are some code snippets that simplify and abstract the management of daemons. the following daemons management framework is the major version of setinterval – a little framework. introduction sometimes a page uses dozens and dozens of animations. ...
...ep track of all events started and then to stop them when appropriate through the cleartimeout() function. a possible approach to solve this problem is to nest all the information needed by each animation to start, stop, etc. in different objects (daemons) and then to create a constructor for such a class of objects (daemon) in order to standardize and simplify the instantiation of them. ...
...ed and then to stop them when appropriate through the cleartimeout() function. a possible approach to solve this problem is to nest all the information needed by each animation to start, stop, etc. in different objects (daemons) and then to create a constructor for such a class of objects (daemon) in order to standardize and simplify the instantiation of them. note: a minimalistic version of it (minidaemon) is published here. ...
...And 2 more matches
Adding Events and Commands - Archive of obsolete content
that the addeventlistener method receives the event name without the "on" prefix, while element attributes do have the prefix. there's a long list of events you can listen to, and which you use depend on the situation. elements only implement the events that are relevant to them, but there are several events that are implemented for most elements. these are some notable events you should keep in mind: oncommand. this is one of the most important and commonly used events in xul. it's very useful because it represents the most common action for input controls such as menu items, buttons and checkboxes. 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. it's an abstraction of the main way to interact with a con...
...n an element receives or loses focus when the user is navigating with the keyboard. you can combine these with -moz-user-focus to add custom focus behavior to elements that normally wouldn't have it. drag and drop. drag and drop operations involve several events. since drag and drop is a complicated thing to manage, there are some high level wrappers that facilitate working with it. ...
...age, there are some high level wrappers that facilitate working with it. also keep in mind that there are 2 drag and drop apis, the newest (and preferred) one introduced in firefox 3.5. event handlers can take an event argument, which is an event object that holds information on the event. you can get information on key modifiers (in case the user was holding a modifier key like alt while performing the event), screen coordinates for mouse events, and most importantly, the target element for the event. for example: <button label="&xulschoolhello.defaultgreeting.label;" oncommand="xulschoolchrome.browseroverlay.changegreeting(event);" /> then on the javascript code you would have something like this: changegreeting : function(aevent) { // more stuff aevent.target.setattribute("labe...
...And 2 more matches
Adding Toolbars and Toolbar Buttons - Archive of obsolete content
you'll have to include the css files for those as well, each in a new line like the one above. we now have code that adds one or more buttons to the toolbar palette. the user can now use the customize dialog to add the buttons to the current firefox toolbars. in most cases this is not what you want as default behavior, because it would be very hard for the user to discover your buttons. keep in mind most users don't know how to customize toolbars in firefox. let's add our own toolbar. this is done in the overlay as well. <window id="main-window"> <toolbox id="navigator-toolbox"> <toolbar id="xulschoolhello-toolbar" toolbarname="&xulschoolhello.toolbarname.label;" accesskey="&xulschoolhello.toolbar.accesskey;" customizable="true" mode="icons" context="toolbar-context-menu...
...and </window> are not required) our toolbar is added as a child of the toolbox element in the main browser window. the toolbox is the collection of toolbars in firefox, including the main menu bar. let's look at the attributes we used: the toolbarname is the name that will appear on the view > toolbars menulist. this menu allows hiding and showing any toolbar. the customizable attribute determines if the user can customize the toolbar. you should normally set this to true, unless you have strong reasons not to want users changing your toolbar. the mode attribute is set to icons, which is the usual value. this can be changed in the customize dialog by the user. the context attribute should also be set if you want a customizable toolbar. it points to the id of a popup element that holds ...
...beneath them. see the back/forward buttons in the main firefox toolbar for an example. menu toolbar buttons are handy when you want to include many options in your toolbar and you don't want it to be too cluttered. the other types, checkbox and radio are useful when you have buttons that change state when the user clicks on them. read more about this in the type attribute specification. keep in mind some users have small screens with low resolution. if you shrink the firefox window, you'll notice that the content resizes until it reaches its minimum size and begin to be cropped (cut), making ui elements disappear. you should test that your toolbar resizes gracefully and doesn't force firefox to crop content before it's strictly necessary. when you need something more elaborate than a butt...
...And 2 more matches
Handling Preferences - Archive of obsolete content
« previousnext » preferences in firefox mozilla applications are highly customizable. preferences are used to store settings and information to change their default behavior. to open the preferences window in firefox, select the following from the main menu: on windows, tools > options on mac, firefox > preferences on linux, edit > preferences note: keep in mind the usage of the terms "preferences" and "options" in different platforms. if you need to refer to the term "preference" in any of your locale files, you must change the string depending on the operating system. tip: you can use window.navigator.platform in your chrome code to figure out the operating system firefox is running on. you can use the hidden dom window in non-chrome code. firefox loads user preferences...
...ser.js in the user's profile directory holds additional preferences the user has set. this file is never written to by firefox, but you may wish to set preferences manually in this file to override other settings. lockfile settings: these preferences are stored in a file that usually has the name mozilla.cfg or netscape.cfg. the file may be located on a network. it is intended to be used by an administrator or isp to set settings centrally. in addition, certain preferences may be locked such that users cannot change them. locked preferences are disabled in the preferences window. firefox exposes its most common high-level preferences through the preferences window and other parts of its ui. in reality there are thousands of other preferences firefox handles that are not readily available t...
...rlier, a preference with no default value can be set later on. note: we recommend that you include all of your extension preferences in the js defaults file. it makes it easier to compile a list of the preferences your extensions handle, and to document what they do. the preferences file you need to create should be defaults/preferences/yourextensionname.js, under your extension root. the naming of the js file is not compulsory, but it is the standard most extensions use. note: the purpose of the defaults directory is to hold non-code files your extension needs. in the past we have used this directory to store xslt files for xml transformations and local storage template files (more on this later). it's the best place to put miscellaneous files your extension needs. download this ...
...And 2 more matches
JavaScript Object Management - Archive of obsolete content
n all of your xul files. we'll be using the placeholder 〈namespace〉 below. this needs to be replaced with an identifier name which is unique to your add-on. if your add-on is called sergeant pepper, for instance, then sgtpepper would be a good namespace name. /** * 〈namespace〉 namespace. */ if (typeof 〈namespace〉 == "undefined") { var 〈namespace〉 = {}; }; note: the naming standard that we normally follow is that the first part of the namespace corresponds to the development group (or company), and the second to the specific project. however, most extensions are small projects by individuals, so these examples follow a more practical approach of having just one namespace with the project name. notice how the 〈namespace〉 namespace is declared using var. we n...
...string-bundle"); window.settimeout( function() { window.alert(that._stringbundle.getstring("xulschoolhello.greeting.label")); }, 0); } the settimeout function executes the function in the first parameter, after a delay in miliseconds specified by the second parameter. in this case we set the delay to 0, which means the function should be executed as soon as possible. firefox has a minimum delay of 10-15ms (taken from this blog post), so it won't really run instantly. it is more than enough to let the window finish its load. use window.settimeout and window.setinterval to control timed code execution. in case you're using javascript code modules or xpcom objects, where a window object is not readily available, use an nsitimer instead. this post suggests a way to achieve ...
...e a variable called that that equals this, and use that in the anonymous function. javascript has a host of features that make it extremely flexible, but it also has some disadvantages, as it is not as strict as other languages, such as java. a clear example of this is the fact that there are no private or public keywords that allow you to protect object members. as a alternative for this, a naming standard is frequently used to distinguish private and public members. there's no scope enforcement whatsoever, but this standard give others the chance to "play nice" and don't use private members. use "_" at the beginning of private attributes and methods in js objects. for example: _stringbundle, _createusernode(). exercise here's a short exercise to test a particular aspect of the chr...
...And 2 more matches
Signing an XPI - Archive of obsolete content
ructions are for how to test with a self-signed certificate. see signing an extension for a practical guide. introduction this article describes how to sign your own firefox extensions with a code-signing certificate on a windows platform. it was developed from the linux article so you want to sign your xpi package? by mozdev group's pete collins. this article is a mirror of the original, with minor reformatting, some new info and all links updated in march 2010. get network security services 1. download the latest network security services (nss) package from the mozilla ftp site at https://ftp.mozilla.org/pub/mozilla.or.../nss/releases/. for windows, you'll want the nss-3.11.4.zip package in the nss_3_11_4_rtm/msvc6.0/winnt5.0_opt.obj/ folder - it is by 2010 the only one with the right ...
...ncrypt your keys. the password should be at least 8 characters long, and should contain at least one non-alphabetic character. 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: . warning: performing this operation while the browser is running could cause corruption of your security databases. if the browser is currently running, you should exit the browser before continuing this operation. enter "y" to continue, or anything else to abort: y enter certificate information. all fields are optional. acceptable characters are numbers, letters, spaces, and apostrophes. certificate common name:...
...enu choose options->advanced->security->view certificates->authorities firefox 1.0: from the tools menu choose options->advanced->certificates->manage certificates->authorities press the import button. navigate to the folder containing x509.cert and choose it. in the downloading certificate dialog, tick trust this ca to identify software developers. and press the view button if you wish to examine the certificate more closely. press the ok button and you'll see your new certificate in the list of authorities. 2. attempt to install the signed extension either drag and drop or browse to and download the signed xpi. when the mozilla firefox software installation dialog appears the organisation name of the certificate will appear where firefox usually displays unsigned. image obtaining a...
...And 2 more matches
Creating a dynamic status bar extension - Archive of obsolete content
specifically, this sample displays a stock quote in the status bar, and, when you mouse over it, displays a tooltip containing more detailed information about the stock. ...
...you can follow this tutorial to update that existing code with new features. download the sample update the install manifest replace all occurrences of the first sample's id, "status-bar-sample-1", with the new sample's id, "stockwatcher", and update the front end metadata to describe our new extension. see install manifests for details. update the chrome manifest the chrome manifest needs only a minor update from the previous sample; simply replace the id of the first sample, "status-bar-sample-1", with the name of the new sample, "stockwatcher". if you need to brush up, visit the chrome manifest section. write the xul file we need a slightly more complicated xul file this time, in order to add a reference to the javascript code that will do the real work: <?xml version="1.0" encoding="utf-8...
...tlistener() dom function to tell firefox to call the stockwatcher.startup() function when a new browser window is opened: window.addeventlistener("load", function(e) { stockwatcher.startup(); }, false); our new extension has two primary functions: startup() and refreshinformation(). the refreshinformation() function contains another function, called inforeceived(). ...
...And 2 more matches
Installing plugins to Gecko embedding browsers on Windows - Archive of obsolete content
since the prospect of embedded gecko browsers raises the scenario of more than one gecko-based browser that a netscape-style plugin can work with, it becomes important to let plugin developers know how to discover these browsers on a windows machine. this information applies to mozilla based browsers that pull the mozilla codebase after the mozilla 0.9.1 milestone release. none of the registry keys mentioned here are written by browsers before the mozilla 0.9.1 timeframe. ...
...ested mechanism to find out where to install the plugin dll so that it is picked up by mozilla based browsers on the desktop. go to hkey_local_machine\software\mozilla caveat emptor: if the mozilla subkey is not present under hkey_local_machine, look under hkey_current_user\software\mozilla\. on windows xp and windows 2000, in order to write to the registry, sometimes the software may need administrator privileges. thus, some mozilla based browsers, such as the netscape 6 installer, write to the hkey_current_user key in addition; this doesn't require administrator privileges. traditionally, hkey_current_user is a copy of everything in hkey_local_machine. the mozilla subkey is written under hkey_current_user\software also. however, always look at hkey_local_machine first. enumerate the...
...ompuserve 7.0 finding the browser executable is useful if you wish to launch the browser following installation of the plugin dll. go to hkey_local_machine\software\mozilla caveat emptor: if the mozilla subkey is not present under hkey_local_machine, look under hkey_current_user\software\mozilla\. on windows xp and win2000, in order to write to the registry, sometimes the software may need administrator privileges. thus, software such as the netscape 6 installer writes to the hkey_current_user key additionally, which doesn't require administrator privileges. traditionally, hkey_current_user is a copy of everything in hkey_local_machine. the mozilla subkey is written under hkey_current_user\software also. however, always look at hkey_local_machine first. you can enumerate the applicatio...
...And 2 more matches
Source code directories overview - Archive of obsolete content
code base. this document contains material for seamonkey, firefox, and toolkit. it is a living document which is (supposed to be) updated monthly according to changes in the mozilla source tree. see also similar information in mozilla source code directory structure, and also see the more detailed overview of how the parts of gecko fit together. introduction: common subdirectories a common naming scheme is used throughout the mozilla source trees. at the top level is the name of the product (e.g. seamonkey). at the second level is the name of the module (e.g. the editor directory in seamonkey). the third level is where the common naming scheme usually takes over. many third level directories contain the base, the public and the idl directories. although not required, these common names a...
...ized into a submodule. build contains any special makefiles for building the particular module. doc contains any documentation associated with this module. idl contains the xpidl (cross platform interface definition language) interface files. interfaces are used so functionality can be available to both javascript scripts and c code with as little effort as possible. xpidl files have their own mini-language and processing tools. public contains source code that will be exported to the dist/include directory. they are not all necessarily public in the general sense; some are only meant for internal use in a certain module. as more code is written with or converted to xpidl interfaces, the value of the public directory diminishes. src contains the bulk of the source code. tests contains c...
...he code for firefox. this will be covered below. build contains scripts (usually perl) and programs used by the mozilla build team for building and managing the mozilla code base. these programs coordinate the running of makefiles and the creation of the dist directory. calendar contains the code for the various mozilla calendar apps and extensions. caps contains c interfaces and code for determining the capabilities of content based on the security settings and certificates (e.g. verisign). chrome contains the toolkit chrome registry. config contains scripts and programs used by mozilla developers to manipulate the code base and to perform special actions inside makefiles. these programs are used for code level things instead of build level things (which are a stored in the build direct...
...And 2 more matches
Layout System Overview - Archive of obsolete content
one-to-many correspondence between content elements and frames. layout creates frames for content based on either the specific html rules for an element or based on the css display type of the element. 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. a content element is passed to the style system and a request is made to resolve the style for that element. this causes the style system to apply all style rules that correspond to the element and results in a resolved style context - the style data specific to that element. the layout module looks at the 'display' field of the style context to deter...
...e that display type by using the style system. a content element is passed to the style system and a request is made to resolve the style for that element. this causes the style system to apply all style rules that correspond to the element and results in a resolved style context - the style data specific to that element. the layout module looks at the 'display' field of the style context to determine what kind of frame to create (block, inline, table, etc.). the style context is associated with the frame via a reference because it is needed for many other computations during the formatting of the frames. once a frame is created for a content element, it must be formatted. we refer to this as 'laying out' the frame, or as 'reflowing' the frame. each frame implements a reflow method to compute...
...el, changes that occur after the document has been loaded and (possibly) presented. these dynamic changes are caused by manipulations of the content model via the dom (generally through javascript). when a content element is modified, added or removed, layout is notified. ...
...And 2 more matches
Modularization techniques - Archive of obsolete content
may reside in separate, possibly dynamically loaded, libraries. each interface is assigned a unique interface identifier, or iid. nsisupports the key interface in our model is the nsisupports interface, our equivalent to com's iunknown interface. nsisupports provides two key features, interface interrogation and reference counting. interface interrogation is a simple, uniform mechanism for determining which interfaces a object supports, and for hiding the the mechanics of how the object was implemented. interface interrogation is performed using the queryinterface() method. the caller passes in an id and a pointer to a address to place the resulting interface. if the query is successful, queryinterface() will return ns_ok. if the object does not support the given interface, it will return ...
...nce counting facilities are always available. the iid for nsisupports is defined as ns_isupports_iid. queryinterface() has several important characteristics that must be maintained. if you perform a queryinterface() on interface a and obtain interface b, you must be able to perform a queryinterface() b and obtain interface a. ...
...must be maintained. if you perform a queryinterface() on interface a and obtain interface b, you must be able to perform a queryinterface() b and obtain interface a. if interfaces a and b are both implemented by the same instance, performing a queryinterface() for nsisupports on either should return the exact same interface. this means that even though interface b inherits from nsisupports, performing a queryinterface() on it may not return the same interface. this important behavior is the only reliable mechanism for determining whether interfaces a and b are implemented by the same object.for simple objects, maintaining these behaviors is easy. aggregation, as we will see later, can complicate things. on the other hand, objects are allowed a certain degree of flexibility in their implement...
...And 2 more matches
Mozilla Application Framework in Detail - Archive of obsolete content
we provide an xml-based language called xul for defining the user interface of your application. ...
...g netscape's open source initiative among thousands of internet developers and participating vendors such as netscape. the gecko browser engine offers several key benefits including: size: gecko has been designed to be lean and modular, bringing full-functionality browsing to a variety of new consumer devices. because it is small, gecko can be embedded on devices with limited footprints and it minimizes download size for desktop browsers. speed: gecko has been designed for speed and is several times faster than previous versions of internet browsing software. standards support: gecko is the first browser technology to fully implement the latest w3c standards and enables developers to build rich, dynamic web pages and web-based applications that look and run as intended across a variety o...
...net standards such as css1, html 4.0, dom1, rdf, xml and javascript. modular, embeddable: gecko's modular architecture enables developers to add or remove modules with little effort, fitting the software to the available hardware and adjusting functionality to match product requirements. gecko is implemented as a collection of xpcom components that can be easily added or removed. flexible programming interfaces such as the web shell api, the java wrapper api and the gecko activex control make gecko easily embeddable into applications and devices. full browser functionality: gecko allows any desktop application as well as new devices, products and appliances to be web-enabled, with complete browser functionality. supported standards and features include data transport protocols, multilingual...
...And 2 more matches
New Security Model for Web Services - Archive of obsolete content
rusted scripts behind firewalls introduction this page describes an alternative mechanism which can be used to protect all internal resources against requests from sandboxed scripts. this should especially be implemented for soap calls by untrusted scripts. when an attempt is made to access a resource at a previously-unknown uri, the sandbox reads a file at that domain with declarations to determine whether access is permitted to the script. if the file is not there, access is denied. the problem external untrusted scripts loaded behind a firewall are executed in a sandbox. these scripts may legitimately require access to external resources, but permitting them to access internal resources permits the compromise of these resources that would normally not be available to applications outsi...
...e firewall. signed scripts a certain degree of additional trust may be lent to a script by having the author digitally sign it. but signed scripts have not really caught on as they require certificates do not change the basic problem that some completely-unknown party has written a script that might now have access to internal resources. asking the user where the sandbox cannot otherwise determine whether the executing script should be permitted access to the resource, a dialog box may be raised to ask the user to grant special privileges. this is currently permitted for locally-saved scripts and signed scripts. this could be combined with the other options above such as whitelisting, signed scripts, etc. but the big problem with this is that the typical browser user really does not eithe...
...quences if he inadvertently opens a hole in his company's firewall. quite complex settings may be required to permit the user to allow access to desired external services without risking other resources. controlling resource access on the server access by untrusted scripts really needs to be under the control of the stake holder, which is the resource and server owner -- not the user -- to determine whether a resource should be insulated from web applications loaded from outside of the firewall. 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. soap services which have not been cleared for access by unt...
...And 2 more matches
Space Manager Detailed Design - Archive of obsolete content
onst {return (bandrect*)pr_next_link(this);} bandrect* prev() const {return (bandrect*)pr_prev_link(this);} void insertbefore(bandrect* abandrect) {pr_insert_before(abandrect, this);} void insertafter(bandrect* abandrect) {pr_insert_after(abandrect, this);} void remove() {pr_remove_link(this);} // split the band rect into two vertically, with this band rect becoming // the top part, and a new band rect being allocated and returned for the // bottom part // // does not insert the new band rect into the linked list bandrect* splitvertically(nscoord abottom); // split the band rect into two horizontally, with this band rect becoming // the left part, and a new band rect being allocated and returned for the // right part // ...
...e than ns_space_manager_cache_size are allocated at a time,then standard allocation is used. void* operator new(size_t asize); void operator delete(void* aptr, size_t asize); a static method is used to shutdown the space manager recycling. this method deletes all of the space mangers in the recycler,and prevents further recycling. it is meant to be called only when the layout module is being terminated. static void shutdown(); origin / coordinate space translation /** * translate the current origin by the specified (dx, dy). this * creates a new local coordinate space relative to the current * coordinate space. */ void translate(nscoord adx, nscoord ady) { mx += adx; my += ady; } /** * returns the current translation from local coordinate space to * world coordinate space. this r...
...etween the band and the y offset is available - create a trapezoid with that region and return it. if the (adjusted) y offset is between the band top and bottom, then get the available space for the band by calling getbandavailablespace otherwise, move to the next band getbandavailablespace: this method is called from getbanddata only. it walks all of the bands in the space manager and determines which bands intersect with the band passed in, and if within those bands there are regions that are available or occupied. first, walk all of the bands until a band that is to the right of the desired offset is located starting at that band, walk the remaining bands: if the current band is to the right of the requested band, then there is available space. if there is more room in the bandd...
...And 2 more matches
Install script template - Archive of obsolete content
var software_name="cult3d mozilla viewer"; // plids (http://mozilla.org/projects/plugins/plugin-identifier.html) are coined by vendors. ...
...tware_name="cult3d mozilla viewer"; // plids (http://mozilla.org/projects/plugins/plugin-identifier.html) are coined by vendors. ...
...// this block also invokes a function to write registry keys (plid) and checks return from key writing // this block invokes refreshplugins() to ensure that plugin and xpt are available for use immediately if (errblock1 == success) { // installation to the current browser was a success - this is the most important job of t...
...And 2 more matches
XUL Events - Archive of obsolete content
en the user presses the close button.commandthe command event is executed when an element is activated.commandupdatethe commandupdate event is executed when a command update occurs on a <commandset>. ...
... close button.commandthe command event is executed when an element is activated.commandupdatethe commandupdate event is executed when a command update occurs on a <commandset>. ...
... change this event is sent when the value of the textbox is changed. the event is not sent until the focus is moved to another element. attribute: onchange click this event is sent when a mouse button is pressed and released. you can determine which mouse button was clicked by retrieving the button property of the event object. this event is also sent when the user double-clicks with the mouse. the detail property specifies how many clicks occurred. you can also check for triple-clicks in a similar manner. you should not use this event in xul to respond to user actions; the command event should be used instead. attribute: ...
...And 2 more matches
textbox (Toolkit autocomplete) - Archive of obsolete content
ll create an autocomplete textbox that will search the user's history. ...
...nsearchcomplete, ontextentered, ontextreverted, open, readonly,showcommentcolumn, showimagecolumn, size, tabindex, tabscrolling, timeout, type, value properties accessibletype, completedefaultindex, controller, crop, disableautocomplete, disablekeynavigation, disabled, editable, focused, forcecomplete, highlightnonmatches, ignoreblurwhilesearching, inputfield, label, maxlength, maxrows, minresultsforpopup, open, popup, popupopen, searchcount, searchparam, selectionend, selectionstart, showcommentcolumn, showimagecolumn,size, tabindex, tabscrolling, textlength, textvalue, timeout, type, value methods getsearchat, onsearchcomplete, ontextentered, ontextreverted, select, setselectionrange examples <textbox type="autocomplete" autocompletesearch="history"/> attributes ...
...m element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. maxlength type: integer the maximum number of characters that the textbox allows to be entered. maxrows type: integer the number of rows to show in the results list at a time. a scrollbar will appear so the user can scroll through the remaining items. minresultsforpopup new in thunderbird 3requires seamonkey 2.0 type: integer the minimum number of results that must be returned for the popup to be displayed. the default value is 1. new in thunderbird 3requires seamonkey 2.0 a zero value will always open the popup. this can be used to display additional items that are not autocomplete results. nomatch type: boolean this attrib...
...And 2 more matches
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
ntent, and paste it into the new file: custombutton = { 1: function () { alert("just testing") }, } there is nothing to customize for now. save the file. the next section in this tutorial contains examples of code that you can use to make your button do something useful. explanation: this file specifies what happens when you press the button. it uses the javascript programming language, together with features provided by the application. 9. download the button image. get a context menu for the image that you see here (for example, by right-clicking it). choose save image as... from the context menu, and save it in the same custombutton directory as the files you have just created. ensure that the name of the saved file is: button-1s.png explanatio...
...nt – javascript console. messages in the javascript console can provide information about javascript, xul or css files. note: the preference setting javascript.options.strict imposes restrictions that are not appropriate for the simple scripts in this tutorial. if you choose to use this setting, either ignore the warnings that it generates, or change the coding style to keep it quiet. ...
...adding more buttons to add another button, edit button.xul. ...
...And 2 more matches
XUL Structure - Archive of obsolete content
t a set of packages containing xul files, javascript and style sheets. these files are accessed via a chrome url and have enhanced privileges and work just like any other package. of course, the browser is much larger and more sophisticated than most extensions. firefox and thunderbird, as well as number of other components are all written in xul and are all accessible via chrome urls. you can examine these packages by looking in the chrome directory where firefox or another xul application is built. the chrome url always begins with 'chrome://'. in much the same way as an 'http://' url always refers to remote web sites accessed using http, and the 'file://' url always refers to local files, the 'chrome://' url always refers to installed packages and extensions. we'll look more at the syntax...
...either of these features grant extra privileges; instead they are used to open a new top-level window without the browser ui such as the menu and toolbar. you will commonly use this feature in more complex xul applications since you wouldn't want the browser ui to exist around your dialog boxes. the files for a package are usually combined into a single jar file. a jar file may be created and examined using a zip utility. for instance, you can open the jar files in mozilla's chrome directory to see the basic structure of a package. although it's normal to combine the files into a jar file, packages may also be accessed in expanded form into a directory. although you don't normally distribute a package this way, it is handy during development since you can edit the file directly and then relo...
... browser.js -- other browser xul and js files goes here -- bookmarks -- bookmarks files go here -- preferences -- preferences files go here -- . . . this is easily recognizable as a content package, as the top-level directory is called content. for skins, this directory will usually be called skin and for locales, it will usually be called locale. this naming scheme isn't necessary, but this is a common convention to make the parts of a package clearer. some packages may include a content section, a skin, and a locale. in this case, you will find a subdirectory for each type. for example, chatzilla is distributed in this way. the content/browser directory contains a number of files with .xul and .js extensions. the xul files are the ones with the .x...
...And 2 more matches
XUL element attributes - Archive of obsolete content
container type: boolean set to true if the element is to act as a container which can have child elements. this would be used for folders. this will be set by the template builder as needed. containment type: uri this attribute specifies rdf properties (an rdf predicate) that indicate that a resource is a container. when generating content from a template this is used to determine which resources from the datasource are containers and thus can have child nodes and which ones are not containers. this attribute should be placed on the same element that the datasources and the ref attribute is on. it may be set to a space-separated list of rdf properties or resources. context type: id should be set to the value of the id of the popup element that should appear when...
...nctions to retrieve the tree rows. flex type: string (representing an integer) indicates the flexibility of the element, which indicates how an element's container distributes remaining empty space among its children. flexible elements grow and shrink to fit their given space. elements with larger flex values will be made larger than elements with lower flex values, at the ratio determined by the two elements. the actual value is not relevant unless there are other flexible elements within the same container. once the default sizes of elements in a box are calculated, the remaining space in the box is divided among the flexible elements, according to their flex ratios. specifying a flex value of 0 has the same effect as leaving the flex attribute out entirely. height type...
...ox are calculated, the remaining space in the box is divided among the flexible elements, according to their flex ratios. specifying a flex value of 0 has the same effect as leaving the flex attribute out entirely. height type: string (representing an integer) the preferred height of the element in pixels. the actual displayed height may be different if the element or its contents have a minimum or maximum height. the css height property may also be used. hidden type: boolean if set to true, the element is not displayed. this is similar to setting the css display property to 'none'. id type: unique id a unique identifier so that you can identify the element with. you can use this as a parameter to getelementbyid() and other dom functions and to reference the eleme...
...And 2 more matches
XUL accessibility guidelines - Archive of obsolete content
rd access keyboard access is important to users who can't use a mouse. many screen reader users and those with physical disabilities rely on the keyboard as their primary input tool. these users require easy, predictable, and well-documented keyboard control. tab order provide a logical tab order and ensure that users can navigate all content using a keyboard. by default, the tab order is determined by the order of the elements in the underlying code. it can also be set programmatically with the tabindex attribute if needed, but this should be done sparingly and thoroughly tested whenever it is used. the navigation order should be logical, generally left to right, top to bottom. navigation order may vary depending on the nature of the application or the reading direction of the language. ...
...tcuts. when creating an extension (for firefox or another xul application), make sure the keyboard shortcuts you assign do not interfere with those already defined by the base application. refer to the following resources when setting keyboard shortcuts. learn more keyboard shortcuts and accesskeys mozilla keyboard planning faq and cross reference. an excellent guide for determining unused key combinations and cross platform issues. mozilla keyboard shortcuts. a full list of keyboard shortcuts for the various mozilla applications. mozilla's accesskey faq. a short reference for using the accesskey attribute. context menus the context menu is the small menu activated with a right mouse click on a content area or element (or with shift + f10 or vk_apps on wi...
... devices such as eye tracking to type. this process can be slow. other users need time to cognitively process what is happening in the application. testing human computer interaction ensure that help documentation is up to date. verify that alerts are displayed through appropriate xul elements. ...
...And 2 more matches
menuitem - Archive of obsolete content
autocheck type: boolean if this attribute is true or left out, the checked state of the button will be switched each time the button is pressed. if this attribute is false, the checked state must be adjusted manually. when autocheck is true, the button type should be "checkbox" or "radio". checked type: boolean indicates whether the element is checked or not. use hasattribute() to determine whether this attribute is set instead of getattribute(). for buttons, the type attribute must be set to checkbox or radio for this attribute to have any effect. note: if the checked attribute is set to true, and you persist its value via the persist attribute, mozilla will fail to persist its value when the menuitem is unchecked because of bug 15232. a workaround is to set the autocheck attr...
... to enable the element, leave this attribute out entirely. visible controls have a disabled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. image type: uri the uri of the image to appear on the element. if this attribute is empty or left out, no image appears. the position of the image is determined by the dir and orient attributes. note: the menuitem must have a class of menuitem-iconic for the image to appear. key type: id set to the id of a key element whose key shortcut is displayed in the menuitem. label type: string the label that will appear on the element. if this is left out, no text appears. for an editable menuitem element the value of this attribute is cop...
... tabindex type: integer the tab order of the element. the tab order is the order in which the focus is moved when the user presses the "tab" key. elements with a higher tabindex are later in the tab sequence. type type: one of the values below can be used to create checkable menuitems or for radio button menuitems. checkbox the menuitem is checked. the checked attribute determines whether the menuitem is checked or not. radio the menuitem becomes part of a radio group. other menuitems that have the same value for their name attributes are part of the same radio group. only one menuitem in the same radio group can be checked at once. more information on adding checkmarks to menus in the xul tutorial validate type: one of the values below this attribute in...
...And 2 more matches
scale - Archive of obsolete content
Archive › Mozilla › XUL › scale
al scale. lower values are to the left and higher values are to the right. set the orient attribute to vertical to use a vertical scale. the user may use the arrow keys to increment and decrement the value by one unit, or the page up and page down keys to increment and decrement the value by one page, as specified by the pageincrement attribute. ...
...row keys to increment and decrement the value by one unit, or the page up and page down keys to increment and decrement the value by one page, as specified by the pageincrement attribute. the home and end keys set the scale's value to the minimum and maximum values, respectively. a scale will fire a change event whenever the scale's value is modified. ...
...ge down keys to increment and decrement the value by one page, as specified by the pageincrement attribute. the home and end keys set the scale's value to the minimum and maximum values, respectively. a scale will fire a change event whenever the scale's value is modified. attributes dir, disabled, increment, max, min, movetoclick, pageincrement, tabindex, value properties disabled, max, min, increment, pageincrement, tabindex, value, methods decrease, decreasepage, increase, increasepage, examples horizontal scale: <scale min="1" max="10"/> vertical scale: <scale min="1" max="10" orient="vertical"/> attributes dir type: one of the values below the direction in which the child elements of the element are placed. normal for scales, the scale's values are...
...And 2 more matches
Getting started with XULRunner - Archive of obsolete content
p 1: download xulrunner you can find a download link on the main xulrunner page here on mdn. since we are not creating any binary xpcom components, we only need to download and install the xulrunner runtime package, not the sdk. the xulrunner download for windows is a zip file, not a true install. as a developer, i like the idea that xulrunner only needs to be unzipped onto my machine. i am assuming that it doesn’t need to hook into my windows system and that’s a good thing. it also means that the xulrunner is portable so, if you develop your applications to be portable you could carry them around on a flash drive or sync them in the cloud. the mac version of xulrunner is distributed as an tar.bz2 archive. you can extract this to any location you like, but there are many places in the...
...eate a new application root-level manifest that includes the /chrome/chrome.manifest, which is what this tutorial will do. step 4: set up application.ini the application.ini file acts as the xulrunner entry point for your application. it specifies how your application intends to use the xulrunner platform as well as configure some information that xulrunner uses to run your application. here is mine: [app] vendor=xultest name=myapp version=1.0 buildid=20100901 id=xulapp@xultest.org [gecko] minversion=1.8 maxversion=200.* note: the minversion and maxversion fields indicate the range of gecko versions your application is compatible with; make sure that you set them so that the version of xulrunner you're using is in that range, or your application won't work. note: make sure your applica...
...3, the default location of the chrome.manifest has changed in xulrunner 2.0, so we also need a simple chrome.manifest in the application root which will include the the manifest in our chrome root. here is the application root chrome.manifest: manifest chrome/chrome.manifest step 6: set up preferences the prefs.js file tells xulrunner the name of the xul file to use as the main window. ...
...And 2 more matches
NPN_Version - Archive of obsolete content
« gecko plugin api reference « browser side plug-in api summary lets plugins obtain version information, both of the plug-in api and of the browser itself. syntax #include <npapi.h> void npn_version(int* plugin_major, int* plugin_minor, int* netscape_major, int* netscape_minor); parameters the function has the following parameters: plugin_major pointer to a plug-in's major version number; changes with major code release number. ...
...f the plug-in api and of the browser itself. syntax #include <npapi.h> void npn_version(int* plugin_major, int* plugin_minor, int* netscape_major, int* netscape_minor); parameters the function has the following parameters: plugin_major pointer to a plug-in's major version number; changes with major code release number. plugin_minor pointer to a plug-in's minor version number; changes with point release number. netscape_major pointer to the browser's major version; changes with major code release number. ...
...for example, plug-in api version 4.03 has a major version number of 4 and a point release number of 3. ...
...And 2 more matches
-ms-scroll-limit - Archive of obsolete content
the -ms-scroll-limit css property is a microsoft extension that specifies values for the -ms-scroll-limit-x-min, -ms-scroll-limit-y-min, -ms-scroll-limit-x-max, and -ms-scroll-limit-y-max properties. ...
... the -ms-scroll-limit css property is a microsoft extension that specifies values for the -ms-scroll-limit-x-min, -ms-scroll-limit-y-min, -ms-scroll-limit-x-max, and -ms-scroll-limit-y-max properties. ...
... the -ms-scroll-limit css property is a microsoft extension that specifies values for the -ms-scroll-limit-x-min, -ms-scroll-limit-y-min, -ms-scroll-limit-x-max, and -ms-scroll-limit-y-max properties. ...
...And 2 more matches
CSS - Archive of obsolete content
Archive › Web › CSS
hat specifies the block progression and layout orientation.-ms-content-zoom-chainingthe -ms-content-zoom-chaining css property is a microsoft extension specifying the zoom behavior that occurs when a user hits the zoom limit during page manipulation.-ms-content-zoom-limitthe -ms-content-zoom-limit css shorthand property is a microsoft extension that specifies values for the -ms-content-zoom-limit-min and -ms-content-zoom-limit-max properties.-ms-content-zoom-limit-maxthe -ms-content-zoom-limit-max css property is a microsoft extension that specifies the selected elements' maximum zoom factor.-ms-content-zoom-limit-minthe -ms-content-zoom-limit-min css property is a microsoft extension that specifies the minimum zoom factor.-ms-content-zoom-snapthe -ms-content-zoom-snap css shorthand property ...
...roperty is a microsoft extension that specifies values for the -ms-content-zoom-snap-type and -ms-content-zoom-snap-points properties.-ms-content-zoom-snap-pointsthe -ms-content-zoom-snap-points css property is a microsoft extension that specifies where zoom snap-points are located.-ms-content-zoom-snap-typethe -ms-content-zoom-snap-type css property is a microsoft extension that specifies how zooming is affected by defined snap-points.-ms-content-zoomingthe -ms-content-zooming css property is a microsoft extension that specifies whether zooming is enabled.-ms-filterthe -ms-filter css property is a microsoft extension that sets or retrieves the filter or collection of filters applied to an object.-ms-flow-fromthe -ms-flow-from css property is a microsoft extension that gets or sets a value id...
...nt that serves as the region's data source.-ms-high-contrast-adjustthe -ms-high-contrast-adjust css property is a microsoft extension that gets or sets a value indicating whether to override any css properties that would have been set in high contrast mode.-ms-hyphenate-limit-charsthe -ms-hyphenate-limit-chars css property is a microsoft extension that specifies one to three values indicating the minimum number of characters in a hyphenated word. if the word does not meet the required minimum number of characters in the word, before the hyphen, or after the hyphen, then the word is not hyphenated.-ms-hyphenate-limit-linesthe -ms-hyphenate-limit-lines css property is a microsoft extension specifying the maximum number of consecutive lines in an element that may be ended with a hyphenated word.
...And 2 more matches
E4X for templating - Archive of obsolete content
functions such as the following foreach (which can work with arrays, objects, or e4x objects) are quite convenient in iterating over complex structures such as e4x would not normally allow. ...
...cts) are quite convenient in iterating over complex structures such as e4x would not normally allow. ...
... (h is a handler with an explicit argument v only, or beginning with k, v) lev is optional argument to note recursive depth (if part of recursion) */ function foreach (min, max, arr, h, lev) { var k, ret=<></>, it = 1; lev = lev || 0; if (typeof min === 'number') { if (typeof max !== 'number') { lev = h; h = arr; arr = max; max = min; min = 1; } } else { lev = arr; h = max; arr = min; max = number.positive_infinity; min = 1; } if (h.length === 1) { for (k in arr) { if (it < min) { ++it; continue; } if (it > max) { break; } ret+=h(arr[k],...
...And 2 more matches
XForms Custom Controls - Archive of obsolete content
ood understanding of xforms, xbl, javascript and css is needed. xpcom knowledge will certainly not hurt. but even if you are only comfortable with a couple of these technologies, we hope that the possibilities outlined below will inspire you to learn more where you need to. implementation status the framework we use in the mozilla xforms processor is very much a "work in progress". please keep in mind that just about everything we mention here may change to some degree as we continue to work on it. work has just started in the w3c xforms working group to investigate the custom control issue, so eventually (hopefully?) there will be an "official" and common way to customize your form's user interface across all xforms processors. why do you need this you will probably find that your need for c...
...ing for. for example, you might want to render images that are held inside an instance document or you would like to show a disabled trigger when its bound node becomes irrelevant rather than having it not display (the current default behavior). every xforms control's presentation has its own xbl binding. in many cases different values provided for the appearance or mediatype attributes will determine which xbl binding will be used for a particular xforms control on the form. as mentioned in the spec, the appearance attribute can be used to influence the look and feel of a control even when all other conditions remain constant. for example, in the mozilla xforms extension we will render a combobox widget when appearance='minimal' on a select1 control. should the form author instead choose to ...
...a control even when all other conditions remain constant. for example, in the mozilla xforms extension we will render a combobox widget when appearance='minimal' on a select1 control. should the form author instead choose to use appearance='compact' on this control, we would render a listbox widget. here is a snippet from our .css file to show the type of css rule we would use to make such a determination. xf|select1[appearance="compact"] { -moz-binding: url('chrome://xforms/content/select-xhtml.xml#xformswidget-select1-compact'); } the mediatype attribute can be used by the form author to align the type of presentation with the type of data that the bound instance node contains. for example, if mediatype='image/*' then the user should see the image that the bytes represent rather than jus...
...And 2 more matches
Windows Media in Netscape - Archive of obsolete content
lled. client-side detection using javascript objects internet explorer implements the activexobject object to create new instances of activex controls. netscape 7.1 introduces geckoactivexobject which can be used in a similar way to create instances of the windows media player. the following javascript illustrates one approach using object detection of activexobject and geckoactivexobject to determine if the windows media activex control is supported and available for use. javascript will dynamically write out what browser you are running, and what kind of windows media player technology you may have. example 1: client-side detection scripts browser architecture supports: netscapeplugin windows media player installed: true windows media scriptable: false windows media version: plu...
...both activexobject and geckoactivexobject function similarly. the next subsection discusses them in detail. geckoactivexobject vs. activexobject both geckoactivexobject and activexobject work very similarly, with one key difference: both take a programmatic id (progid) and use it to create a reference to the windows media player. the progid of windows me...
...qualifying references with document. is sufficient to resolve the...
...And 2 more matches
Index - Game development
new technologies are constantly arriving to make it possible to develop better and more powerful games that can be run in any standards-compliant web browser. 2 anatomy of a video game games, javascript, main loop, requestanimationframe i want to be clear that any of the above, or none of them, could be best for your game. ...
... guide, mobile no summary! 7 publishing games games, html5, javascript, monetization, promotion, distribution, publishing this series of articles looks at the options you have when you want to publish and distribute your game, and earn something out of it while you wait for it to become famous. 8 game distribution cocoonio, game, game publishing, games, gaming, html5, javascript, mobile game distribution, phonegap, web stores, distribution distribution is the way to give the world access to your game. there are many options available and there's no single good answer as to which is the best. when you've published the game it's time to focus on promotion — letting people know your game exists. without promotion, they wouldn't even be able to le...
...s the best. when you've published the game it's time to focus on promotion — letting people know your game exists. without promotion, they wouldn't even be able to learn about it and play it. 9 game monetization games, html5, javascript, monetization, advertisements, branding, iap, licensing there are many ways to earn money — everything that applies to the "normal" aaa gaming world can be, more or less, applied to casual html5 games. you might however also focus on selling licenses, doing branding, or earning on a revenue share basis from the advertisements. it's totally up to you which path you're going to follow. 10 game promotion community, games, javascript, promotion, blog, competitions, youtube any way of promoting your game is good. you ha...
...And 2 more matches
What is accessibility? - Learn web development
erstanding content, remembering how to complete tasks, and confusion caused by inconsistent webpage layouts. ...
...t. this myth actually can be true if either: you are trying to "retrofit" accessibility onto an existing website that has significant accessibility issues. you have only started to consider accessibility and uncovered related issues in the late stages of a project. if however, you consider accessibility from the start of a project, the cost of making most content accessible should be fairly minimal. when planning your project, factor accessibility testing into your testing regime, just like testing for any other important target audience segment (e.g. target desktop or mobile browsers). test early and often, ideally running automated tests to pick up on programmatically detectable missing features (such as missing image alternative text or bad link text — see element relationships an...
...hic, and take reasonable steps to try to fix the problem. note: our handling common accessibility problems article covers accessibility specifics that should be tested in more detail. to summarize: consider accessibility from the start of a project, and test early and often. just like any other bug, an accessibility problem becomes more expensive to fix the later it is discovered. bear in mind that a lot of accessibility best practices benefit everyone, not just users with disabilities. for example, lean semantic markup is not only good for screen readers, but it is also fast to load and performant. this benefits everyone, especially those on mobile devices and/or slow connections. publish an accessibility statement on your site and engage with people having problems. accessibility...
...And 2 more matches
Organizing your CSS - Learn web development
you will find in use by others to help improve maintainability. prerequisites: basic computer literacy, basic software installed, basic knowledge of working with files, html basics (study introduction to html), and an idea of how css works (study css first steps.) objective: to learn some tips and best practices for organizing stylesheets, and find out about some of the naming conventions and tools in common usage to help with css organization and team working. tips to keep your css tidy here are some general suggestions for ways to keep your stylesheets organised and tidy. does your project have a coding style guide? if you are working with a team on an existing project, the first thing to check is whether the project has an existing style guide for css. th...
...guide for css. the team style guide should always win over your own personal preferences. there often isn't a right or wrong way to do things, but consistency is important. keep it consistent if you get to set the rules for the project or are working alone, then the most important thing to do is to keep things consistent. 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? if spaces, how many spaces?) having a set of rules you always follow reduces the amount of mental overhead needed when writing css, as some of the decisions are already made. formatting readable css there are a couple of ways you ...
...ade. formatting readable css there are a couple of ways you will see css formatted. some developers put all of the rules onto a single line, like so: .box { background-color: #567895; } h2 { background-color: black; color: white; } other developers prefer to break everything onto a new line: .box { background-color: #567895; } h2 { background-color: black; color: white; } css doesn't mind which one you use. we personally find it is more readable to have each property and value pair on a new line. comment your css adding comments to your css will help any future developer work with your css file, but will also help you when you come back to the project after a break. /* this is a css comment it can be broken onto multiple lines. */ a good tip is to add a block of comments betw...
...And 2 more matches
Flexbox - Learn web development
endicular to the direction the flex items are being laid out in. the start and end of this axis are called the cross start and cross end. the parent element that has display: flex set on it (the <section> in our example) is called the flex container. the items being laid out as flexible boxes inside the flex container are called flex items (the <article> elements in our example). bear this terminology in mind as you go through subsequent sections. you can always refer back to it if you get confused about any of the terms being used. columns or rows? flexbox provides a property called flex-direction that specifies what direction the main axis runs in (what direction the flexbox children are laid out in) — by default this is set to row, which causes them to be laid out in a row in the d...
... when you refresh, you'll see that the third <article> takes up twice as much of the available width as the other two — there are now four proportion units available in total (since 1 + 1 + 2 = 4). the first two flex items have one unit each so they take 1/4 of the available space each. the third one has two units, so it takes up 2/4 of the available space (or one-half). you can also specify a minimum size value inside the flex value. try updating your existing article rules like so: article { flex: 1 200px; } article:nth-of-type(3) { flex: 2 200px; } this basically states "each flex item will first be given 200px of the available space. after that, the rest of the available space will be shared out according to the proportion units." try refreshing and you'll see a difference in ho...
...e flex-grow longhand property. a second unitless proportion value — flex-shrink — that comes into play when the flex items are overflowing their container. this specifies how much of the overflowing amount is taken away from each flex item's size, to stop them overflowing their container. this is quite an advanced flexbox feature, and we won't be covering it any further in this article. the minimum size value we discussed above. this can be specified individually using the flex-basis longhand value. we'd advise against using the longhand flex properties unless you really have to (for example, to override something previously set). they lead to a lot of extra code being written, and they can be somewhat confusing. horizontal and vertical alignment you can also use flexbox features to...
...And 2 more matches
Legacy layout methods - Learn web development
er project. 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 the grid layout systems used prior to css grid layout being available in browsers. 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. we now refer to these as "legacy" methods. for new projects, in most cases css grid layout will be used in combination with one or more other modern layout methods to form the basis for any layout. you will ho...
...n how grid systems and grid frameworks based on floats and flexbox work. having studied grid layout you will probably be surprised how complicated this all seems! this knowledge will be helpful to you if you need to create fallback code for browsers that do not support newer methods, in addition to allowing you to work on existing projects which use these types of systems. it is worth bearing in mind, as we explore these systems, that none of them actually create a grid in the way that css grid layout creates a grid. they work by giving items a size, and pushing them around to line them up in a way that looks like a grid. a two column layout let's start with the simplest possible example — a two column layout. you can follow along by creating a new index.html file on your computer, filli...
...ious example page, or make a local copy of our simple-grid-finished.html code to use as a starting point. update the second css rule (with the .wrapper selector) as follows: body { width: 90%; max-width: 980px; margin: 0 auto; } .wrapper { padding-right: 2.08333333%; } not only have we given it a percentage width, we have also added a max-width property in order to stop the layout becoming too wide. next, update the fourth css rule (with the .col selector) like so: .col { float: left; margin-left: 2.08333333%; width: 6.25%; background: rgb(255, 150, 150); } now comes the slightly more laborious part — we need to update all our .col.span rules to use percentages rather than pixel widths. this takes a bit of time with a calculator; to save you some effort, we've done it...
...And 2 more matches
Responsive design - Learn web development
certain resolution) and apply css selectively to style the page appropriately for the user's needs. for example, the following media query tests to see if the current web page is being displayed as screen media (therefore not a printed document) and the viewport is at least 800 pixels wide. the css for the .container selector will only be applied if these two things are true. @media screen and (min-width: 800px) { .container { margin: 1em 2em; } } you can add multiple media queries within a stylesheet, tweaking your whole layout or parts of it to best suit the various screen sizes. the points at which a media query is introduced, and the layout changed, are known as breakpoints. a common approach when using media queries is to create a simple single-column layout for narrow-scre...
...ays have their browser window maximized. by using a flexible grid, you only need to add in a breakpoint and change the design at the point where the content starts to look bad. for example, if the line lengths become unreadably long as the screen size increases, or a box becomes squashed with two words on each line as it narrows. in the early days of responsive design, our only option for performing layout was to use floats. flexible floated layouts were achieved by giving each element a percentage width, and ensuring that across the layout the totals were not more than 100%. in his original piece on fluid grids, marcotte detailed a formula for taking a layout designed using pixels and converting it into percentages. target / context = result for example, if our target column size is 60...
...and give you easier ways to do so. multicol the oldest of these layout methods is multicol — when you specify a column-count, this indicates how many columns you want your content to be split into. the browser then works out the size of these, a size that will change according to the screen size. .container { column-count: 3; } if you instead specify a column-width, you are specifying a minimum width. the browser will create as many columns of that width as will comfortably fit into the container, then share out the remaining space between all the columns. therefore the number of columns will change according to how much space there is. .container { column-width: 10em; } flexbox in flexbox, flex items will shrink and distribute space between the items according to the space i...
...And 2 more matches
How can we design for all types of users? - Learn web development
s, culture, location, and so on. active learning there is no active learning available yet. dig deeper color contrast to keep your text readable, use a text color that contrasts well with the background color. make it extra easy to read the text, to help visually-impaired people and people using their phones on the street. the w3c defines a good color mix with an algorithm that calculates luminosity ratio between foreground and background. the calculation may seem pretty complicated, but we can rely on tools to do the job for us. let's download and install the paciello group's colour contrast analyser. note: alternatively you can find a number of contrast checkers online, such as webaim's color contrast checker. we suggest a local checker because it comes packaged with an on-screen c...
...ad and install the paciello group's colour contrast analyser. note: alternatively you can find a number of contrast checkers online, such as webaim's color contrast checker. we suggest a local checker because it comes packaged with an on-screen color picker to find out a color value. for instance, let's test the colors on this page and see how we fare in the colour contrast analyser: the luminosity contrast ratio between text and background is 8.30:1, which exceeds the minimum standard (4.5:1) and should enable many visually-impaired people to read this page. font size you can specify font size on a website either through relative units or absolute units. absolute units absolute units are not proportionally calculated but refer to a size set in stone, so to speak, and are expressed...
...els (px). for instance, if in your css you declare this: body { font-size:16px; } … you are telling the browser that whatever happens, the font size must be 16 pixels. modern browsers get around this rule by pretending that you're asking for "16 pixels when the user sets a zoom factor of 100%". yet, for many years internet explorer adamantly displayed 16 pixels as 16 pixels. in this case, zooming did nothing, even as late as internet explorer 8, which we still have to cater to because it's still around. relative units also called proportional units, relative units are computed relative to a parent element. relative units are friendlier to accessibility because they respect the settings on the user's system. relative units are expressed in em, % and rem: percent-based sizes: % this...
...And 2 more matches
What are hyperlinks? - Learn web development
the same website, is called an internal link. without internal links, there's no such thing as a website (unless, of course, it's a one-page website). external link a link from your webpage to someone else's webpage. without external links, there is no web, since the web is a network of webpages. use external links to provide information besides the content available through your webpage. incoming links a link from someone else's webpage to your site. it's the opposite of an external link. note that you don't have to link back when someone links to your site. when you're building a website, focus on internal links, since those make your site usable. find a good balance between having too many links and too few. we'll talk about designing website navigation in another article, but as a ...
... and too few. we'll talk about designing website navigation in another article, but as a rule, whenever you add a new webpage, make sure at least one of your other pages links to that new page. on the other hand, if your site has more than about ten pages, it's counter-productive to link to every page from every other page. when you're starting out, you don't have to worry about external and incoming links as much, but they are very important if you want search engines to find your site (see below for more details). anchors most links tie two webpages together. anchors tie two sections of one document together. when you follow a link pointing to an anchor, your browser jumps to another part of the current document instead of loading a new document. however, you make and use anchors the sam...
...ew document. however, you make and use anchors the same way as other links. links and search engines links matter both to users and search engines. every time search engines crawl a webpage, they index the website by following the links available on the webpage. ...
...And 2 more matches
Debugging HTML - Learn web development
code of some kind, everything is usually fine, until that dreaded moment when an error occurs — you've done something wrong, so your code doesn't work — either not at all, or not quite how you wanted it to. for example, the following shows an error reported when trying to compile a simple program written in the rust language. here, the error message is relatively easy to understand — "unterminated double quote string". if you look at the listing, you can probably see how println!(hello, world!"); might logically be missing a double quote. however, error messages can quickly get more complicated and less easy to interpret as programs get bigger, and even simple cases can look a little intimidating to someone who doesn't know anything about rust. debugging doesn't have to be scary thoug...
...e how println!(hello, world!"); might logically be missing a double quote. however, error messages can quickly get more complicated and less easy to interpret as programs get bigger, and even simple cases can look a little intimidating to someone who doesn't know anything about rust. ...
...le with writing and debugging any programming language or code is familiarity with both the language and the tools. html and debugging html is not as complicated to understand as rust. html is not compiled into a different form before the browser parses it and shows the result (it is interpreted, not compiled). and html's element syntax is arguably a lot easier to understand than a "real programming language" like rust, javascript, or python. the way that browsers parse html is a lot more permissive than how programming languages are run, which is both a good and a bad thing. permissive code so what do we mean by permissive? well, generally when you do something wrong in code, there are two main types of error that you'll come across: syntax errors: these are spelling errors in your co...
...And 2 more matches
Asynchronous JavaScript - Learn web development
-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites asynchronous javascript is a fairly advanced topic, and you are advised to work through javascript first steps and javascript building blocks modules before attempting this. if you are not familiar with the concept of asynchronous programming, you should definitely start with the general asynchronous programming concepts article in this module. if you are, then you can probably skip to the introducing asynchronous javascript module. note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you can try out (most of) the code examples in an online coding program such as jsbi...
...you should understand these concepts before working through the other articles in the module. ...
...nchronous javascript module. note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you can try out (most of) the code examples in an online coding program such as jsbin or glitch. guides general asynchronous programming concepts in this article we'll run through a number of important concepts relating to asynchronous programming, and how this looks in web browsers and javascript. you should understand these concepts before working through the other articles in the module. introducing asynchronous javascript in this article we briefly recap the problems associated with sychronous javascript, and take a first look at some of the different asynchronous javascript techniques you'll encounter, showing how they can help u...
...And 2 more matches
Making decisions in your code — conditionals - Learn web development
for example, in a game, if the player's number of lives is 0, then it's game over. in a weather app, if it is being looked at in the morning, show a sunrise graphic; show stars and a moon if it is nighttime. in this article, we'll explore how so-called conditional statements work in javascript. prerequisites: basic computer literacy, a basic understanding of html and css, javascript first steps. objective: to understand how to use conditional structures in javascript. ...
... select.value; if (choice === 'sunny') { para.textcontent = 'it is nice and sunny outside today. ...
...ain is falling outside; take a rain coat and an umbrella, and don\'t stay out for too long.'; } else if (choice === 'snowing') { para.textcontent = 'the snow is coming down — it is freezing! best to stay in with a cup of hot chocolate, or go build a snowman.'; } else if (choice === 'overcast') { para.textcontent = 'it isn\'t raining, but the sky is grey and gloomy; it could turn any minute, so take a rain coat just in case.'; } else { para.textcontent = ''; } } here we've got an html <select> element allowing us to make different weather choices, and a simple paragraph. in the javascript, we are storing a reference to both the <select> and <p> elements, and adding an event listener to the <select> element so that when its value is changed, the setweather() functi...
...And 2 more matches
Introduction to web APIs - Learn web development
at what the different main classes of apis are, and what kind of uses they have. prerequisites: basic computer literacy, a basic understanding of html and css, javascript basics (see first steps, building blocks, javascript objects). objective: to gain familiarity with apis, what they can do, and how you can use them in your code. what are apis? application programming interfaces (apis) are constructs made available in programming languages to allow developers to create complex functionality more easily. they abstract more complex code away from you, providing some easier syntax to use in its place. as a real-world example, think about the electricity supply in your house, apartment, or other dwellings. if you want to use an appliance in your house, you simpl...
...pt tools so above, we talked about what client-side javascript apis are, and how they relate to the javascript language. let's recap this to make it clearer, and also mention where other javascript tools fit in: javascript — a high-level scripting language built into browsers that allows you to implement functionality on web pages/apps. note that javascript is also available in other programming environments, such as node. browser apis — constructs built into the browser that sits on top of the javascript language and allows you to implement functionality more easily. third-party apis — constructs built into third-party platforms (e.g. twitter, facebook) that allow you to use some of those platform's functionality in your own web pages (for example, display your latest tweets on y...
......
...And 2 more matches
Arrays - Learn web development
n the same way that you accessed the letters in a string. enter the following into your console: shopping[0]; // returns "bread" you can also modify an item in an array by simply giving a single array item a new value. try this: shopping[0] = 'tahini'; shopping; // shopping will now return [ "tahini", "milk", "cheese", "hummus", "noodles" ] note: we've said it before, but just as a reminder — computers start counting from 0! note that an array inside an array is called a multidimensional array. you can access an item inside an array that is itself inside another array by chaining two sets of square brackets together. for example, to access one of the items inside the array that is the third item inside the random array (see previous section), we could do something like this:...
... single parameter, the character you want to separate the string at, and returns the substrings between the separator as items in an array. note: okay, this is technically a string method, not an array method, but we've put it in with arrays as it goes well here. let's play with this, to see how it works. ...
...,'bella','slugger']; dognames.tostring(); // rocket,flash,bella,slugger adding and removing array items we've not yet covered adding and removing array items — let us look at this now. we'll use the myarray array we ended up with in the last section. if you've not already followed that section, create the array first in your console: let myarray = ['manchester', 'london', 'liverpool', 'birmingham', 'leeds', 'carlisle']; first of all, to add or remove an item at the end of an array we can use push() and pop() respectively. let's use push() first — note that you need to include one or more items that you want to add to the end of your array. try this: myarray.push('cardiff'); myarray; myarray.push('bradford', 'brighton'); myarray; the new length of the array is returned whe...
...And 2 more matches
Storing the information you need — Variables - Learn web development
versions of internet explorer with your code (it doesn't support let until version 11; the modern windows edge browser supports let just fine). updating a variable once a variable has been initialized with a value, you can change (or update) that value by simply giving it a different value. try entering the following lines into your console: myname = 'bob'; myage = 40; an aside on variable naming rules you can call a variable pretty much anything you like, but there are limitations. generally, you should stick to just using latin characters (0-9, a-z, a-z) and the underscore character. you shouldn't use other characters because they may cause errors or be hard to understand for an international audience. don't use underscores at the start of variable names — this is used in certai...
...ems, and so you'll get errors. note: you can find a fairly complete list of reserved keywords to avoid at lexical grammar — keywords. good name examples: age myage init initialcolor finaloutputvalue audio1 audio2 bad name examples: 1 a _12 myage myage var document skjfndskjfnbdskjfb thisisareallylongstupidvariablenameman try creating a few more variables now, with the above guidance in mind. variable types there are a few different types of data we can store in variables. in this section we'll describe these in brief, then in future articles, you'll learn about them in more detail. so far we've looked at the first two, but there are others. numbers you can store numbers in variables, either whole numbers like 30 (also called integers) or decimal numbers like 2.456 (also called...
... these in brief, then in future articles, you'll learn about them in more detail. so far we've looked at the first two, but there are others. numbers you can store numbers in variables, either whole numbers like 30 (also called integers) or decimal numbers like 2.456 (also called floats or floating point numbers). you don't need to declare variable types in javascript, unlike some other programming languages. when you give a variable a number value, you don't include quotes: let myage = 17; strings strings are pieces of text. when you give a variable a string value, you need to wrap it in single or double quote marks; otherwise, javascript tries to interpret it as another variable name. let dolphingoodbye = 'so long and thanks for all the fish'; booleans booleans are true/false value...
...And 2 more matches
Properly configuring server MIME types - Learn web development
this article may contain out of date information, as it has not been significantly updated in many years. background by default, many web servers are configured to report a mime type of text/plain or application/octet-stream for unknown content types. as new content types are invented or added to web servers, web administrators may fail to add the new mime types to their web server's configuration. this is a major source of problems for users of gecko-based browsers, which respect the mime types as reported by web servers and web applications. what are mime types? mime types describe the media type of content either in email or served by web servers or web applications and are intended to help guide a web browser in how the content is to be processed and displayed. examples of m...
...o way, according to the http specification, of knowing that the author actually intended the content to be processed and displayed in a way different from that implied by the reported mime type. some other web browsers, such as microsoft® internet explorer, try to allow for misconfigured web servers and applications by guessing what the correct mime type should be. this has sheltered many web administrators from their own errors, since internet explorer will continue to process content as expected even though the web server is misconfigured, e.g. displays an image which is reported to be plain text. 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 docu...
...ell-formed css construct; the heuristic has been removed in firefox 4, and you have to properly set the text/css mime types to have your css pages recognized. why browsers should not guess mime types apart from violating the http specification, it is a bad strategy for browsers to guess mime types for the following reasons: loss of control if the browser ignores the reported mime type, web administrators and authors no longer have control over how their content is to be processed. for example, a web site oriented for web developers might wish to send certain example html documents as either text/html or text/plain in order to have the documents either processed and displayed as html or as source code. if the browser guesses the mime type, this option is no longer available to the author...
...And 2 more matches
React interactivity: Editing, filtering, conditional rendering - Learn web development
at least), we'll add the finishing touches to the main areas of functionality in our todo list app. this includes allowing you to edit existing tasks, and filtering the list of tasks between all, completed, and incomplete tasks. we'll look at conditional ui rendering along the way. prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. objective: to learn about conditional rendering in react, and implementing list filtering and an editing ui in our app. editing the name of a task we don’t have a user interface for editing the name of a task yet. we'll get to that in a moment. to start with, we can at least implement an edittask() function in app.js. it’ll be similar to deletetask() be...
...= ( <form classname="stack-small"> <div classname="form-group"> <label classname="todo-label" htmlfor={props.id}> new name for {props.name} </label> <input id={props.id} classname="todo-text" type="text" /> </div> <div classname="btn-group"> <button type="button" classname="btn todo-cancel"> cancel <span classname="visually-hidden">renaming {props.name}</span> </button> <button type="submit" classname="btn btn__primary todo-edit"> save <span classname="visually-hidden">new name for {props.name}</span> </button> </div> </form> ); const viewtemplate = ( <div classname="stack-small"> <div classname="c-cb"> <input id={props.id} type="checkbox" defaultch...
...span classname="visually-hidden">{props.name}</span> </button> </div> </div> ); we've now got the two different template structures — "edit" and "view" — defined inside two separate constants. this means that the return statement of <todo /> is now repetitious — it also contains a definition of the "view" template. we can clean this up by using conditional rendering to determine which template the component returns, and is therefore rendered in the ui. conditional rendering in jsx, we can use a condition to change what is rendered by the browser. to write a condition in jsx, we can use a ternary operator. in the case of our <todo /> component, our condition is "is this task being edited?" change the return statement inside todo() so that it reads like so: return <li...
...And 2 more matches
Deployment and next steps - Learn web development
erview: client-side javascript frameworks in the previous article we learning about svelte's typescript support, and how to use it to make your application more robust. in this final article we will look at how to deploy your application and get it online, and also share some of the resources that you should go on to, to continue your svelte learning journey. prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line. you'll need a terminal with node + npm installed to compile and build your app. objective: learn how to prepare our svelte app for production, and what learning resources you should visit next. note that our application is ful...
... recompiling the app and refreshing the page when a change occurs. your generated bundle.js and bundle.css files will be something like this (file size on the left): 504 jul 13 02:43 bundle.css 95981 jul 13 02:43 bundle.js to compile our application for production we have to run npm run build instead. in this case, svelte won't lunch a web server or keep watching for changes. it will however minify and compress our javascript files using terser. so, after running npm run build, our generated bundle.js and bundle.css files will be more like this: 504 jul 13 02:43 bundle.css 21782 jul 13 02:43 bundle.js try running npm run build in your app's root directory now. you might get a warning, but you can ignore this for now. our whole app is now just 21 kb — 8.3 kb when gzipped. there ar...
... name: 'app', file: 'public/build/bundle.js' }, plugins: [ svelte({ // enable run-time checks when not in production dev: !production, // we'll extract any component css out into // a separate file - better for performance css: css => { css.write('public/build/bundle.css'); } }), later on in the same file you'll also see how rollup minimizes our scripts in production mode and launches a local server in development mode: // in dev mode, call `npm run start` once // the bundle has been generated !production && serve(), // watch the `public` directory and refresh the // browser on changes when not in production !production && livereload('public'), // if we're building for production (npm run build ...
...And 2 more matches
Git and GitHub - Learn web development
g issues with the code, reviewing tools, project management features such as assigning tasks and task statuses, and more. note: git is actually a distributed version control system, meaning that a complete copy of the repository containing the codebase is made on your computer (and everyone else's). you make changes to your own copy, and then push those changes back up to the server, where an administrator will decide whether to merge your changes with the master copy. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites to use git and github, you need: a desktop computer with git installed on it (see the git downloads page). a tool to use git. depe...
...course that includes all the essential information you need to work towards your goal. get started prerequisites to use git and github, you need: a desktop computer with git installed on it (see the git downloads page). a tool to use git. 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. in fact, it is probably useful for you to get to know at least the basics of git terminal commands, even if you intend to use a gui. a github account. if you haven't already got one, sign up now using the provided link. in terms of prerequisite knowledge, you don't need to know anything about web development, git/github or vcses to start this module. however, it is recommended that y...
...f you haven't already got one, sign up now using the provided link. in terms of prerequisite knowledge, you don't need to know anything about web development, git/github or vcses to start this module. however, it is recommended that you know some coding so that you have reasonable computer literacy, and some code to store in your repositories! it is also preferrable that you have some basic terminal knowledge, so for example moving between directories, creating files, and modifying the system path. note: github is not the only site/toolset you can use with git. 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. we've only stuck with github in this course to provide a single way that works. ...
...And 2 more matches
Deploying our app - Learn web development
ng the app. post development there's potentially a large range of problems to be solved in this section of the project's lifecycle. as such, it's important to create a toolchain that handles these problems in a way that requires as little manual intervention as possible. here's just a few things to consider for this particular project: generating a production build: ensuring files are minimised, chunked, have tree-shaking applied, and that versions are "cache busted". running tests: these can range from "is this code formatted properly?" to "does this thing do what i expect?", and ensuring failing tests prevent deployment. actually deploying the updated code to a live url: or potentially a staging url so it can be reviewed first. note: cache busting is a new term that we have...
...up, and we'll look at that now. the build process again, because we're using parcel for development, the build option is extremely simple to add. instead of running the server with npx parcel src/index.html, we can run it with npx parcel build src/index.html and parcel will build everything ready for production instead of just running it for development and testing purposes. this includes doing minification and tree-shaking of code, and cache-busting on filenames. the newly-created production code is placed in a new directory called dist, which contains all the files required to run the website, ready for you to upload to a server. however, doing this step manually isn't our final aim — what we want is for the build to happen automatically and the result of the dist directory to be depl...
...ll be prompted to enter a username and password before git will allow the push to be sent. this is because we used the https option rather than the ssh option, as seen in the screenshot earlier. for this you need your github username and then — if you do not have two-factor authentication (2fa) turned on — your github password. we would always encourage you to use 2fa if possible, but bear in mind that if you do, you'll also need to use a "personal access token". github help pages has an excellent and simple walkthrough covering how to get one. note: if you are interested in using the ssh option, thereby avoiding the need to enter your username and password every time you push to github, this tutorial walks you through how. this final command instructs git to push the code (aka pub...
...And 2 more matches
Mozilla accessibility architecture
a cross platform manner, and then deal with the platform differences on a consistent manner. the shared code makes itself available to the toolkit-specific code via generic xpcom interfaces that return information about objects we want to expose. all focusable nodes, tables and text have accessibility interfaces. we call these objects "accessible nodes". each of these accessible nodes supports at minimum the generic cross-platform accessibility interface nsiaccessible (which provides a text name, enumerated role identifier and a set of state flags) and sometimes additional interfaces. for example, tables support nsiaccessibletable, text supports nsiaccessibletext and edit boxes support nsieditabletext., although this code has been moved into the atk specific directories because it is not cur...
...they are fired by gecko whenever nodes in the document are created, mov...
... our isimpledomnode extension to msaa, which we implement on nsaccessnodewrap. isimpledomnode is used by the assistive technology to get access to information about individual dom nodes which may or may not be "accessible". because an nsaccessnode can point to any dom node, even dom nodes that are not "accessible", it may or may not also be an nsaccessible. in other words, the lowest common denominator for objects we must cache is nsaccessnode. nsaccessnode::init() when nsaccessibilityservice::getaccessible() gets a newly created accessible, it calls nsiaccessnode::init() on the new object, which will add this to the cache for the doc accessible. each nsaccessnode contains the dom node and weak pres shell for the object. the weak pres shell is used to create a hash key to get the doc access...
...And 2 more matches
Gecko info for Windows accessibility vendors
ogy which allows the author to specify the type of document or container. once you know that you have a document, go up the ancestor chain of windows until you see a mozillacontentwindowclass or a mozillauiwindowclass. if it is a content window, you may use accessibleobjectfromwindow() to get the root iaccessible for the content, and begin traversing the tree from there. gecko also helps determine when to load a new window by firing two event_state_change's on the root role_document accessible -- the first state change indicates the document pane is now busy loading. the second state change indicates the document pane has finished. when handling the event, use get_accstate() to check the state_busy flag. when the document has finished loading the busy flag will be cleared. msaa support: ...
...xplorer's use of it. please let us know if you find any differences not listed here: accessible relations are supported the accnavigate() method can be used with new constants defined for gecko. the results are always returned via vt_dispatch. enum { navrelation_label_for = 0x1002 }; enum { navrelation_description_for = 0x100f }; these two relations can be used on object to determine what form control is being labelled or desribed. enum { navrelation_labelled_by = 0x1003 }; enum { navrelation_described_by = 0x100e }; these two relations are they inverse; they can be used on form controls. if the form control has an accname, you can get the iaccessible that it was labelled by in order to get more formatting information. it is also useful to check for a description. ...
... hresult get_attributes( /* [in] */ unsigned short maxattribs, /* [out] */ bstr *attribnames, /* [out] */ short *namespaceid, /* [out] */ bstr *attribvalues, /* [out] */ unsigned short *numattribs); a variation on this method is get_attributesfornames, which lets turns the attribnames array into an [in] parameter, letting you specify only those attributes you're interested in. this helps minimize the cost of marshalling for those times in which you're interested in only a few attributes per node. hresult get_attributesfornames( /* [in] */ unsigned short numattribs, /* [in] */ bstr __rpc_far *attribnames, /* [in] */ short __rpc_far *namespaceid, /* [out] */ bstr __rpc_far *attribvalues); the get_computedstyle method is used to find out the cumulative, computed results for...
...And 2 more matches
Mozilla's Section 508 Compliance
8 is a new standard for defining accessibility requirements for software and other electronic and information technology. part of section 508 (§1194.21) specifically relates to mozilla, and the ability of us government agencies to buy software that contains mozilla software components. here is a detailed list of section 508 bugs in mozilla's seamonkey application suite. some of them are fairly minor. the following is provided for informational purposes only and is not a legally binding voluntary product accessibility template (vpat). here are the section 508 requirements and how far along mozilla seamonkey rv1.8a4 is with each one: requirement windows linux/unix mac os requirement windows linux...
... mostly complete. caveats: 1) although sidebar cannot be customized without a mouse, all sidebar functions that come with the browser are available through other means 2) java and in-page plugins cannot be used with the keyboard, so they must not be installed for keyboard-only users additional features for th...
... (b) applications shall not disrupt or disable activated features of other products that are identified as accessibility features, where those features are developed and documented according to industry standards. applications also shall not disrupt or disable activated features of any operating system that are identified as accessibility features where the application programming interface for those accessibility features has been documented by the manufacturer of the operating system and is available to the product developer. complete. (c) a well-defined on-screen indication of the current focus shall be provided that moves among interactive interface elements as the input focus changes. the focus shall be programmatically exposed so that a...
...And 2 more matches
A bird's-eye view of the Mozilla framework
author: susan d. tiner last updated date: 11/23/05 statement of purpose the purpose of this article is to provide a high-level technical overview of the architecture of the extensible, object-based mozilla application framework. it examines what happens when the user performs a simple user interface (ui) action such as clicking a link in the contents panel of the help viewer window shown below. the article focuses on the architecture of the overall framework supporting the mozilla application suite, not the architecture of the individual applications themselves. prerequisites this article assumes you have access to mozilla sources and are familiar with the directory structure of the source tree. the code samples in the article are based on mozilla/5.0 (windows; u; windows...
...ure of the source tree. the code samples in the article are based on mozilla/5.0 (windows; u; windows nt 5.1; en-us; rv:1.9a1) gecko/20051104 seamonkey/1.1a from a new source tree checked out 11/04/05. the build id is 2005110409. thehelp viewer files referenced in the article are located in /seamonkey/extensions/help/ this article also assumes you are familiar with the javascript and c++ programming languages, object-oriented programming (oop) terminology and design concepts, the microsoft® component object model (com), and the corba omg interface definition language (idl). organization this article first covers some conceptual groundwork, then walks through a user scenario to illustrate how key mozilla architectural components work together to support a simplehelp viewer ui action. fra...
...implementing the ui behavior a package (also known as chrome) is really just a bundling of a set of ui widgets and associated services implementing a particular application feature. chrome and extensions are examples of packages. content (dom) the mozilla document object model (dom) specifies a logical tree structure for storing ui and document content, and provides an api (application programming interface) for accessing and manipulating the content. an application such as the browser may have one or more open documents accessible via dom apis. when an html, xml, svg or other type of document is loaded, the nglayout engine (also known as gecko) parses the contents into a dom tree, and handles the layout and rendering of the document pages. the nglayout engine also parses xul ui controls ...
...And 2 more matches
Creating reftest-based unit tests
er. so, if the effect of complex markup is being tested, put that complex markup into a page and create another page that uses simple markup to achieve the same visual effect. reftest will then compare them and verify whether they produce the same bitmap. this idea can seem odd when first encountered. automated testing usually compares output against an invariant, a "gold standard", that is determined to be correct. if one has software that multiplies numbers, one wants a regression test to show that 2 * 2 continues to be calculated to be 4, not something similar to but not quite exactly 4. but an operating system does change with time. it is not invariant. and a browser may change the visual effect produced by a tag while still being compliant with relevant standards. for example, the html ...
...t it is a silly example, but this will step you through creating your first reftest. step 1 for now you must check out and build the browser in order to run the tests. see the build documentation for details on doing that. sorry about this, but the released builds and the nightly builds are built with the "--disable-tests" option and reftest will not work - see bug 369809. step 2 open a terminal window. create a directory (inside firefox's source code tree) and make that your current directory (i.e. move to that directory). step 3 create a file named foo.html with the following: <html><head><title>reftest0001</title> <body><strong>hello!</strong></body> </html> step 4 create a file named bar.html with the following: <html><head><title>reftest0001</title> <body><b>hello!</b><...
...uilt a debug version of the browser, there can be a lot of extra console output. the reftest.list file can be named whatever you want, not necessarily reftest.list (but it has to end with .list). more to do create more reftests. new tests can be added to the reftest.list file, which can contain any number of tests. the file can include other things, but it does not get very complicated. keep in mind new tests should fit a 600x600 window so we can test on mobile platforms easier. here is an example. include ../other.list == foo.html bar.html != aaa.html bbb.html the first line, as one might expect, includes another manifest. the second line should look familiar. it says that foo.html and bar.html should produce visually identical output. the third line says that aaa.html and bbb.html shou...
...And 2 more matches
Configuring Build Options
most of the time a mozconfig file is not required. the default options are the most well-supported, so it is preferable to add as few options as possible. please read the following directions carefully before building, and follow them in order. skipping any step may cause the build to fail, or the built software to be unusable. build options, including options not usable from the command-line, may appear in "confvars.sh" files in the source tree. ...
...two types of options: options prefixed with mk_add_options are passed to client.mk. the most important of these is moz_objdir, which controls where your application gets built (also known as the object directory). options prefixed with ac_add_options are passed to configure, and affect the build process. building with an objdir this means that the source code and object files are not intermingled in your directory system and you can build multiple applications (e.g., firefox and thunderbird) from the same source tree. if you do not specify a moz_objdir, it will be automatically set to @topsrcdir@/obj-@config_guess@. if you need to re-run configure, the easiest way to do it is using ./mach configure; running configure manually is strongly discouraged. adding the following line to you...
...t of space on disk. parallel compilation note: the build system automatically makes an intelligent guess for how many cpu cores to use when building. the option below is typically not needed. most modern systems have multiple cores or cpus, and they can be optionally used concurrently to make the build faster. the -j flag controls how many parallel builds will run concurrently. you will see (diminishing) returns up to a value approximately 1.5× to 2.0× the number of cores on your system. mk_add_options moz_make_flags="-j4" if your machine is overheating, you might want to try a lower value, e.g. -j1. choose an application the --enable-application=application flag is used to select an application to build. firefox is the default. choose one of the following options to add to your mo...
...And 2 more matches
Eclipse CDT
actions that follow, it will not include results for sections of the code that are ifdef'ed out by the configuration used to create your object directory. for example, if you are using a mac and you search for callers of nsdisplaylistbuilder::isintransform, the results will not include the caller in nsobjectframe.cpp because that caller is wrapped in "#ifndef xp_macosx". just something to keep in mind. ;-) to jump to the definition of a symbol (or the declaration of a symbol if already at the definition), hover over the symbol, hold down the ctrl/cmd key, move the mouse slightly to linkify the symbol, then click on it. (having to move the mouse slightly is eclipse bug 26873). alternately, you can jump to the definition of the symbol under the cursor by pressing f3. to do a c++ symbol search...
...th-python=/usr' (create an optimized build with support for python (so that you can use python to much better control when you break etc.), and install it in $home/bin). that done, open the workspace preferences, select "c/c++ > debug > gdb", and set "gdb debugger" to the full path of your new gdb executable. gdb unexpectedly detaching if gdb starts ignoring your breakpoints, or unexpectedly terminates or detaches from the firefox process, this may be caused by out of date breakpoints (breakpoints that you set during a previous debug session, after which you've since rebuilt). remove any such breakpoints and restart your debug session. known issues there are various known limitations and bugs when it comes to using eclipse with mozilla. eclipse is open source, of course so if anyone feels...
... is there a mercurial plugin for eclipse? there is mercurialeclipse, but probably most mozilla developers will just prefer to use the command line. if you t...
...And 2 more matches
Experimental features in Firefox
no beta 30 no release 30 no preference name canvas.hitregions.enabled webgl: draft extensions when this preference is enabled, any webgl extensions currently in "draft" status which are being tested are enabled for use. currently, there are no webgl extensions being tested by firefox. webgpu api this new api provides low-level support for performing computation and graphics rendering using the graphics processing unit (gpu) of the user's device or computer. the specification is still a work-in-progress. see bug 1602129 for our progress on this api. release channel version added enabled by default? nightly 73 no developer edition 73 no beta 73 no release 73 no ...
...lease channel version added enabled by default? ...
...the other gestures were added for firefox 79. compatibility panel a side panel for the page inspector that shows you information detailing your app's cross-browser compatibility status. see bug 1584464 for more details. ...
...And 2 more matches
DeferredTask.jsm
e delay will start when the current execution finishes. the task will always be executed on a different tick of the event loop, even if the delay specified on construction is zero. multiple "arm" calls within the same tick of the event loop are guaranteed to result in a single execution of the task. by design, this method doesn't provide a way for the caller to detect when the next execution terminates, or collect a result. in fact, doing that would often result in duplicate processing or logging. 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. the "finalize" method can be used in the common case of waiting for completion on shutdown. void arm(); disarm canc...
...r, thus the delay will restart from its original value in case the "arm" method is called again. void disarm(); finalize ensure that any pending task is executed from start to finish, while preventing any attempt to arm the timer again. if the task is running and the timer is armed, then one last execution from start to finish will happen again, immediately after the current execution terminates; then the returned promise will be resolved. if the task is running and the timer is not armed, the returned promise will be resolved when the current execution terminates. if the task is not running and the timer is armed, then the task is started immediately, and the returned promise resolves when the new execution terminates. if the task is not running and the timer is not armed, the me...
...nd the execution of the task starts, the task cannot be canceled anymore. it is, however, possible to arm the timer again during the execution of the task, in which case the task will need to finish before the timer is started again, thus guaranteeing a time of inactivity between executions that is at least equal to the provided delay. the "finalize" method can be used to ensure that the task terminates properly. the promise it returns is resolved only after the last execution of the task is finished. to guarantee that the task is executed for the last time, the method prevents any attempt to arm the timer again. if the timer is already armed when the "finalize" method is called, then the task is executed immediately. if the task was already running at this point, then one last execution fr...
...And 2 more matches
Creating localizable web applications
php: <?php function isrtl($locale) { $rtl_locales = array('ar', 'fa', 'he'); return in_array($locale, $rtl_locales); } ?> <html lang="<?= $locale?>" dir="<?= isrtl($locale) ? 'rtl' : 'ltr' ?>" > <body class="<?= $locale?> <?= isrtl($locale) ? 'rtl' : 'ltr' ?>"> </body> </html> notice that <body/> is given a class equal to the current locale. this is useful to add minor corrective rules to the css that apply only for selected locales. for example, for locales that tend to have longer words than english, you may want to make an element slightly wider. snippet 3. good: body.de foo, body.fr foo, body.pl foo { /* locale-specific rules for the foo element */ width: 10em; /* originally 8em */ } adapt the interaction to rtl locales right-to-left locales not o...
...n, use css to give a cue to the user that if she follows the link, she will be served english content. snippet 1. bad: <a href="http://www.mozilla.com/privacy-policy.html"><?= _('privacy policy'); ?></a> snippet 2. 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. because they contain a lot of text and localizing source html is easier), make sure to keep the code responsible for application logic separate from the localizable content. the logic of the website should not be exposed directly in the localization files, to avoid any accidental change...
...he *.po files to include the new msgids. snippet 1. bad: <?= _("view a sample persona header <b><a href=\"/static/img/persona_header_labs.jpg\">here</a></b>.");?> snippet 2. good: <?php printf(_("view a sample persona header <b><a href=\"%s\">here</a></b>."), '/static/img/persona_header_labs.jpg'); ?> snippet 3. bad: <p><?=_("if you are interested in supporting the approval process by becoming an approver, please email <a href=\"mailto:personas@mozilla.com\">personas@mozilla.com</a>.")?></p> snippet 4. good: <p><?= printf(_("if you are interested in supporting the approval process by becoming an approver, please email <a href=\"mailto:%s\">%s</a>."), 'personas@mozilla.com', 'personas@mozilla.com')?> </p> snippet 5. also good: <p><?= printf(_("if you are...
...And 2 more matches
Profiling with the Firefox Profiler
hat there was an event pending for that long. black: these indicate synchronous ipc calls. ranges ranges of time can be zoomed in on by clicking and dragging anywhere in the tracing marker or thread areas. once a range is selected, a magnifying glass appears which zooms into that range. clicking on a tracing marker will create a selection corresponding with its duration allowing for easy zooming in on interesting time ranges. as you zoom in on ranges, breadcrumbs are created allowing you to easily navigate back to previously-selected ranges or the entire profile (denoted as "full range"). tip: while zooming out to a previously-selected range deletes the narrower range, the browser back button can be used to restore the narrower range. thread timeline(s) thread/process timelines: be...
... (time) axis: the timelines go from left to right as wall clock time increases along the x axis. elements in the timeline are spaced at the sampling frequency with an attempt to align them with time. factors such as sampling or stack-walking variance and system load can lead to sampling delays which manifest as gaps in the timeline. note: because this is a sampling profiler, be cautious when examining running time that is equal to the sampling interval. for very time-sensitive profiling, you may want to consider a non-sampling profiler. y (stack) axis: the y axis is the stack depth, not the cpu activity. the change in stack height is useful to find patterns like long blocking calls (long flatlines) or very tall spiky blocks (recursive calls and js). with more experience you can read profi...
...om javascript, gecko, or system libraries. note that if some functions are not yet named properly, symbolication may not yet be finished. tip: you can right-click on a function name to get an option to copy its name to the clipboard. a significant portion of time can be spent in idle, blocking calls like waiting for events. this is ideal for a responsive application to be ready to service incoming events. there are os-specific waiting functions like ntwaitformultipleobjects seen in the example above taken on windows or mach_msg_trap on macos. tip: you can quickly go deeper into the call tree by holding down your right arrow key. alternatively, expand an entire tree segment by holding alt and clicking on the arrow to the left of the collapsed tree segment. as we progress into a more sp...
...And 2 more matches
TraceMalloc
g the shutdown log, taken from the tinderbox leak builds. this example is for macos; small modifications are needed for other platforms. # run application with shutdown logging # note: tinderbox leak tests use: python leaktest.py -- --trace-malloc malloc.log --shutdown-leaks=sdleak.log # note 2: it appears that the shutdown log is not recorded if --trace-malloc is given the - argument. ...
...use the following web page to do so. <script type="text/javascript"> var filename = window.prompt("filename to log: "); if (filename) tracemallocdumpallocations(filename); </script> one can then use the script tools/trace-malloc/diffbloatdump.pl to compare trace-malloc dumps before and after doing an action that might leak. if there are significant differences, it might be worth examining the call stacks for the destructors of the objects in question to see what is extending their lifetime. (this can be done by examining the unprocessed output of an xpcom_mem_refcnt_log, one of the nstracerefcnt logs.) you should use the --use-address argument to diffbloatdump.pl, and then the diff tree can be run through fix_linux_stack.py or fix_macosx_stack.py as needed. leaksoup leaksoup is...
... an xpcom_mem_refcnt_log, one of the nstracerefcnt logs.) you should use the --use-address argument to diffbloatdump.pl, and then the diff tree can be run through fix_linux_stack.py or fix_macosx_stack.py as needed. leaksoup leaksoup is a trace-malloc tool that analyzes the shutdown log. because this log includes the contents of heap blocks, leaksoup can analyze the graph of live objects and determine which allocations are roots (within that graph, of course -- stack allocations and global variables don't count). leaksoup also finds sets of objects that are rooted by a cycle (i.e., a set of reference counted objects that own references to each other in a cycle). however, it cannot distinguish between owning and non-owning pointers, which means that non-owning pointers that are nulled out by d...
...And 2 more matches
powermetrics
use a sample length of 5 seconds (5000 ms). change this number to get shorter or longer samples. ...
...s) wakeups (intr, pkg idle) gpu ms/s com.apple.terminal 293 447.66 274.83 120.35 221.74 firefox 84627 77.59 55.55 15.37 2.59 91.42 42.12 204.47 plugin-container 84628 377.22 37.18 43.91 18.56 178.65 75.85 17.29 terminal 694 9.86 79.94 0.00 0.00 4.39 2.20 0.00 powermetrics 84694 1.21 31.53 0.00 0.00 0.20 0.20 0.00 com.google.chrome 489 233.83 48.10 25.95 0.00 google chrome helper 84688 181.57 92.81...
... safari. the grouping of parent and child processes (in coalitions) is obvious. the meaning of the columns is as follows. name: coalition/process name. process names within coalitions are indented. id: coalition/process id number. cpu ms/s: cpu time used by the coalition/process, per second, during the sample period. the sum of the process values typically exc...
...And 2 more matches
A brief guide to Mozilla preferences
it provides a general overview of mozilla preferences, including where preferences are stored, a file-by-file analysis of preference loading sequence, and information on editing preferences. what is a preference? a preference is any value or defined behavior that can be set (presumably, one setting is preferable to another). preference changes via user interface usually take effect immediately. the values are saved to the user profile (in prefs.js), for both firefox and thunderbird. a preference is read from a file, and can call up to four methods: pref(), user_pref(), sticky_pref() and lockpref(). ...
... load the config file. load user pref files, first prefs.js, then user.js . preference conflicts are resolved in favor of the last entry; for example, user.js takes precedence over prefs.js . if the application encounters any error during loading of a default pref file, the application will issue a warning that a configuration file has failed to load and then quit. this allows system administrators to know quickly if there is a configuration error in the installation. if the application encounters an error when loading user pref files, the application will issue a warning but will continue running. preferences saving usually when the user specifically commits a preference change via user interface such as the preferences dialog, the application saves the change by overwriting p...
...e as the default. modifying preferences advanced users can set named preferences via the advanced preferences editor, by typing about:config in the location bar. this ui is not recommended for most users. 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
About NSPR
history a good portion of the library's purpose, and perhaps the primary purpose in the gromit environment, was to provide the underpinnings of the java vm, more or less mapping the sys layer that sun defined for the porting of the java vm to various platforms. ...
...econd generation".) many of the concepts have been reformed, expanded, and matured. today nspr may still be appropriate as the platform dependent layer under java, but its primary application is supporting clients written entirely in c or c++. how it works nspr's goal is to provide uniform service over a wide range of operating system environments. it strives to not export the lowest common denominator, but to exploit the best features of each operating system on which it runs, and still provide a uniform service across a wide range of host offerings. threads threads are the major feature of nspr. the industry's offering of threads is quite sundry. nspr, while far from perfect, does provide a single api to which clients may program and expect reasonably consistent behavior. the operating ...
...at the systems offer as it can. it is a goal of nspr that nspr impose as little overhead as possible in accessing those appropriate system features. thread synchronization thread synchronization is loosely based on monitors as described by c.a.r. hoare in monitors: an operating system structuring concept , communications of the acm, 17(10), october 1974 and then formalized by xerox' mesa programming language ("mesa language manual", j.g. mitchell et al, xerox parc, csl-79-3 (apr 1979)). this mechanism provides the basic mutual exclusion (mutex) and thread notification facilities (condition variables) implemented by nspr. additionally, nspr provides synchronization methods more suited for use by java. the java-like facilities include monitor reentrancy, implicit and tightly bound notificatio...
...And 2 more matches
Optimizing Applications For NSPR
netscape portable runtime (nspr) tries to provide a consistent level of service across the platforms it supports. this has proven to be quite challenging, a challenge that was met to a large degree, but there is always room for improvement. the casual client may not encounter a need to know the details of the shortcomings to the level described here, but if and when clients become more sophisticated, these issues will certainly surface. this memo is by no way complete. multiplatform do not call any blocking system call from a local thread. the only exception to this rule is the <tt>select()</tt> and <tt>poll()</tt> system calls on unix, both of which nspr has overridden to make sure they are aware of the nspr local threads. in the combined (mxn) model, which includes nt, irix (sp...
...preemptable. as usual, it isn't that we couldn't preempt them, but rather that the macintosh libraries are not prepared for such things to happen. nspr does take advantage of macintosh' asynchronous i/o capability to perform scheduling during i/o. still, there is no enforceable mechanism to guarantee thread scheduling fairness. calendar time facilities are limited on macintosh. one can only determine the immediate setting of daylight savings time, not what it would be at some arbitrary time in the past or the future. initialization of nspr may fail if the host is not connected to a network of some kind. win-16 http://www.sybase.com/products/languages/watccpl.html the win-16 port is unique in the nspr world in that it uses the watcom development environment. this environment does bring a...
...eans that nspr threads use a shadow stack to preserve context across a thread switch. at thread switch time, the stack of the current running thread is copied to other storage associated with that thread and the about-to-be-dispatched thread's stack data is copied back onto the windows stack just before the thread is given control. this has disastrous implications on the generally accepted programming practice of taking the address of a stack variable and giving that address to another thread. consider that the windows stack is swapped in and out with each thread switch. the thread that created a stack variable sees his own stack variables correctly across thread switches. however, another thread does not see the data as intended because the stack has been swapped out to the shadow stack and...
...And 2 more matches
NSS 3.21 release notes
distribution information the hg tag is nss_3_21_rtm. nss 3.21 requires nspr 4.10.10 or newer. ...
...n secmod.h secmod_createmoduleex - create a new secmodmodule structure from module name string, module parameters string, nss specific parameters string, and nss configuration parameter string. the module represented by the module structure is not loaded. the difference with secmod_createmodule is the new function handles nss configuration parameter strings. ...
...km_tls12_master_key_derive ck_tls12_key_mat_params{_ptr} - parameters {or pointer} for ckm_tls12_key_and_mac_derive ck_tls_kdf_params{_ptr} - parameters {or pointer} for ckm_tls_kdf ck_tls_mac_params{_ptr} - parameters {or pointer} for ckm_tls_mac in sslt.h sslhashtype - identifies a hash function sslsignatureandhashalg - identifies a signature and hash function sslpreliminarychannelinfo - provides information about the session state prior to handshake completion new macros in nss.h nss_rsa_min_key_size - used with nss_optionset and nss_optionget to set or get the minimum rsa key size nss_dh_min_key_size - used with nss_optionset and nss_optionget to set or get the minimum dh key size nss_dsa_min_key_size - used with nss_optionset and nss_opti...
...And 2 more matches
NSS Sample Code Utilities_1
port_free(phrases); return null; } if (slot) { tokenname = pk11_gettokenname(slot); if (tokenname) { tokenlen = port_strlen(tokenname); } } i = 0; do { int startphrase = i; int phraselen; /* handle the windows eol case */ while (phrases[i] != '\r' && phrases[i] != '\n' && i < nb) i++; /* terminate passphrase */ phrases[i++] = '\0'; /* clean up any eol before the start of the next passphrase */ while ( (i<nb) analyze="" char="" current="" getmodulepassword="" if="" int="" now="" passphrase="" phrase="&amp;phrases[startphrase];" phraselen="" pk11slotinfo="" pwdata="=" pwdata-="" retry="" return="" secupwdata="" the="" void="" while="">source != pw_none) { p...
... } pr_fprintf(pr_stderr, "password check failed: no password found.\n"); return null; } /* * generaterandom */ secstatus generaterandom(unsigned char *rbuf, int rsize) { char meter[] = { "\r| |" }; int fd, count; int c; secstatus rv = secsuccess; cc_t orig_cc_min; cc_t orig_cc_time; tcflag_t orig_lflag; struct termios tio; fprintf(stderr, "to generate random numbers, " "continue typing until the progress meter is full:\n\n"); fprintf(stderr, "%s", meter); fprintf(stderr, "\r|"); /* turn off echo on stdin & return on 1 char instead of nl */ fd = fileno(stdin); tcgetattr(fd, &tio); orig_...
...; tcflag_t orig_lflag; struct termios tio; fprintf(stderr, "to generate random numbers, " "continue typing until the progress meter is full:\n\n"); fprintf(stderr, "%s", meter); fprintf(stderr, "\r|"); /* turn off echo on stdin & return on 1 char instead of nl */ fd = fileno(stdin); tcgetattr(fd, &tio); orig_lflag = tio.c_lflag; orig_cc_min = tio.c_cc[vmin]; orig_cc_time = tio.c_cc[vtime]; tio.c_lflag &= ~echo; tio.c_lflag &= ~icanon; tio.c_cc[vmin] = 1; tio.c_cc[vtime] = 0; tcsetattr(fd, tcsaflush, &tio); /* get random noise from keyboard strokes */ count = 0; while (count < rsize) { c = getc(stdin); if (c == eof) { rv = secfailure; break; } ...
...And 2 more matches
Utilities for nss samples
port_free(phrases); return null; } if (slot) { tokenname = pk11_gettokenname(slot); if (tokenname) { tokenlen = port_strlen(tokenname); } } i = 0; do { int startphrase = i; int phraselen; /* handle the windows eol case */ while (phrases[i] != '\r' && phrases[i] != '\n' && i < nb) i++; /* terminate passphrase */ phrases[i++] = '\0'; /* clean up any eol before the start of the next passphrase */ while ( (i<nb) && (phrases[i] == '\r' || phrases[i] == '\n')) { phrases[i++] = '\0'; } /* now analyze the current passphrase */ phrase = &phrases[startphrase]; if (!tokenname) break; if (port_strncmp(phrase, to...
... } pr_fprintf(pr_stderr, "password check failed: no password found.\n"); return null; } /* * generaterandom */ secstatus generaterandom(unsigned char *rbuf, int rsize) { char meter[] = { "\r| |" }; int fd, count; int c; secstatus rv = secsuccess; cc_t orig_cc_min; cc_t orig_cc_time; tcflag_t orig_lflag; struct termios tio; fprintf(stderr, "to generate random numbers, " "continue typing until the progress meter is full:\n\n"); fprintf(stderr, "%s", meter); fprintf(stderr, "\r|"); /* turn off echo on stdin & return on 1 char instead of nl */ fd = fileno(stdin); tcgetattr(fd, &tio); orig_...
...; tcflag_t orig_lflag; struct termios tio; fprintf(stderr, "to generate random numbers, " "continue typing until the progress meter is full:\n\n"); fprintf(stderr, "%s", meter); fprintf(stderr, "\r|"); /* turn off echo on stdin & return on 1 char instead of nl */ fd = fileno(stdin); tcgetattr(fd, &tio); orig_lflag = tio.c_lflag; orig_cc_min = tio.c_cc[vmin]; orig_cc_time = tio.c_cc[vtime]; tio.c_lflag &= ~echo; tio.c_lflag &= ~icanon; tio.c_cc[vmin] = 1; tio.c_cc[vtime] = 0; tcsetattr(fd, tcsaflush, &tio); /* get random noise from keyboard strokes */ count = 0; while (count < rsize) { c = getc(stdin); if (c == eof) { rv = secfailure; break; } ...
...And 2 more matches
Notes on TLS - SSL 3.0 Intolerant Servers
this is the main symptom of the problem when mozilla based browsers encounter tls/ssl 3.0 intolerant servers. cause there are some number of web servers in production today which incorrectly implement the ssl 3.0 specification. ...
...e was no version higher than 3.0 from which to be rolled back. tls is now available and used, and products that have implemented the roll-back detection incorrectly are not interoperable with tls/ssl spec-compliant clients. normally the servers which have this problem are not equipped to deal with the tls protocol, but instead of rolling back to ssl 3.0 as the rollback provision provides, they terminate/drop the connection, thus resulting in most cases a blank page display. for up-to-date information, you can read a bugzilla bug report which keeps track of this problem with mozilla-based browsers. see bug 59321. servers currently known to exhibit this intolerant behavior as of this writing, this problem has been reported for the following servers: (wherever there is an upgraded version whi...
...te information, you can read a bugzilla bug report which keeps track of this problem with mozilla-based browsers. see bug 59321. servers currently known to exhibit this intolerant behavior as of this writing, this problem has been reported for the following servers: (wherever there is an upgraded version which fixes the problem, it is indicated by an asterisked remark in the parentheses. ) domino-go-webserver/4.6.2.6 (and perhaps some later versions) ibm_http_server/1.3.6.3 or earlier (* update to 1.3.6.4) ibm_http_server/1.3.12.1 or earlier (* update to 1.3.12.2) java web server 2 osu/3.2 - decthreads http server for openvm stronghold/2.2 webmail v. 3.6.1 by infinite technologies (* update available) n.b. there might be servers other than those listed above which exhibit this pr...
...And 2 more matches
SpiderMonkey Build Documentation
able-debug --disable-optimize # use "mozmake" on windows make you can also build debug builds of spidermonkey with the js_gc_zeal option, which adds a new built-in function to spidermonkey that lets you configure zealous garbage collection. this can help debug memory leaks and other memory-related problems. see js_setgczeal() for details. ...
...o be able to build!) windows builds since version 28, threadsafe builds are the default, and should work out of the box on all posix platforms. hence, the following instructions should only be relevant if you're on windows or compiling an older version of spidermonkey. the mozillabuild batch file you used to open your shell (e.g. start-shell-msvc2013.bat or start-shell-msvc2013-x64.bat) determines whether the compiler toolchain will target 32-bit or 64-bit builds. to create a 64-bit build, note that you must configure with --target=x86_64-pc-mingw32 --host=x86_64-pc-mingw32. since the posix nspr emulation is not available for windows, a working version of nspr must be available to your build. the easiest option is to configure with --enable-nspr-build. this configure option builds the i...
...h --enable-nspr-build. this configure option builds the in-tree version of nspr which is probably what you want; because spidermonkey uses newer nspr symbols, the nspr that ships with your operating system probably does not work. 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. ...
...And 2 more matches
Garbage collection
a cell is the unit of memory that is allocated and collected by the gc, as used externally. in other words, from the point of view of the rest of the engine, the job of the gc is to allocate cells and automatically collect them. cell is the base class for all classes that are allocated by the gc, e.g., jsobject. allocation kind cells are classified by allocation kind. the allocation kind determines the size of the object and the finalization behavior. allocation kind is defined by enum allockind. arenas always hold objects of the same allocation kind. thus, an arena holds objects all of the same size and finalization behavior. compartments the js heap is partitioned into compartments. some key properties of compartments are: every cell (js heap object) belongs to at most one compart...
...ous sequence of free cells [first,last] within an arena. freespan contains functions to allocate from the free span. mark bitmap the mark bitmap is represented by chunkbitmap. the mark bitmap has two bits per gc cell, so that it can represent both regular liveness marking ("marked black") as well as reachability from cycle-collected objects ("marked gray"). mark bits are allocated based on the minimum cell size, thus an object comprised of larger cells consumes multiple bits in the bitmap (but only uses two of them.) exact stack rooting api note: the information here is about the implementation of gc roots and their use within spidermonkey. for information on how the rooting apis should be used by embedders, read: gc rooting guide. this information has been split out into a separate a...
...o allocate and release chunks. there are also functions to commit or decommit memory, i.e., tell the os that certain pages are not being used and can be thrown away instead of paged to disk. gc/root.h defines classes for noting variables as gc roots. gc/statistics.{h,cpp} defines struct statistics, which stores spidermonkey gc performance counters. dictionary of terms black in common cs terminology, an object is black during the mark phase if it has been marked and its children are gray (have been queued for marking). an object is black after the mark phase if it has been marked. in spidermonkey, an object is black if its black mark bit is set. gray in common cs terminology, an object is gray during the mark phase if it has been queued for marking. in spidermonkey, an object is queue...
...And 2 more matches
Tracing JIT
nanojit which is co-maintained between adobe and mozilla, and a spidermonkey-specific high level component called jstracer. the nanojit component is language agnostic, and contains no knowledge about spidermonkey or any other part of the mozilla codebase. the jstracer component consists of a monitor and a recorder. the monitor watches the executing spidermonkey interpreter. when the monitor determines that the interpreter has entered a region of code that would benefit from native compilation, the monitor activates the recorder. the recorder records the activity of the interpreter, using nanojit to build an efficient, native representation of the execution called a fragment. the monitor then calls into the native code stored in the fragment. a schematic diagram of the components of the trac...
...form the lins values into nins values. nanojit/fragmento.* the nanojit/fragment.cpp and nanojit/fragmento.cpp files define the fragment and fragmento classes. a fragmento is a resource-management object that allocates and stores a set of fragments and pages, and manages their lifecycle. a fragmento owns its associated fragments. a fragment represents a single linear code sequence, typically terminating in a jump to another fragment or back to the beginning of the fragment. a fragment's code is stored in a set of associated pages and guardrecords allocated from the fragment's owning fragmento. a fragment initially holds no pages. as the compilation pipeline inserts lir instructions (lins values) into the fragment, it allocates pages to store the lir code. later, when the fragment is assembl...
... that program control can flow from one fragment into another, or back out of generated code and into the interpreter. an assembler is the only component of the tracing jit that reads or writes native code. therefore an assembler contains several machine-specific methods which are implemented in the accompanying nanojit/native*.* files. an assembler runs in a single pass over its input, transforming one lins value to zero or more nins values. it is important to keep in mind that this pass runs backwards from the last lins in the input lir code to the first, generating native code in reverse. running backwards sometimes makes the logic difficult to follow, but it is an essential factor in maintaining the assembler's high speed and small size. in the spidermonkey tracing jit there is only ev...
...And 2 more matches
Gecko events
is supported: yes event_document_reload the document contents are being reloaded. is supported: yes event...
... is supported: yes event_document_reload the document contents are being reloaded. is supported: yes event_document_load_stopped the loading of the docu...
... is supported: yes event_document_reload the document contents are being reloaded. is supported: yes event_document_load_stopped the loading of the document was interrupted. is supported: yes event_...
...And 2 more matches
Aggregating the In-Memory Datasource
introduction you can use xpcom aggregation1 with the in-memory datasource. why would you want to do this? say you were writing a datasource2, and the way you chose to implement it was to "wrap" the in-memory datasource; i.e., myclass : public nsimyinterface, public nsirdfdatasource { private: nscomptr<nsirdfdatasource> minner; public: // nsirdfdatasource methods ns_imethod init(const char* auri) { return minner->init(auri); } ns_imethod geturi(char* *auri) { return minner->geturi(auri); } // etc., for each method in nsirdfdatasource! }; very painful, prone to errors, and fragile as the interfaces are still in flux (a wee bit). aggregation to the rescue! here are the gory details on how. when it won't work although this magic is terribly co...
...esumably so that it can be aggregated with other information or displayed as styled content). technical details as before, have an nscomptr as your delegate, but this time around,don't derive from nsirdfdatasource. also, instead of keeping an nscomptr<nsirdfdatasource>, you'll just want an nscomptr<nsisupports>: class myclass : public nsimyinterface { ... private: nscomptr<nsisupports> minner; }; construct the datasource delegate when your object is constructed (or, at worst, when somebody qi's for it): rv = nscomponentmanager::createinstance( krdfinmemorydatasourcecid, this, /* the "outer" */ nscomtypeinfo<nsisupports>::getiid(), getter_addrefs(minner)); note passing this as the "outer" parameter. now, if the in-memory datasource's implementat...
...for ex...
...And 2 more matches
Avoiding leaks in JavaScript XPCOM components
uch a memory allocation system are: memory should be returned to the heap when the program no longer needs it (or soon thereafter) so that the amount of memory consumed by the program does not increase. programs should not dereference pointers pointing to memory that has been returned to the heap (and potentially reused). meeting both requirements at the same time can be tricky. many programming languages guarantee a solution for (2) and handle all the heap management for the programmer. however, this doesn't mean that (1) is also solved. the most common strategies for managing heap allocation are the following: malloc and free (or new and delete) the simplest strategy for heap allocation is that the programmer makes one function call to request memory from the heap and another one t...
...ammer makes one function call to request memory from the heap and another one to return it. in c, these are malloc and free. in c++, they're new and delete. if the programmer forgets to return the memory to the heap, it leaks. if the programmer accesses the memory after returning it to the heap, the program will access whatever happens to be at that location, and will likely either behave nondeterministically or crash. with this strategy, a single pointer to the object is considered the "owner" of the object and the object is deleted through that pointer. it's difficult to use this strategy when there are multiple pointers to a given object and it's uncertain which one will need to last the longest. reference counting reference counting is a simple solution to the problem of allowing multip...
...me point or ensure that the cycle is never created in the first place by making one of the pointers not own a reference (which carries the potential for crashes just like malloc and free). the potential causes of leaks with garbage collection (the next strategy) also apply to reference counting as well. garbage collection garbage collection is generally used to refer to algorithms that (1) determine which objects are still needed by starting from a set of roots and finding all objects reachable from those objects and (2) returning all remaining objects to the heap. the roots include things like global variables and variables on the current call stack. mozilla's javascript engine uses one of the most common garbage collection algorithms, mark and sweep, in which the garbage collector clears ...
...And 2 more matches
Creating the Component Code
in xpcom, all of these classes also derive from the nsisupports base interface. digging in: required includes and constants let's take a look at the first several lines of code in the component and discuss what they mean in xpcom. the includes and definitions at the top of an xpcom source file can give you an idea about some of the data types and techniques we'll be discussing more in the upcoming chapters. for example, mozilla_strict_api is a variable that shields you from certain private, non-xpcom headers. for example, including nsicomponentmanager.idl without mozilla_strict_api defined will include the following headers, which are not supported across versions (unfrozen): nscomponentmanagerutils.h nscomponentmanagerobsolete.h these variables are picked up by files that do not s...
...ing and also provides a graphical user interface if you'd rather point and click. or you can use one of the special "bots" on irc in #developers, where you can also get help from human beings. irc irc.mozilla.org /join #developers /msg firebot uuid this command makes the bot generate and return a uuid, which you can then copy into your component source code. now that we've looked at the preliminaries, it's time to discuss the classes that this module provides and the way that they define the relationships of the component in xpcom. coding for the registration process when xpcom discovers your component for the first time (via xpinstall or regxpcom, both of which are discussed in component installation overview), the first thing it tries to do is load your library and find the symbol ns...
...any one time setup functionality. the registerself call allows your component to tell xpcom exactly what it supports. note that whatever you do in registerself should be undone in unregisterself. first, the nsgetmodule entry point is called in your component library, and it returns an interface pointer to a nsimodule implementation. then xpcom calls registerself, passing parameters that we'll examine here. the registerself method the first parameter is the nsicomponentmanager, which provides a kind of entry point into managing the registration process. you can queryinterface it in order to obtain access to the other component management interfaces described below. the many faces of the xpcom component manager the three core component management interfaces, nsicomponentmanager, nsiservic...
...And 2 more matches
Observer Notifications
low you to modify headers and such. see this code snippet to learn how to get the tab that issued the request. http-on-opening-request similar to http-on-modify-request, but called earlier (synchronously during the channel's asyncopen() call), and some channel attributes (proxyinfo) may be missing. use only if your observer must be called before asyncopen returns. ...
...chronously during the channel's asyncopen() call), and some channel attributes (proxyinfo) may be missing. use only if your observer must be called before asyncopen returns. http-on-examine-response called after a response has been received from the web server. headers are available on the channel. the response can be accessed and modified via nsitraceablechannel. http-on-examine-cached-response called instead of http-on-examine-response when a response will be read completely from the cache. headers are available on the channel. http-on-examine-merged-response called instead of http-on-examine-response when a response will be read partially from cache, and partially from the network (http 206 or 304 response). headers are available on the channel. ...
...(added, changed, cleared, or deleted) cookie-rejected called when the setting of a cookie was rejected by the browser (per the user's preferences) http-on-response-set-cookie this is fired only when a cookie is created due to the presence of set-cookie header in the response header of any network request. this notification will come only after the "http-on-examine-response" is fired, but it will not always appear. download manager these topics indicate that events related to the download manager have occurred. topic description download-manager-ui-done called when the list of downloads in the download manager windows finishes updating. this can happen multiple times, such as when the window first opens, when multiple ...
...And 2 more matches
nsIDocShell
uri(in nsiuri auri); void suspendrefreshuris(); void tabtotreeowner(in boolean forward, out boolean tookfocus); attributes attribute type description allowauth boolean certain dochshells (like the message pane) should not throw up auth dialogs because it can act as a password trojan. allowdnsprefetch boolean attribute that determines whether dns prefetch is allowed for this subtree of the docshell tree. defaults to true. setting this will make it take effect starting with the next document loaded in the docshell. allowimages boolean attribute stating whether or not images should be loaded. allowjavascript boolean whether to allow javascript execution. allowmedia boolean attribut...
...e underlying content changes. read only. currentdocumentchannel nsichannel gets the channel for the currently loaded document, if any. for a new document load, this will be the channel of the previous document until after onlocationchange fires. read only. documentcharsetinfo nsidocumentcharsetinfo the document character set info. this is used by a load to determine priorities for charset detection and so on. obsolete since gecko 12.0 note: the properties of the old nsidocumentcharsetinfo interface were merged into nsidocshell in gecko 12.0. eldestpresshell nsipresshell presentation shell for the oldest document, if this docshell is currently transitioning between documents. read only. native code only! forcedchars...
... history. read only. isactive boolean indicates whether or not the docshell is currently active. an active docshell is one that is currently visible, which means it's not a good candidate for optimizations such as image frame discarding. docshells are active if this is true, which is the default state. note: starting in gecko 8.0, isactive is false for documents in minimized windows. isapptab boolean sets whether a docshell is an app tab. an app tab docshell may behave differently than a non-app tab docshell in some cases, such as when handling link clicks. docshells are not app tabs unless told otherwise. isexecutingonloadhandler boolean returns true if the docshell is currently executing the onload handler. read only. ...
...And 2 more matches
nsIHttpChannelInternal
internal.idlscriptable an internal interface for http channels. using features exposed by this interface is not recommended, as it will change in unpredictable ways. 66 introduced gecko 1.0 inherits from: nsisupports last changed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) method overview void getrequestversion(out unsigned long major, out unsigned long minor); void getresponseversion(out unsigned long major, out unsigned long minor); void httpupgrade(in acstring aprotocolname, in nsihttpupgradelistener alistener); void setcookie(in string acookieheader); void setupfallbackchannel(in string afallbackkey); attributes attribute type description canceled boolean returns true if and only if the channel has been canceled. read only. ...
...f8string the local ip address to which the channel is bound, in the same format produced by pr_netaddrtostring(). this may be either an ipv4 or ipv6 address. note: if network address translation (nat) is in effect, this may not be the same address the remote host thinks it is talking to. this may throw an ns_error_not_available exception if accessed when the channel's endpoints haven't been determined yet, or any time the nsihttpactivityobserver.isactive attribute is false. see bug 534698 and bug 526207. read only. localport print32 the local port number to which the channel is bound. this may throw an ns_error_not_available exception if accessed when the channel's endpoints haven't been determined yet, or any time the nsihttpactivityobserver.isactive attribute is false. see bug 534698 a...
...ug 534698 and bug 526207. read only. proxyinfo nsiproxyinfo get the proxy info in use by the channel. read only. obsolete since gecko 1.9 remoteaddress autf8string the ip address of the remote host to which this channel is bound, in the same format produced by pr_netaddrtostring(). this may throw an ns_error_not_available exception if accessed when the channel's endpoints haven't been determined yet, or any time the nsihttpactivityobserver.isactive attribute is false. see bug 534698 and bug 526207. read only. remoteport print32 the remote port number to which the channel is bound. this may throw an ns_error_not_available exception if accessed when the channel's endpoints haven't been determined yet, or any time the nsihttpactivityobserver.isactive attribute is false. see bug 534698...
...And 2 more matches
nsIMemory
t changed in gecko 0.9.6 nsimemory is used to allocate and deallocate memory segments from a heap. the implementation is free to define the heap. ns_getmemorymanager returns the global nsimemory instance. method overview voidptr alloc(in size_t size); violates the xpcom interface guidelines void free(in voidptr ptr); violates the xpcom interface guidelines void heapminimize(in boolean immediate); boolean islowmemory(); deprecated since gecko 2.0 voidptr realloc(in voidptr ptr, in size_t newsize); violates the xpcom interface guidelines methods alloc allocates a block of memory of a particular size. voidptr alloc( in size_t size ); parameters size the size of the block to allocate. return value if the memory cannot be alloc...
... of an out-of-memory condition), null is returned. otherwise, it returns a pointer to the newly allocated memory segment. the result must be freed with a call to free() when it is no longer needed. free frees a previously allocated block of memory. void free( in voidptr ptr ); parameters ptr the address of the memory block to free. this may be null, in which case nothing happens. ...
...t be freed with a call to free() when it is no longer needed. free frees a previously allocated block of memory. void free( in voidptr ptr ); parameters ptr the address of the memory block to free. this may be null, in which case nothing happens. heapminimize() attempts to shrink the size of the heap. a particular nsimemory instance may choose not to implement this method. void heapminimize( in boolean immediate ); parameters immediate if true, heap minimization will occur immediately if the call was made on the main thread. if false, the flush will be scheduled to happen when the app is idle. islowmemory determine if we are in a low-memory situation (what constitutes low-memory is platform dependent). this can be used to trigger the memory pressure observers. note...
...And 2 more matches
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. method overview void init(in astring id, in astring version, in astring installlocationkey, in astring minappversion, in astring maxappversion, in astring name, in astring downloadurl, in astring xpihash, in astring iconurl, in astring updateurl, in astring updatekey, in long type, in astring targetappid); attributes attribute type description iconurl astring the url of the icon that can be shown for this item. read only. id astring the guid of the ...
... iconurl astring the url of the icon that can be shown for this item. read only. id astring the guid of the item. read only. installlocationkey astring the name of the install location where this item is installed. read only. maxappversion astring the maximum version of the application that this item works with, in fvf format. read only. minappversion astring the minimum version of the application that this item works with, in fvf format. read only. name astring the name of this item. read only. objectsource astring returns a js object source representing an nsiupdateitem. read only. targetappid astring the target application id used for checking compatibility for this item. ...
... type_multi_xpi 0x20 type_addon type_extension + type_theme + type_locale + type_plugin type_extension + type_theme + type_locale type_any type_app + type_addon 0xff type_plugin 0x10 methods init() initializes the object. ...
...And 2 more matches
nsIZipWriter
el from which to get the data. aqueue if true, the operation is queued for later execution. if false, the operation is performed immediately. will be performed when processqueue() is called. exceptions thrown ns_error_not_initialized no zip file is open. ns_error_file_already_exists the specified path already exists in the zip file. ns_error_in_progress the zip writer is already performing another operation. addentrydirectory() adds a new directory entry to the zip file. if azipentry does not end with "/" then it will be added. note: although it is not necessary to add directory entries in order to add file entries within them, some zip utilities may have problems with that, so it may be best to add the directory entries explicitly first. void addentrydirectory( in autf8str...
... of the entry in microseconds. aqueue if true, the operation is queued for later execution. if false, the operation is performed immediately. will be performed when processqueue() is called. exceptions thrown ns_error_not_initialized no zip file is open. ns_error_file_already_exists the specified path already exists in the zip file. ns_error_in_progress the zip writer is already performing another operation. addentryfile() adds a new file or directory to the zip file. if the specified file is a directory, this call is equivalent to: addentrydirectory(azipentry, afile.lastmodifiedtime, aqueue); void addentryfile( in autf8string azipentry, in print32 acompression, in nsifile afile, in boolean aqueue ); parameters azipentry the path of the file entry to add to the...
...he data and modification time. aqueue if true, the operation is queued for later execution. if false, the operation is performed immediately. will be performed when processqueue() is called. exceptions thrown ns_error_not_initialized no zip file is open. ns_error_file_already_exists the specified path already exists in the zip file. ns_error_in_progress the zip writer is already performing another operation. ns_error_file_not_found if file does not exist. addentrystream() adds data from an input stream to the zip file. void addentrystream( in autf8string azipentry, in prtime amodtime, in print32 acompression, in nsiinputstream astream, in boolean aqueue ); parameters azipentry the path of the file entry to add to the zip file. this is the path it will be loca...
...And 2 more matches
Drawing and Event Handling - Plugins
« previousnext » this chapter tells how to determine whether a plug-in instance is windowed or windowless, how to draw and redraw plug-ins, and how to handle plug-in events. when it comes to determining the way a plug-in instance appears in a web page, you (and the web page author) have many options. the content provider who writes the web page determines its display mode: whether the plug-in is embedded, or displayed in its own separate page. you determine whether a plug-in is windowed or windowless by the way you define the plug-in itself. a windowed plug-in is drawn into its own native window (or portion of a native window) on a web page. ...
... a windowless plug-in does not require a native window. it is drawn in a target called a drawable, which corresponds to either the browser window or an off-screen bitmap. a drawable can be defined in several ways, depending on the platform. ...
... does not require a native window. it is drawn in a target called a drawable, which corresponds to either the browser window or an off-screen bitmap. a drawable can be defined in several ways, depending on the platform. windowless plug-ins can be opaque or transparent. a windowless plug-in draws itself only in response to a paint message from the browser. for information about the way html determines plug-in display mode, see using html to display plug-ins. note: windowless plug-ins were not supported on the x window system platform prior to gecko 1.9 alpha 7 (bug 137189). the npwindow structure when a plug-in is loaded, it is drawn into a target area. this target is either the windowed plug-in's native window, or the drawable of a windowless plug-in. the npwindow structure represents ...
...And 2 more matches
Debugger.Object - Firefox Developer Tools
bject, and place its own properties on a debugger.object instance to store metadata about particular debuggee objects. javascript code in different compartments can have different views of the same object. for example, in firefox, code in privileged compartments sees content dom element objects without redefinitions or extensions made to that object’s properties by content code. (in firefox terminology, privileged code sees the element through an “xray wrapper”.) to ensure that debugger code sees each object just as the debuggee would, each debugger.object instance presents its referent as it would be seen from a particular compartment. this “viewing compartment” is chosen to match the way the debugger came across the referent. as a consequence, a single debugger instance may actua...
... accessor properties of the debugger.object prototype a debugger.object instance inherits the following accessor properties from its prototype: proto the referent’s prototype (as a new debugger.object instance), or null if it has no prototype. this accessor may throw if the referent is a scripted proxy or some other sort of exotic object (an opaque wrapper, for example). class a string naming the ecmascript [[class]] of the referent. callable true if the referent is a callable object (such as a function or a function proxy); false otherwise. name the name of the referent, if it is a named function. if the referent is an anonymous function, or not a function at all, this is undefined. this accessor returns whatever name appeared after the function keyword in the source code, r...
...ion, or not a function at all, returns undefined instead. isgeneratorfunction if the referent is a debuggee function, returns true if the referent was created with a function* expression or statement, or false if it is some other sort of function. if the referent is not a debuggee function, or not a function at all, this is undefined. ...
...And 2 more matches
DOM allocation example - Firefox Developer Tools
this article describes a very simple web page that we'll use to illustrate some features of the memory tool. you can try out the site at https://mdn.github.io/performance-scenarios/dom-allocs/alloc.html. ...
... this article describes a very simple web page that we'll use to illustrate some features of the memory tool. you can try out the site at https://mdn.github.io/performance-scenarios/dom-allocs/alloc.html. ...
...icle describes a very simple web page that we'll use to illustrate some features of the memory tool. you can try out the site at https://mdn.github.io/performance-scenarios/dom-allocs/alloc.html. ...
...And 2 more matches
Migrating from Firebug - Firefox Developer Tools
es firebug lets you toggle the css pseudo-classes :hover, :active and :focus for an element via the options menu of the style side panel. in the devtools there are two ways to do the same. the first one is to toggle them via the pseudo-class panel within the rules side panel. the second one is to right-click and element within the node view and toggle the pseudo-classes via the context menu. examine css shorthand properties css shorthand properties can be split into their related longhand properties by setting the option expand shorthand properties within the style side panel. the devtools' rules panel is a bit smarter and allows you to expand individual shorthand properties by clicking the twisty besides them. only show applied styles the style side panel in firebug has an option to dis...
...610, bug 1004678, bug 895893 and bug 1165010). while there are no breakpoints for single javascript errors, there is a setting pause on exceptions within the debugger panel options. 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. they work the same in both tools. ...
...with the script execution halted it shows the different variable scopes available within the current call stack frame. furthermore, it allows you to add and manipulate watch expressions. the devtools have a variables side panel, which works basically the same. ...
...And 2 more matches
Network request list - Firefox Developer Tools
s to a known tracker that would be blocked with content blocking enabled. timeline the request list also displays a timeline for the different parts of each request. each timeline is given a horizontal position in its row relative to the other network requests, so you can see the total time taken to load the page. for more details on the color-coding used here, see the section on the timings page. starting in firefox 45, the timeline also contains two vertical lines: the blue line marks the point at which the page's domcontentloaded event is triggered. the red line marks the point at which the page's load event is triggered. blocking specific urls if you want to view your page as it would look without a resource (e.g., if it were blocked by the browser or an extension), you...
...n't have "google.com" in the url. request properties use the search box in the toolbar. see next section. filtering by properties the search box recognizes specific keywords, which can be used to filter the requests by specific request properties. those keywords are followed by a colon and a related filter value. the filter values are matched case insensitive. ...
... remote-ip:63.245.215.53 remote-ip:[2400:cb00:2048:1::6810:2802] cause shows resources matching a specific cause type. the types can be found in the description of the cause column. ...
...And 2 more matches
Work with animations - Firefox Developer Tools
it displays animations created using css transitions, css @keyframes rules, or the web animations api. starting in firefox 48, it will show animations applied to the ::before and ::after pseudo-elements. to see how it works, we'll walk through an example. ...
...his is shown as a cross-hatched portion of the bar. delay and enddelay are both represented. if you hover over the bar, a tooltip appears, giving you more detailed information about the animation or transition, including: the type of animation: css transition, css animation, or web animations api the duration of the animation the animation's start and end delay the animation's easing (or timing function). the animation's fill the playback rate of the animation information about the animated element to the left of each bar is a selector for the element that the animation applies to. if you hover over this selector, the element is highlighted in the page. click the selector to select the element in the inspector. to the left of the selector is a "target" icon (). clicking this ic...
...-inspector-compositing.html and click the red rectangle, a simple opacity animation will start. if you look at this in the animation inspector in firefox 49+, you'll see that: the white lightning bolt icon now indicates whether all the animation properties have been optimized by running them through the compositor, where possible. the bar tooltip also includes this information, as a further reminder. you'll get a message of "all animation properties are optimized." the expanded animation information now includes a lightning bolt icon next to the properties whose animation has been optimized via the compositor. let's now look at animation-inspector-compositing-silly.html — this is the same example, except that now once the red rectangle is clicked we animate both the left and transf...
...And 2 more matches
AbstractRange - Web APIs
rstand the difference between those two interfaces, and how to choose which is appropriate for your needs. ...
...nd the difference between those two interfaces, and how to choose which is appropriate for your needs. ...
... a staticrange is a basic range which cannot be changed once it's been created. specifically, as the node tree mutates and changes, the range does not. this is useful when you need to specify a range that will only be used once, since it avoids the performance and resource impact of the more complex range interface. contents of elements when trying to access the contents of an element, keep in mind that the element itself is a node, but so is any text inside it. in order to set a range endpoint within the text of an element, be sure to find the text node inside the element: let startelem = document.queryselector("p"); let endelem = startelem.queryselector("span"); let range = document.createrange(); range.setstart(startelem, 0); range.setend(endelem, endelem.childnodes[0].length/2); let ...
...And 2 more matches
AudioBufferSourceNode - Web APIs
the audiobuffersourcenode interface is an audioscheduledsourcenode which represents an audio source consisting of in-memory audio data, stored in an audiobuffer. it's especially useful for playing back audio which has particularly stringent timing accuracy requirements, such as for sounds that must match a specific rhythm and can be kept in memory rather than being played from disk or the network. to play sounds which require accurate timing but must be streamed from the network or played from disk, use a audioworkletnode to implement its playback. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 23.333333333333332%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;"...
... must be streamed from the network or played from disk, use a audioworkletnode to implement its playback. ...
...t be streamed from the network or played from disk, use a audioworkletnode to implement its playback. ...
...And 2 more matches
Applying styles and colors - Web APIs
working with scalable 2d graphics, paying attention to the pixel grid and the position of paths ensures that your drawings will look correct regardless of scaling or any other transformations involved. a 1.0-width vertical line drawn at the correct position will become a crisp 2-pixel line when scaled up by 2, and will appear at the correct position. a linecap example the linecap property determines how the end points of every line are drawn. there are three possible values for this property and those are: butt, round and square. by default this property is set to butt. butt the ends of lines are squared off at the endpoints. round the ends of lines are rounded. square the ends of lines are squared off by adding a box with an equal width and half the height of the line's thicknes...
... there are three possible values for this property: round, bevel and miter. by default this property is set to miter. note that the linejoin setting has no ...
...when joining two lines with the miter option, the outside edges of the two joining lines are extended up to the point where they meet. for lines which are at large angles with each other, this point is not far from the inside connection point. however, as the angles between each line decreases, the distance (miter length) between these points increases exponentially. the miterlimit property determines how far the outside connection point can be placed from the inside connection point. if two lines exceed this value, a bevel join gets drawn instead. note that the maximum miter length is the product of the line width measured in the current coordinate system, by the value of this miterlimit property (whose default value is 10.0 in the html <canvas>), so the miterlimit can be set independently ...
...And 2 more matches
CloseEvent - Web APIs
served and not used. 1000 normal closure normal closure; the connection successfully completed whatever purpose for which it was created. 1001 going away the endpoint is going away, either because of a server failure or because the browser is navigating away from the page that opened the connection. 1002 protocol error the endpoint is terminating the connection due to a protocol error. 1003 unsupported data the connection is being terminated because the endpoint received data of a type it cannot accept (for example, a text-only endpoint received binary data). 1004 reserved. a meaning might be defined in the future. 1005 no status received reserved. indicates that no status...
...ed in the future. 1005 no status received reserved. indicates that no status code was provided even though one was expected. 1006 abnormal closure reserved. used to indicate that a connection was closed abnormally (that is, with no close frame being sent) when a status code is expected. 1007 invalid frame payload data the endpoint is terminating the connection because a message was received that contained inconsistent data (e.g., non-utf-8 data within a text message). 1008 policy violation the endpoint is terminating the connection because it received a message that violates its policy. this is a generic status code, used when codes 1003 and 1009 are not suitable. 1009 message too big the endp...
...onnection because a message was received that contained inconsistent data (e.g., non-utf-8 data within a text message). 1008 policy violation the endpoint is terminating the connection because it received a message that violates its policy. this is a generic status code, used when codes 1003 and 1009 are not suitable. 1009 message too big the endpoint is terminating the connection because a data frame was received that is too large. ...
...And 2 more matches
DOMHighResTimeStamp - Web APIs
with the fractional part of the number indicating fractions of a millisecond. however, if the browser is unable to provide a time value accurate to 5 µs (due, for example, to hardware or software constraints), the browser can represent the value as a time in milliseconds accurate to a millisecond. also note the section below on reduced time precision controlled by browser preferences to avoid timing attacks and fingerprinting. further, if the device or operating system the user agent is running on doesn't have a clock accurate to the microsecond level, they may only be accurate to the millisecond. reduced time precision to offer protection against timing attacks and fingerprinting, the precision of time stamps might get rounded depending on browser settings. in firefox, the privacy.reduc...
...seconds, whichever is larger. properties this type has no properties. it is a double-precision floating-point value. value the value of a domhighrestimestamp is a double-precision floating-point number which describes the number of milliseconds (accurate to within 5 microseconds if the device supports it) elapsed between two points in time. ...
...f the device supports it) elapsed between two points in time. the starting time can be either a specific time determined by the script for a site or app, or the time origin. the time origin the time origin is a standard time which is considered to be the beginning of the current document's lifetime. it's calculated like this: if the script's global object is a window, the time origin is determined as follows: if the current document is the first one loaded in the window, the time origin is the time at which the browser context was created. if during the process of unloading the previous document which was loaded in the window, a confirmation dialog was displayed to let the user confirm whether or not to leave the previous page, the time origin is the time at which the user confi...
...And 2 more matches
Element.animate() - Web APIs
Web › API › Element › animate
calling element.getanimations(). syntax var animation = element.animate(keyframes, options); parameters keyframes either an array of keyframe objects, or a keyframe object whose property are arrays of values to iterate over. see keyframe formats for more details. options either an integer representing the animation's duration (in milliseconds), or an object containing one or more timing properties: id optional a property unique to animate(): a domstring with which to reference the animation. delay optional the number of milliseconds to delay the start of the animation. defaults to 0. direction optional whether the animation runs forwards (normal), backwards (reverse), switches direction after each iteration (alternate), or runs backwards and switches direction ...
...tion optional whether the animation runs forwards (normal), backwards (reverse), switches direction after each iteration (alternate), or runs backwards and switches direction after each iteration (alternate-reverse). defaults to "normal". duration optional the number of milliseconds each iteration of the animation takes to complete. defaults to 0. although this is technically optional, keep in mind that your animation will not run if this value is 0. easing optional the rate of the animation's change over time. accepts the pre-defined values "linear", "ease", "ease-in", "ease-out", and "ease-in-out", or a custom "cubic-bezier" value like "cubic-bezier(0.42, 0, 0.58, 1)". defaults to "linear". enddelay optional the number of milliseconds to delay after the end of an animation. this is p...
... an animation with 2 iterations would end halfway through a third iteration. defaults to 0.0. iterations optional the number of times the animation should repeat. defaults to 1, and can also take a value of infinity to make it repeat for as long as the element exists. you can also include a composite operation or iteration composite operation in your options list: composite optional determines how values are combined between this animation and other, separate animations that do not specify their own specific composite operation. defaults to replace. add dictates an additive effect, where each successive iteration builds on the last. for instance with transform, a translatex(-200px) would not override an earlier rotate(20deg) value but result in translatex(-200px) rotate(20deg). ...
...And 2 more matches
KeyboardEvent: code values - Web APIs
digit0" "digit0" 0x0003 "digit1" "digit1" 0x0004 "digit2" "digit2" 0x0005 "digit3" "digit3" 0x0006 "digit4" "digit4" 0x0007 "digit5" "digit5" 0x0008 "digit6" "digit6" 0x0009 "digit7" "digit7" 0x000a "digit8" "digit8" 0x000b "digit9" "digit9" 0x000c "minus" "minus" 0x000d "equal" "equal" 0x000e "backspace" "backspace" 0x000f "tab" "tab" 0x0010 "keyq" "keyq" 0x0011 "keyw" "keyw" 0x0012 "keye" "keye" 0x0013 "keyr" "keyr" 0x0014 "keyt" "keyt" 0x0015 "keyy" "keyy" 0x0016 "keyu" "keyu" 0x0017...
... "digit2" "digit2" kvk_ansi_3 (0x14) "digit3" "digit3" kvk_ansi_4 (0x15) "digit4" "digit4" kvk_ansi_6 (0x16) "digit6" "digit6" kvk_ansi_5 (0x17) "digit5" "digit5" kvk_ansi_equal (0x18) "equal" "equal" kvk_ansi_9 (0x19) "digit9" "digit9" kvk_ansi_7 (0x1a) "digit7" "digit7" kvk_ansi_minus (0x1b) "minus" "minus" kvk_ansi_8 (0x1c) "digit8" "digit8" kvk_ansi_0 (0x1d) "digit0" "digit0" kvk_ansi_rightbracket (0x1e) "bracketright" "bracketright" kvk_ansi_o (0x1f) "keyo" "keyo" kvk_ansi_u (0x20) "keyu" "keyu" kvk_ansi_leftbracket (0x21) "bracketleft" "bracketleft" kvk_ansi_i (0x22) ...
... (was "volumedown" until firefox 49) "audiovolumedown" (was "volumedown" until chrome 50) kvk_mute (0x4a) "audiovolumemute" (was "volumemute" until firefox 49) "audiovolumemute" (was "volumemute" until chrome 50) kvk_ansi_keypaddivide (0x4b) "numpaddivide" "numpaddivide" kvk_ansi_keypadenter (0x4c) "numpadenter" "numpadenter" kvk_ansi_keypadminus (0x4e) "numpadsubtract" "numpadsubtract" kvk_f18 (0x4f) "f18" "f18" kvk_f19 (0x50) "f19" "f19" kvk_ansi_keypadequals (0x51) "numpadequal" "numpadequal" kvk_ansi_keypad0 (0x52) "numpad0" "numpad0" kvk_ansi_keypad1 (0x53) "numpad1" "numpad1" kvk_ansi_keypad2 (0x54) "numpad2" "numpad2" kvk_ansi...
...And 2 more matches
Transcoding assets for Media Source Extensions - Web APIs
rough the requirements and shows you a toolchain you can use to encode your assets appropriately. getting started the first and most important step is to ensure that your files are comprised of a container and codec that users' browsers support. depending on the codec, you might need to fragment the file to comply with the iso bmff spec. (optional) if you decide to use dynamic adaptive streaming over http (dash) for adaptive bitrate streaming, you need to transcode your assets into multiple resolutions. most dash clients expect a corresponding media presentation description (mpd) manifest file, which is typically generated while generating the multiple resolution asset files. below we'll cover all of these steps, but first let's look at a toolchain we can use to do this fairly easily.
...eo and aac audio codecs have support across all modern browsers, while others don't. to convert our sample media from a quicktime mov container to an mp4 container, we can use ffmpeg. because the audio codec in the mov container is already aac and the video codec is h.264, we can instruct ffmpeg not to perform transcoding. instead, it will just copy the audio and video tracks over without performing any transcoding, which is relatively faster than having to transcode. $ ffmpeg -i trailer_1080p.mov -c:v copy -c:a copy bunny.mp4 $ ls bunny.mp4 trailer_1080p.mov checking fragmentation in order to properly stream mp4, we need the asset to be an iso bmf format mp4. without proper fragmentation, any given mp4 file is not guaranteed to work with mse. this means that metadata within the...
...already have an mp4, but it's not properly fragmented, you can again use ffmpeg: $ ffmpeg -i non_fragmented.mp4 -movflags frag_keyframe+empty_moov fragmented.mp4 in both cases, chrome may require an extra movie flag to be set: -movflags frag_keyframe+empty_moov+default_base_moof having a properly fragmented mp4 file is all you need to get started. if you wish to employ adaptive bitrate streaming, you'll have to create encodings at multiple resolutions. while mse is flexible enough to allow you to make your implementation, it's highly recommended to use an existing dash client as dash is a well-specified application protocol. creating content for dash given that you have ffmpeg and bento4's utilities accessible through your $path, you can run bento4's mp4-dash-encode.py python script ...
...And 2 more matches
MouseEvent - Web APIs
() constructor. several more specific events are based on mouseevent, including wheelevent and dragevent. ...
...onstructor. several more specific events are based on mouseevent, including wheelevent and dragevent. ...
...the mouse pointer in global (screen) coordinates. mouseevent.shiftkey read only returns true if the shift key was down when the mouse event was fired. mouseevent.which read only the button being pressed when the mouse event was fired. ...
...And 2 more matches
Page Visibility API - Web APIs
e chance that any given webpage is in the background and thus not visible to the user. the page visibility api provides events you can watch for to know when a document becomes visible or hidden, as well as features to look at the current visibility state of the page. notes: the page visibility api is especially useful for saving resources and improving performance by letting a page avoid performing unnecessary tasks when the document isn't visible. when the user minimizes the window or switches to another tab, the api sends a visibilitychange event to let listeners know the state of the page has changed. you can detect the event and perform some actions or behave differently. for example, if your web app is playing a video, it can pause the video when the user puts the tab into the backg...
...r example, watching for blur and focus events on the window helps you know when your page is not the active page, but it does not tell you that your page is actually hidden to the user. the page visibility api addresses this. note: while onblur and onfocus will tell you if the user switches windows, it doesn't necessarily mean it's hidden. pages only become hidden when the user switches tabs or minimizes the browser window containing the tab. policies in place to aid background page performance separately from the page visibility api, user agents typically have a number of policies in place to mitigate the performance impact of background or hidden tabs. these may include: most browsers stop sending requestanimationframe() callbacks to background tabs or hidden <iframe>s in order to i...
...r than specified for more details. budget-based background timeout throttling is now available in modern browsers (firefox 58+, chrome 57+), placing an additional limit on background timer cpu usage. this operates in a similar way across modern browsers, with the details being as follows: in firefox, windows in background tabs each have their own time budget in milliseconds — a max and a min value of +50 ms and -150 ms, respectively. chrome is very similar except that the budget is specified in seconds. windows are subjected to throttling after 30 seconds, with the same throttling delay rules as specified for window timers (again, see reasons for delays longer than specified). in chrome, this value is 10 seconds. timer tasks are only permitted when the budget is non-negative. ...
...And 2 more matches
RTCIceCandidatePairStats - Web APIs
sight into the quality and performance of an rtcpeerconnection while connected and configured as described by the specified pair of ice candidates. if a rtcstats-based object's type is candidate-pair, it's an rtcicecandidatepairstats object. properties rtcicecandidatepairstats is based upon rtcstats and inherits its properties. in addition, it adds the following new properties: availableincomingbitrate optional provides an informative value representing the available inbound capacity of the network by reporting the total number of bits per second available for all of the candidate pair's incoming rtp streams. this does not take into account the size of the ip overhead, nor any other transport layers such as tcp or udp. availableoutgoingbitrate optional provides an informative value r...
...e representing the available outbound capacity of the network by reporting the total number of bits per second available for all of the candidate pair's outoing rtp streams. this does not take into account the size of the ip overhead, nor any other transport layers such as tcp or udp. bytesreceieved optional the total number of payload bytes received (that is, the total number of bytes received minus any headers, padding, or other administrative overhead) on this candidate pair so far. bytessent optional the total number of payload bytes sent (that is, the total number of bytes sent minus any headers, padding, or other administrative overhead) so far on this candidate pair. circuitbreakertriggercount optional an integer value indicating the number of times the circuit-breaker has been t...
...y happen if responsesreceived is 0. consentrequestssent optional the total number of consent requests that have been sent on this candidate pair. currentroundtriptime optional a floating-point value indicating the total time, in seconds, that elapsed elapsed between the most recently-sent stun request and the response being received. this may be based upon requests that were involved in confirming permission to open the connection. firstrequesttimestamp optional a domhighrestimestamp value which specifies the time at which the first stun request was sent from the local peer to the remote peer for this candidate pair. lastpacketreceivedtimestamp optional a domhighrestimestamp value indicating the time at which the last packet was received by the local peer from the remote peer for this...
...And 2 more matches
WebGLRenderingContext.blendEquationSeparate() - Web APIs
the webglrenderingcontext.blendequationseparate() method of the webgl api is used to set the rgb blend equation and alpha blend equation separately. the blend equation determines how a new pixel is combined with a pixel already in the webglframebuffer. syntax void gl.blendequationseparate(modergb, modealpha); parameters modergb a glenum specifying how the red, green and blue components of source and destination colors are combined. 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, th...
... modealpha a glenum specifying how the alpha component (transparency) of source and destination colors are combined. ...
... modealpha a glenum specifying how the alpha component (transparency) of source and destination colors are combined. ...
...And 2 more matches
WebGL model view projection - Web APIs
n 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). the code below will create 2 triangles that will draw a square on the screen. the z depth in the squares determines what gets drawn on top when the squares share the same space. the smaller z values are rendered on top of the larger z values. webglbox example this example will create a custom webglbox object that will draw a 2d box on the screen. note: the code for each webglbox example is available in this github repo and is organized by section. in addition there is a jsfiddle link at the bottom of eac...
...dimension introduces the notion of perspective into the coordinate system; with it in place, we can map 3d coordinates into 2d space—thereby allowing two parallel lines to intersect as they recede into the distance. the value of w is used as a divisor for the other components of the coordinate, so that the true values of x, y, and z are computed as x/w, y/w, and z/w (and w is then also w/w, becoming 1). a three dimensional point is defined in a typical cartesian coordinate system. the added fourth dimension changes this point into a homogeneous coordinate. it still represents a point in 3d space and it can easily be demonstrated how to construct this type of coordinate through a pair of simple functions. function cartesiantohomogeneous(point) let x = point[0]; let y = point[1]; let ...
... compute a perspective projection matrix, we need to introduce the concept of the viewing frustum (also known as the view frustum). this is the region of space whose contents are visible to the user at the current time. it's the 3d region of space defined by the field of view and the distances specified as the nearest and farthest content that should be rendered. while rendering, we need to determine which polygons need to be rendered in order to represent the scene. this is what the viewing frustum defines. but what's a frustum in the first place? a frustum is the 3d solid that results from taking any solid and slicing off two sections of it using two parallel planes. consider our camera, which is viewing an area that starts immediately in front of its lens and extends off into the distanc...
...And 2 more matches
Taking still photos with WebRTC - Web APIs
e. we'll break it up into a few bite-sized pieces to make it easier to explain. 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. ...
...ion to avoid global variables, then setting up various variables we'll be using. (function() { var width = 320; // we will scale the photo width to this var height = 0; // this will be computed based on the input stream var streaming = false; var video = null; var canvas = null; var photo = null; var startbutton = null; those variables are: width whatever size the incoming video is, we're going to scale the resulting image to be 320 pixels wide. height the output height of the image will be computed given the width and the aspect ratio of the stream. streaming indicates whether or not there is currently an active stream of video running. video this will be a reference to the <video> element after the page is done loading. canvas this will be a reference to...
...period of time that elapses before the stream of video begins to flow. to avoid blocking until that happens, we add an event listener to video for the canplay event, which is delivered when the video playback actually begins. at that point, all the properties in the video object have been configured based on the stream's format. ...
...And 2 more matches
Starting up and shutting down a WebXR session - Web APIs
before you can begin to render your augmented or virtual reality scenario, you need to create and set up the webxr session, and you should know how to shut it down properly as well. you will learn how to do these things in this article. accessing the webxr api your app's access to the webxr api begins with the xrsystem object. this object represents the overall webxr device suite available to you through the hardware and drivers available on the user's equipment. ...
...e extension is also available on github. emulator issues and notes while this isn't the place for a full article about the extension, there are some specific things worth mentioning. version 0.4.0 of the extension was announced on march 26, 2020. it introduced support for augmented reality (ar) through the webxr ar module, which has is approaching a stable state. documentation for ar is forthcoming shortly here on mdn. other improvements include updating the emulator to rename the xr interface to xrsystem, introduce support for squeeze (grip) input sources, and add support for the xrinputsource property profiles. context requirements a webxr compatible environment starts with a securely-loaded document. your document needs to either have been loaded from the local drive (such as by usin...
...e webxr standardization process. the polyfill brings support for webxr to browsers that don't have native webxr support, and smooths out the inconsistencies among implementations in the browsers that do have it, so it can sometimes also be useful even if webxr is natively available. 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. let webxrpolyfill = null; function getxr(usepolyfill) { let tempxr; let temppoly; switch(usepolyfill) { case "if-needed": if (!navigator.xr) { webxrpolyfill = new webxrpolyfill(); } tempxr = navigator.xr; break; case "yes": webxrpolyfill = new webxrpolyfill(); te...
...And 2 more matches
WebXR Device API - Web APIs
ured for use by webxr. guides and tutorials the following guides and tutorials are a great resource to learn how to comprehend webxr and the underlying 3d and vr/ar graphics concepts. foundations and basics fundamentals of webxr before diving into the details of how to create content using webxr, it may be helpful to read this overview of the technology, which includes introductions to terminology that may be unfamiliar to you, or which may be used in a new way. matrix math for the web a guide covering how matrices can be used on the web, including both for css transforms and for webgl purposes, as well as to handle the positioning and orientation of objects in webxr contexts. webxr application life cycle an overview of the overall life cycle of a webxr application, from startup ...
...—including the user's body and its parts—are located in space, and how their movement and orientation relative to one another is monitored and managed over time. this article explains the relationship between spaces, poses, viewers, and views. rendering and the webxr frame animation callback starting with how you schedule frames to be rendered, this guide then continues to cover how to determine the placement of objects in the view and how to then render them into the webgl buffer used for each of the two eyes' views of the scene. viewpoints and viewers: simulating cameras in webxr webgl (and therefore webxr) doesn't really have a concept of a camera, which is the traditional concept used to represent a viewpoint in 3d graphics. in this article, we see how to simulate a camera and ho...
...ove. lighting a webxr setting since webxr rendering is based upon webgl, the same lighting techniques used for any 3d application are applied to webxr scenes. however, there are issues specific to creating augmented and virtual reality settings that need to be considered when writing your lighting code. this article discusses those issues. using bounded reference spaces in this article, we examine how to use a bounded-floor reference space to define the boundaries of where the viewer can safely move about without leaving the area tracked by their xr hardware or colliding with a physical obstacle. on devices which support it, bounded-floor can be a useful tool in your repertoire. making it interactive movement, orientation, and motion: a webxr example in this example and tutorial, we...
...And 2 more matches
Web Audio API - Web APIs
. a simple, typical workflow for web audio would look something like this: create audio context inside the context, create sources — such as <audio>, oscillator, stream create effects nodes, such as reverb, biquad filter, panner, compressor choose final destination of audio, for example your system speakers connect the sources up to the effects, and the effects to the destination. timing is controlled with high precision and low latency, allowing developers to write code that responds accurately to events and is able to target specific samples, even at a high sample rate. so applications such as drum machines and sequencers are well within reach. the web audio api also allows us to control how audio is spatialized. using a system based on a source-listener model, it allows cont...
...aren't familiar with audio or music terms, and as it incorporates a great deal of functionality it can prove difficult to get started if you are a developer. it can be used to simply incorporate audio into your website or application, by providing atmosphere like futurelibrary.no, or auditory feedback on forms. however, it can also be used to create advanced interactive instruments. with that in mind, it is suitable for both developers and musicians alike. we have a simple introductory tutorial for those that are familiar with programming but need a good introduction to some of the terms and structure of the api. there's also a basic concepts behind web audio api article, to help you understand the way digital audio works, specifically in the realm of the api. this also includes a good int...
... web audio api interfaces the web audio api has a number of interfaces and associated events, which we have split up into nine categories of functionality. general audio graph definition general containers and defini...
...And 2 more matches
Window - Web APIs
Web › API › Window
nd innerheight. generally, anything that can't reasonably pertain to a tab pertains to the window instead. ...
...nnerheight. generally, anything that can't reasonably pertain to a tab pertains to the window instead. ...
...browser window. window.outerwidth read only gets the width of the outside of the browser window. window.pagexoffset read only an alias for window.scrollx. window.pageyoffset read only an alias for window.scrolly window.parent read only returns a reference to the parent of the current window or subframe. window.performance read only returns a performance object, which includes the timing and navigation attributes, each of which is an object providing performance-related data. see also using navigation timing for additional information and examples. window.personalbar read only returns the personalbar object, whose visibility can be toggled in the window. window.screen read only returns a reference to the screen object associated with the window. window.screenx and window.
...And 2 more matches
Using XMLHttpRequest - Web APIs
est provides the ability to listen to various events that can occur while the request is being processed. this includes periodic progress notifications, error notifications, and so forth. support for dom progress event monitoring of xmlhttprequest transfers follows the specification for progress events: these events implement the progressevent interface. the actual events you can monitor to determine the state of an ongoing transfer are: progress the amount of data that has been retrieved has changed. load the transfer is complete; all data is now in the response var oreq = new xmlhttprequest(); oreq.addeventlistener("progress", updateprogress); oreq.addeventlistener("load", transfercomplete); oreq.addeventlistener("error", transferfailed); oreq.addeventlistener("abort", transfercan...
... note: you need to add the event listeners before calling open() on the request. otherwise the progress events will not fire. the progress event handler, specified by the updateprogress() function in this example, receives the total number of bytes to transfer as well as the number of bytes transferred so far in the event's total and loaded fields. however,...
... submitting forms and uploading files instances of xmlhttprequest can be used to submit forms in two ways: using only ajax using the formdata api using the formdata api is the simplest and fastest, but has the disadvantage that data collected can not be stringified. using only ajax is...
...And 2 more matches
Web APIs
Web › API
ough this doesn't always have to be the case. specifications this is a list of all the apis that are available. ...
...ential management apiddomeencoding apiencrypted media extensionsffetch apifile system api frame timing apifullscreen apiggamepad api geolocation apihhtml drag and drop apihigh resolution timehistory apiiimage capture apiindexeddbintersection observer apillong tasks api mmedia capabilities api media capture and streamsmedia session apimedia source extensions mediastream recordingnnavigation timingnetwork information api ppage visibility apipayment request apiperformance apiperformance timeline apipermissions apipointer eventspointer lock apiproximity events push api rresize observer apiresource timing apisserver sent eventsservice workers apistoragestorage access apistreams ttouch eventsuurl apivvibration apivisual viewport wweb animationsweb audio apiweb authentication apiweb crypto...
...aynode deprecationreportbody devicelightevent devicemotionevent devicemotioneventacceleration devicemotioneventrotationrate deviceorientationevent deviceproximityevent directoryentrysync directoryreadersync displaymediastreamconstraints document documentfragment documentorshadowroot documenttimeline documenttouch documenttype doublerange dragevent dynamicscompressornode e ext_blend_minmax ext_color_buffer_float ext_color_buffer_half_float ext_disjoint_timer_query ext_float_blend ext_frag_depth ext_srgb ext_shader_texture_lod ext_texture_compression_bptc ext_texture_compression_rgtc ext_texture_filter_anisotropic eckeygenparams eckeyimportparams ecdhkeyderiveparams ecdsaparams effecttiming element elementcssinlinestyle elementtraversal errorevent event eventlistener eventsou...
...And 2 more matches
ARIA live regions - Accessibility
or client side validation notices to users. (tbd: link to aria form tutorial with aria info) to maximize compatibility, some people recommend adding a redundant aria-live="assertive" when using this role. however, adding both aria-live and role="alert" causes double speaking issues in voiceover on ios. progressbar a hybrid between a widget and a live region. use this with aria-valuemin, aria-valuenow and aria-valuemax. (tbd: add more info here). marquee for text which scrolls, such as a stock ticker. timer or any kind of timer or clock, such as a countdown timer or stopwatch readout. advanced live regions (tbd: more granular information on the support of the individual attributes with combinations of os/browser/at). general support f...
...d label identifiers are separated with a space. aria-describedby: the aria-describedby=[idlist] is used to associate a region with its descriptions, similar to aria-controls but instead associating descriptions to the region and description identifiers are separated with a space. ...
...ith a space. aria-describedby: the aria-describedby=[idlist] is used to associate a region with its descriptions, similar to aria-controls but instead associating descriptions to the region and description identifiers are separated with a space. advanced use case: clock as an illustration of aria-atomic, consider a site with a simple clock, showing hours and minutes. ...
...And 2 more matches
Using the progressbar role - Accessibility
e effect it has on browsers and assistive technology. the progressbar role should be used for an element that displays the progress status for a task that take a long time or consists of several steps. a progressbar indicates that the user's request has been received and the application is making progress toward completing the requested action. 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. if the progress value is indeterminate, the developer should omit the aria-valuenow attribute. as the task progresses, the aria-valuenow value has to be updated dynamically to indicate this progress to assistive technology products. if the progressbar is describing the loading ...
...region of a page, the author should use aria-describedby to point to the status, and set the aria-busy attribute to true on the region until it is finished loading. it is not possible for the user to alter the value of a progressbar because it is always readonly. note: assistive technologies generally will render the value of aria-valuenow as a percent of the range between the value of aria-valuemin and aria-valuemax, unless aria-valuetext is specified. it is best to set the values for aria-valuemin, aria-valuemax, and aria-valuenow in a manner that is appropriate for this calculation. note: elements with the role progressbar have an implicit aria-readonly value of true. possible effects on user agents and assistive technology screen readers should announce the progress updates as they o...
...d announce the progress updates as they occur. if the progress bar is labeled, the label text should be mentioned as well. note: opinions may differ on how assistive technology should handle this. the information provided above is one of those opinions and therefore not normative. ...
...And 2 more matches
Web accessibility for seizures and physical reactions - Accessibility
seizure disorders can have a seizure triggered by content that flashes at certain frequencies for more than a few flashes” and goes on to note, very specifically that: “people are even more sensitive to red flashing than to other colors, so a special test is provided for saturated red flashing”. you don't even need an image or video to cause harm. a <div> element set to change color and luminosity at high frequency, easily done via javascript, can cause real harm. and, flickering can occur everywhere. for example, "spinners" commonly used to display while pages load, can easily "flicker" while spinning. additional concerns exist for individuals with motor-skills problems. for example, the page for trace research & development center’s photosensitive epilepsy analysis tool notes tha...
...uld prefer a larger contrast." sometimes there can be such a thing as too much contrast; a halo effect around text can occur in such situations and actually reduce legibility. putting the amount of contrast in the user's control is a definite gift for accessibility. prefers-reduced-transparency the prefers-reduced-transparency media feature is used to detect if the user has requested the system minimize the amount of transparent or translucent layer effects it uses. mediaquerylist interface section 4.2 from the csswg.org drafts integrates with the event loop defined in html. [html] for the mediaquerylist object. see the mdn document, mediaquerylist for more information. personalization help and support the requirement for the literal property is taken from section 23 non-literal text an...
...es to users. transitions (for css and svg) the following is from the web animations model csswg.org drafts the web animations model is intended to provide the features necessary for expressing css transitions [css-transitions-1], css animations [css-animations-1], and svg [svg11]. ...
...And 2 more matches
Operable - Accessibility
tionality available from a keyboard. guideline 2.2 — enough time: provide users enough time to read and use content this guideline covers situations in which functionality may have a time limit. for example, purchases sometimes need to be completed within a time limit for security reasons. success criteria how to conform to the criteria practical resource 2.2.1 timing is adjustable (a) for functionality with time limits (e.g. completing a hotel or flight booking often has a time limit), the user should be given controls to allow them to adjust, extend or turn off the time limit. exceptions to this are activities with time limits longer than 20 hours, real time events (e.g. live multiplayer games), and any other activity that requires a time limit...
...ers to disable animations from interactions (unless the animation is essential). understanding animations from interactions note: also see the wcag description for guideline 2.3 seizures and physical reactions: do not design content in a way that is known to cause seizures or physical reactions. guideline 2.4 — navigable: provide ways to help users navigate, find content, and determine where they are the conformance criteria under this guideline relate to ways in which users can be expected to orientate themselves, and find the content and functionality they are looking for on the current page or other pages of the site. success criteria how to conform to the criteria practical resource 2.4.1 bypass blocks (a) a mechanism should be provide...
...nse, meaning that the page is still usable by non-sighted/keyboard users. see ui controls for general advice on tabbing to controls. if you need to place elements in an unusual layout, it is better to make sure the source order is sensible, then use css features like positioning to handle the layout. 2.4.4 link purpose (in context) (a) the purpose/destination of a link can be determined from the link text, or from its surroundings (e.g. the surrounding text). exceptions are where the link purpose is ambiguous to all users (see ambiguous to users in general for a useful explanation of this). see meaningful text labels. also note that you should minimize instances where multiple copies of the same text are linked to different places. this can cause problems for screenreader u...
...And 2 more matches
-moz-device-pixel-ratio - CSS: Cascading Style Sheets
the -moz-device-pixel-ratio gecko-only css media feature can be used to apply styles based on the number of device pixels per css pixel. do not use this feature. use the resolution feature with the dppx unit instead. note: this media feature is also implemented by webkit and by ie 11 for windows phone 8.1 as -webkit-device-pixel-ratio. ...
...he -moz-device-pixel-ratio gecko-only css media feature can be used to apply styles based on the number of device pixels per css pixel. do not use this feature. use the resolution feature with the dppx unit instead. note: this media feature is also implemented by webkit and by ie 11 for windows phone 8.1 as -webkit-device-pixel-ratio. ...
...ss pixel. do not use this feature. use the resolution feature with the dppx unit instead. note: this media feature is also implemented by webkit and by ie 11 for windows phone 8.1 as -webkit-device-pixel-ratio. the min and max prefixes as implemented by gecko are named min--moz-device-pixel-ratio and max--moz-device-pixel-ratio; but the same prefixes as implemented by webkit are named -webkit-min-device-pixel-ratio and -webkit-max-device-pixel-ratio. syntax <number> the number of device pixels per css pixel. ...
...And 2 more matches
height - CSS: Cascading Style Sheets
Web › CSS › @viewport › height
syntax /* one value */ height: auto; height: 320px; height: 15em; /* two values */ height: 320px 200px; values auto the used value is calculated from the other css descriptors' values. <length> a non-negative absolute or relative length. ...
... syntax /* one value */ height: auto; height: 320px; height: 15em; /* two values */ height: 320px 200px; values auto the used value is calculated from the other css descriptors' values. <length> a non-negative absolute or relative length. ...
...d value is calculated from the other css descriptors' values. <length> a non-negative absolute or relative length. <percentage> a percentage value relative to the width or height of the initial viewport at zoom factor 1.0, for horizontal and vertical lengths respectively. must be non-negative. formal definition related at-rule@viewportinitial valueas each of the properties of the shorthand:min-height: automax-height: nonepercentagesas each of the properties of the shorthand:min-height: the percentage is calculated with respect to the height of the generated box's containing block. if the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the percentage value is treated as 0.max-height: the perc...
...And 2 more matches
Introduction to the CSS basic box model - CSS: Cascading Style Sheets
every box is composed of four parts (or areas), defined by their respective edges: the content edge, padding edge, border edge, and margin edge. the content area, bounded by the content edge, contains the "real" content of the element, such as text, an image, or a video player. ...
..."real" content of the element, such as text, an image, or a video player. its dimensions are the content width (or content-box width) and the content height (or content-box height). it often has a background color or background image. if the box-sizing property is set to content-box (default) and if the element is a block element, the content area's size can be explicitly defined with the width, min-width, max-width, height, min-height, and max-height properties. the padding area, bounded by the padding edge, extends the content area to include the element's padding. its dimensions are the padding-box width and the padding-box height. the thickness of the padding is determined by the padding-top, padding-right, padding-bottom, padding-left, and shorthand padding properties. the border are...
...padding-box width and the padding-box height. the thickness of the padding is determined by the padding-top, padding-right, padding-bottom, padding-left, and shorthand padding properties. the border area, bounded by the border edge, extends the padding area to include the element's borders. its dimensions are the border-box width and the border-box height. the thickness of the borders are determined by the border-width and shorthand border properties. if the box-sizing property is set to border-box, the border area's size can be explicitly defined with the width, min-width, max-width, height, min-height, and max-height properties. when there is a background (background-color or background-image) set on a box, it extends to the outer edge of the border (i.e. extends underneath the border in...
...And 2 more matches
Basic Concepts of grid layout - CSS: Cascading Style Sheets
the features shown in this overview will then be explained in greater detail in the rest of this guide. what is a grid? a grid is a set of intersecting horizontal and vertical lines defining columns and rows. elements can be placed onto the grid within these column and row lines. ...
...for example, i may want my rows to never collapse smaller than 100 pixels, but if my content stretches to 300 pixels in height, then i would like the row to stretch to that height. grid has a...
...: 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; } track sizing and minmax when setting up an explicit grid or defining the sizing for automatically created rows or columns we may want to give tracks a minimum size, but also ensure they expand to fit any content that is added. for example, i may want my rows to never collapse smaller than 100 pixels, but if my content stretches to 300 pixels in height, then i would like the row to stretch to that height. grid has a solution for this with the minmax() function. in this next example i am using minmax() in the value of grid-auto-rows. this means auto...
...And 2 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. in this guide we are going to look at how these two things work together when we use named lines. line naming is incredibly useful, but some of the more baffling looking grid syntax comes from this combination of names and track sizes. once you work through some examples it should become clearer and easier to work with. naming lines when defining a grid you can assign some or all of the lines in your grid a name when you define your grid with the grid-template-rows and grid-template-columns properties. to demonstrate i’ll use the simple layout created in the guide on line-based placement. this time i’ll create the grid using name...
... main-start; } .box4 { grid-column-start: content-start; grid-column-end: main-end; grid-row-start: content-end; } <div class="wrapper"> <div class="box1">one</div> <div class="box2">two</div> <div class="box3">three</div> <div class="box4">four</div> </div> everything else about line-based placement still works in the same way and you can mix named lines and line numbers. naming lines is useful when creating a responsive design where you redefine the grid, rather than then needing to redefine the content position by changing the line number in your media queries, you can ensure that the line is always named the same in your definitions. giving lines multiple names you may want to give a line more than one name, perhaps it denotes the sidebar-end and the main-start for...
...is always named the same in your definitions. giving lines multiple names you may want to give a line more than one name, perhaps it denotes the sidebar-end and the main-start for example. to do this add the names inside the square brackets with whitespace between them [sidebar-end main-start]. you can then refer to that line by either of the names. implicit grid areas from named lines when naming the lines, i mentioned that you can name these anything you like. the name is a custom ident, an author-defined name. when choosing the name you need to avoid words that might appear in the specification and be confusing - such as span. idents are not quoted. while you can choose any name, if you append -start and -end to the lines around an area, as i have in the example above, grid will creat...
...And 2 more matches
CSS values and units - CSS: Cascading Style Sheets
of lengths in css: relative and absolute. relative length units specify a length in relation to something else. for example, em is relative to the font size on the element and vh is relative to the viewport height. relative length units unit relative to em font size of the element. ex x-height of the element's font. cap cap height (the nominal height of capital letters) of the element's font. ch average character advance of a narrow glyph in the element’s font, as represented by the “0” (zero, u+0030) glyph. ic average character advance of a full width glyph in the element’s font, as represented by the “水” (cjk water ideograph, u+6c34) glyph. rem font size of the root element. ...
...er ideograph, u+6c34) glyph. rem font size of the root element. lh line height of the element. rlh line height of the root element. vw 1% of viewport's width. vh 1% of viewport's height. vi 1% of viewport's size in the root element's inline axis. vb 1% of viewport's size in the root element's block axis. vmin 1% of viewport's smaller dimension. vmax 1% of viewport's larger dimension. absolute length units are fixed to a physical length: either an inch or a centimeter. many of these units are therefore more useful when the output is a fixed size media, such as print. for example, mm is a physical millimeter, 1/10th of a centimeter. absolute length units unit name...
...mage that can be used in css, and is defined in the css image values and replaced content module. position the <position> type defines 2d positioning of an object inside a positioning area, for example a background image inside a container. this type is interpreted as a background-position and therefore specified in the css backgrounds and borders specification. functional notation calc() min() max() clamp() toggle() attr() functional notation is a type of value that can represent more complex types or invoke special processing by css. the syntax starts with the name of the function immediately followed by a left parenthesis ( followed by the argument(s) to the notation followed by a right parenthesis ). functions can take multiple arguments, which are formatted similarly to a c...
...And 2 more matches
CSS reference - CSS: Cascading Style Sheets
Web › CSS › Reference
his index do not include the javascript names where they differ from the css standard names. ...
...le()gridgrid-areagrid-auto-columnsgrid-auto-flowgrid-auto-rowsgrid-columngrid-column-endgrid-column-startgrid-rowgrid-row-endgrid-row-startgrid-templategrid-template-areasgrid-template-columnsgrid-template-rowshhzhanging-punctuationheightheight (@viewport)@historical-forms:hoverhsl()hsla()hue-rotate()hyphensi<ident><image>image()image-orientationimage-renderingimage-set()@importin:in-range:indeterminateinheritinitialinline-sizeinsetinset()inset-blockinset-block-endinset-block-startinset-inlineinset-inline-endinset-inline-start<integer>:invalidinvert()isolationjjustify-contentjustify-itemsjustify-selfkkhz@keyframesl:lang:last-child:last-of-typeleader():leftleft@left-bottom<length><length-percentage>letter-spacingline-breakline-heightlinear-gradient():linklist-stylelist-style-imagelist-style-po...
...eftmargin-rightmargin-top::markermarks (@page)maskmask-bordermask-border-modemask-border-outsetmask-border-repeatmask-border-slicemask-border-sourcemask-border-widthmask-clipmask-compositemask-imagemask-modemask-originmask-positionmask-repeatmask-sizemask-typematrix()matrix3d()max()max-block-sizemax-heightmax-height (@viewport)max-inline-sizemax-widthmax-width (@viewport)max-zoom (@viewport)@mediamin()min-block-sizemin-heightmin-height (@viewport)min-inline-sizemin-widthmin-width (@viewport)min-zoom (@viewport)minmax()mix-blend-modemmmsn@namespacenegative (@counter-style):not:nth-child:nth-last-child:nth-last-of-type:nth-of-type<number>oobject-fitobject-positionoffsetoffset-anchoroffset-distanceoffset-pathoffset-rotate:only-child:only-of-typeopacityopacity():optionalorderorientation (@viewpor...
...And 2 more matches
grid - CSS: Cascading Style Sheets
Web › CSS › grid
the gutter properties are not reset by this shorthand. ...
...re not reset by this shorthand. ...
...] <'grid-auto-rows'>? / <'grid-template-columns'> va...
...And 2 more matches
mask-type - CSS: Cascading Style Sheets
Web › CSS › mask-type
the mask-type css property sets whether an svg <mask> element is used as a luminance or an alpha mask. it applies to the <mask> element itself. /* keyword values */ mask-type: luminance; mask-type: alpha; /* global values */ mask-type: inherit; mask-type: initial; mask-type: unset; this property may be overridden by the mask-mode property, which has the same effect but applies to the element where the mask is used. alpha masks will generally be faster to render. syntax the mask-type property is specified as one of the keyword values listed below. values luminance is a keyword indicating that the associated mask image is a luminance mask, i.e., that its relative luminance values must be used when applying it. alpha is a keyword indicating that the associated mask image is an alp...
...ed as one of the keyword values listed below. values luminance is a keyword indicating that the associated mask image is a luminance mask, i.e., that its relative luminance values must be used when applying it. alpha is a keyword indicating that the associated mask image is an alpha mask, i.e., that its alpha channel values must be used when applying it. ...
...d mask image is a luminance mask, i.e., that its relative luminance values must be used when applying it. alpha is a keyword indicating that the associated mask image is an alpha mask, i.e., that its alpha channel values must be used when applying it. ...
...And 2 more matches
mix-blend-mode - CSS: Cascading Style Sheets
formal definition initial valuenormalapplies toall elementsinheritednocomputed valueas specifiedanimation typediscretecreates stacking contextyes formal syntax <blend-mode>where <blend-mode> = normal | multiply | screen | over...
...lending mode that should be applied. ...
...ass="item firefox"></div> <svg viewbox="0 0 150 150"> <ellipse class="item r" cx="75" cy="75" rx="25" ry="70"></ellipse> <ellipse class="item g" cx="75" cy="75" rx="25" ry="70"></ellipse> <ellipse class="item b" cx="75" cy="75" rx="25" ry="70"></ellipse> </svg> </div> </div> </div> <div class="cell"> luminosity <div class="container luminosity"> <div class="group"> <div class="item firefox"></div> <svg viewbox="0 0 150 150"> <ellipse class="item r" cx="75" cy="75" rx="25" ry="70"></ellipse> <ellipse class="item g" cx="75" cy="75" rx="25" ry="70"></ellipse> <ellipse class="item b" cx="75" cy="75" rx="25" ry="70"></el...
...And 2 more matches
HTML attribute: max - HTML: Hypertext Markup Language
Web › HTML › Attributes › max
if the max attribute is present by is not specified or is invalid, no max value is applied. ...
...t type syntax example date yyyy-mm-dd <input type="date" max="2019-12-25" step="1"> month yyyy-mm <input type="month" max="2019-12" step="12"> week yyyy-w## <input type="week" max="2019-w23" step=""> time hh:mm <input type="time" max="17:00" step="900"> datetime-local yyyy-mm-ddthh:mm <input type="datetime-local" min="2019-12-25t23:59"> number <number> <input type="number" min="0" step="5" max="100"> range <number> <input type="range" min="60" step="5" max="100"> note: when the data entered by the user doesn't adhere to the maximum value set, the value is considered invalid in contraint validation and will match the :invalid and :out-of-range pseudoclasses see client-si...
...lient-side validation and rangeoverflow for more information. for the<progress> element, the max attribute describes how much work the task indicated by the progress element requires. if present, must have a value greater than zero and be a valid floating point number. for the <meter> element, the max attribute defines the upper numeric bound of the measured range. ...
...And 2 more matches
<body>: The Document Body element - HTML: Hypertext Markup Language
Web › HTML › Element › body
document permitted aria roles no role permitted dom interface htmlbodyelement the <body> element exposes the htmlbodyelement interface. you can access the <body> element through the document.body property. attributes this element includes the global attributes. alink color of text for hyperlinks when selected. this method is non-conforming, use css color property in conjunction with the :active pseudo-class instead. background uri of a image to use as a background. this method is non-conforming, use css background property on the element instead. bgcolor background color for the document. this method is non-conforming, use css background-color property on the element instead. bottommargin the margin of the bottom of th...
...unction with the :active pseudo-class instead. background uri of a image to use as a background. this method is non-conforming, use css background property on the element instead. bgcolor background color for the document. this method is non-conforming, use css background-color property on the element instead. bottommargin the margin of the bottom of the body. this method is non-conforming, use css margin-bottom property on the element instead. leftmargin the margin of the left of the body. this method is non-conforming, use css margin-left property on the element instead. link color of text for unvisited hypertext links. this method is non-conforming, use css color property in conjunction with the :link pseudo-class instead. onafterprint function to call after the user ...
...s moved forward in undo transaction history. onresize function to call when the document has been resized. onstorage function to call when the storage area has changed. onundo function to call when the user has moved backward in undo transaction history. onunload function to call when the document is going away. rightmargin the margin of the right of the body. ...
...And 2 more matches
<script>: The Script element - HTML: Hypertext Markup Language
Web › HTML › Element › script
content categories metadata content, flow content, phrasing content. permitted content dynamic script such as text/javascript. tag omission none, both the starting and ending tag are mandatory. ...
...sync attribute is present, then the classic script will be fetched in parallel to parsing and evaluated as soon as it is available. for module scripts, if the async attribute is present then the scripts and all their dependencies will be executed in the defer queue, therefore they will get fetched in parallel to parsing and evaluated as soon as they are available. this attribute allows the elimination of parser-blocking javascript where the browser would have to load and evaluate scripts before continuing to parse. defer has a similar effect in this case. this is a boolean attribute: the presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value. see browser compatibility for notes on browser support. see also a...
...oad and evaluate scripts before continuing to parse. defer has a similar effect in this case. this is a boolean attribute: the presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value. see browser compatibility for notes on browser support. see also async scripts for asm.js. crossorigin normal script elements pass minimal information to the window.onerror for scripts which do not pass the standard cors checks. to allow error logging for sites which use a separate domain for static media, use this attribute. see cors settings attributes for a more descriptive explanation of its valid arguments. defer this boolean attribute is set to indicate to a browser that the script is meant to be executed after the doc...
...And 2 more matches
HTML elements reference - HTML: Hypertext Markup Language
Web › HTML › Element
an alphabetical list of all elements is provided in the sidebar on every element's page as well as this one. for more information about the basics of html elements and attributes, see the section on elements in the introduction to html article. main root element description <html> the html <html> element represents the root (top-level element) of an html document, so it is also referred to as the root element. all other elements must be descendants of this element. ...
...ments. <h1>, <h2>, <h3>, <h4>, <h5>, <h6> the html <h1>–<h6> elements represent six levels of section headings. <h1> is the highest section level and <h6> is the lowest. <hgroup> the html <hgroup> element represents a multi-level heading for a section of a document. it groups a set of <h1>–<h6> elements. <main> the html <main> element represents the dominant content of the <body> of a document. the main content area consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application. <nav> the html <nav> element represents a section of a page whose purpose is to provide navigation links, either within the current document or to other documents. common example...
...n optional caption, which is specified using the (<figcaption>) element. <hr> the html <hr> element represents a thematic break between paragraph-level elements: for example, a change of scene in a story, or a shift of topic within a section. <li> the html <li> element is used to represent an item in a list. <main> the html <main> element represents the dominant content of the <body> of a document. the main content area consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application. <ol> the html <ol> element represents an ordered list of items — typically rendered as a numbered list. <p> the html <p> element represents a paragraph. ...
...And 2 more matches
Configuring servers for Ogg media - HTTP
formats will be especially helpful when configuring serers to host media properly. handle http 1.1 byte range requests correctly in order to support seeking and playing back regions of the media that aren't yet downloaded, gecko uses http 1.1 byte-range requests to retrieve the media from the seek target position. in addition, gecko uses byte-range requests to seek to the end of the media (assuming you serve the content-length header) in order to determine the duration of the media. your server should accept the accept-ranges: bytes http header if it can accept byte-range requests. it must return 206: partial content to all byte range requests; otherwise, browsers can't be sure you actually support byte range requests. your server must also return 206: partial content for the request ran...
...ou may need to experiment a bit to get the right balance between file size and seek performance. 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. without preload, the browser only downloads enough of the media to display the first video frame, and to determine the media's duration. preload is off by default, so if getting to video is the point of your web page, your users may appreciate it if you include preload in your video elements. using preload="metadata" will preload the media file's metadata and possibly the first few frames of video. setting payload to auto tells the browser to automatically begin downloading the media as soon as the page is ...
...er the assumption that the user will play it. configuration for older firefox versions serve x-content-duration headers note: as of firefox 41, the x-content-duration header is no longer supported. see bug 1160695 for more details. ...
...And 2 more matches
Closures - JavaScript
ert() statement within the displayname() function successfully displays the value of the name variable, which is declared in its parent function. this is an example of lexical scoping, which describes how a parser resolves variable names when functions are nested. the word lexical refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. nested functions have access to variables declared in their outer scope. closure consider the following code example: function makefunc() { var name = 'mozilla'; function displayname() { alert(name); } return displayname; } var myfunc = makefunc(); myfunc(); running this code has exactly the same effect as the previous example of the init() fun...
...lert(name); } return displayname; } var myfunc = makefunc(); myfunc(); running this code has exactly the same effect as the previous example of the init() function above. what's different (and interesting) is that the displayname() inner function is returned from the outer function before being executed. at first glance, it might seem unintuitive that this code still works. in some programming languages, the local variables within a function exist for just the duration of that function's execution. once makefunc() finishes executing, you might expect that the name variable would no longer be accessible. however, because the code still works as expected, this is obviously not the case in javascript. the reason is that functions in javascript form closures. a closure is the combination...
... are both closures. they share the same function body definition, but store different lexical environments. in add5's lexical environment, x is 5, while in the lexical environment for add10, x is 10. practical closures closures are useful because they let you associate data (the lexical environment) with a function that operates on that data. this has obvious parallels to object-oriented programming, where objects allow you to associate data (the object's properties) with one or more methods. consequently, you can use a closure anywhere that you might normally use an object with only a single method. situations where you might want to do this are particularly common on the web. much of the code written in front-end javascript is event-based. you define some behavior, and then attach it to...
...And 2 more matches
Memory Management - JavaScript
mory management primitives such as malloc() and free(). in contrast, javascript automatically allocates memory when objects are created and frees it when they are not used anymore (garbage collection). this automaticity is a potential source of confusion: it can give developers the false impression that they don't need to worry about memory management. memory life cycle regardless of the programming language, the memory life cycle is pretty much always the same: allocate the memory you need use the allocated memory (read, write) release the allocated memory when it is not needed anymore the second part is explicit in all languages. the first and last parts are explicit in low-level languages but are mostly implicit in high-level languages like javascript. allocation in javascript v...
...ation of a and a2 elements. using values using values basically means reading and writing in allocated memory. this can be done by reading or writing the value of a variable or an object property or even passing an argument to a function. release when the memory is not needed anymore the majority of memory management issues occur at this phase. the most difficult aspect of this stage is determining when the allocated memory is no longer needed. low-level languages require the developer to manually determine at which point in the program the allocated memory is no longer needed and to release it. some high-level languages, such as javascript, utilize a form of automatic memory management known as garbage collection (gc). the purpose of a garbage collector is to monitor memory allocatio...
...e allocated memory is no longer needed. low-level languages require the developer to manually determine at which point in the program the allocated memory is no longer needed and to release it. some high-level languages, such as javascript, utilize a form of automatic memory management known as garbage collection (gc). the purpose of a garbage collector is to monitor memory allocation and determine when a block of allocated memory is no longer needed and reclaim it. this automatic process is an approximation since the general problem of determining whether or not a specific piece of memory is still needed is undecidable. garbage collection as stated above, the general problem of automatically finding whether some memory "is not needed anymore" is undecidable. as a consequence, garbage co...
...And 2 more matches
SyntaxError: JSON.parse: bad parsing - JavaScript
the javascript exceptions thrown by json.parse() occur when string failed to be parsed as json. ...
...he javascript exceptions thrown by json.parse() occur when string failed to be parsed as json. ...
...en string failed to be parsed as json. ...
...And 2 more matches
Intl.NumberFormat.prototype.resolvedOptions() - JavaScript
ons argument, or "auto" filled in as a default. usegrouping the values provided for these properties in the options argument or filled in as defaults. currency currencydisplay the values provided for these properties in the options argument or filled in as defaults. these properties are only present if style is "currency". ...
...gument, or "auto" filled in as a default. usegrouping the values provided for these properties in the options argument or filled in as defaults. currency currencydisplay the values provided for these properties in the options argument or filled in as defaults. these properties are only present if style is "currency". ...
..." filled in as a default. usegrouping the values provided for these properties in the options argument or filled in as defaults. currency currencydisplay the values provided for these properties in the options argument or filled in as defaults. these properties are only present if style is "currency". ...
...And 2 more matches
Intl.PluralRules.prototype.resolvedOptions() - JavaScript
p 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale. pluralcategories an array of plural categories used by the given locale, seleced from the list "zero", "one", "two", "few", "many" and "other". type the type used (cardinal or ordinal). ...
...anguage tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale. pluralcategories an array of plural categories used by the given locale, seleced from the list "zero", "one", "two", "few", "many" and "other". type the type used (cardinal or ordinal). ...
... led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale. pluralcategories an array of plural categories used by the given locale, seleced from the list "zero", "one", "two", "few", "many" and "other". type the type used (cardinal or ordinal). ...
...And 2 more matches
Strict mode - JavaScript
code. browsers not supporting strict mode will run strict mode code with different behavior from browsers that do, so don't rely on strict mode without feature-testing for support for the relevant aspects of strict mode. strict mode code and non-strict mode code can coexist, so scripts can opt into strict mode incrementally. strict mode makes several changes to normal javascript semantics: eliminates some javascript silent errors by changing them to throw errors. fixes mistakes that make it difficult for javascript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that's not strict mode. prohibits some syntax likely to be defined in future versions of ecmascript. see transitioning to strict mode, if you want to change your code ...
...-strict mode script: the entire concatenation looks strict! the inverse is also true: non-strict plus strict looks non-strict. obviously, concatenation of scripts is never ideal, but if you must, consider enabling strict on a function-by-function basis. you can also take the approach of wrapping the entire contents of a script in a function and having that outer function use strict mode. this eliminates the concatenation problem and it means that you have to explicitly export any shared variables out of the function scope. strict mode for functions likewise, to invoke strict mode for a function, put the exact statement "use strict"; (or 'use strict';) in the function's body before any other statements. function strict() { // function-level strict mode syntax 'use strict'; function n...
...s it impossible to accidentally create global variables. in normal javascript mistyping a variable in an assignment creates a new property on the global object and continues to "work" (although future failure is possible: likely, in modern javascript). assignments, which would accidentally create global variables, instead throw an error in strict mode: 'use strict'; // assuming no global variable mistypedvariable exists mistypevariable = 17; // this line throws a referenceerror due to the // misspelling of variable second, strict mode makes assignments which would otherwise silently fail to throw an exception. for example, nan is a non-writable global variable. in normal code assigning to nan does nothing; the developer receives no failure fee...
...And 2 more matches
JavaScript
read more about javascript. this section is dedicated to the javascript language itself, and not the parts that are specific to web pages or other host environments. for information about api specifics to web pages, please see web apis and dom. ...
...read more about javascript. this section is dedicated to the javascript language itself, and not the parts that are specific to web pages or other host environments. for information about api specifics to web pages, please see web apis and dom. the standard for javascript is ecmascript. as of 2012, all modern browsers fully support ecmascript 5.1. ...
...ecmascript 3. on june 17, 2015, ecma international published the sixth major version of ecmascript, which is officially called ecmascript 2015, and was initially referred to as ecmascript 6 or es6. since then, ecmascript standards are on yearly release cycles. this documentation refers to the latest draft version, which is currently ecmascript 2020. do not confuse javascript with the java programming language. both "java" and "javascript" are trademarks or registered trademarks of oracle in the u.s. and other countries. however, the two programming languages have a very different syntax, semantic, and use. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started tutorials le...
...And 2 more matches
Authoring MathML - MathML
as those used on this mdn wiki then a small mathml.css stylesheet might be enough. 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). there is also a similar script to display a warning at the top of the page for browsers without good mathml support and let the users choose between one of the fallback above: <script src="https://fred-wang.github.io/mathml-warning.js/mpadde...
...s"></script> note that these two scripts perform feature detection of the mspace or mpadded elements (see the browser compatibility table on these pages). there is also a similar script to display a warning at the top of the page for browsers without good mathml support and let the users choose between one of the fallback above: <script src="https://fred-wang.github.io/mathml-warning.js/mpadded-min.js"></script> if you don't want to use this link to github but instead to integrate these polyfills or others in your own project, you might need the detection scripts to verify the level of mathml support. for example the following function verifies the mathml support by testing the mspace element (you may replace mspace with mpadded): function hasmathmlsupport() { var div = document.create...
... system. it's also good to provide a fallback with web fonts. prior to gecko 31.0 (firefox 31.0 / thunderbird 31.0 / seamonkey 2.28), it was a bit tedious to setup math fonts, see the font instructions for mozilla 2.0. for gecko 31.0 (firefox 31.0 / thunderbird 31.0 / seamonkey 2.28), this is much simpler and is compatible with any web rendering engine with mathml support. ...
...And 2 more matches
Autoplay guide for media and Web Audio APIs - Web media technologies
ly under specific circumstances. autoplay availability as a general rule, you can assume that media will be allowed to autoplay only if at least one of the following is true: the audio is muted or its volume is set to 0 the user has interacted with the site (by clicking, tapping, pressing keys, etc.) if the site has been whitelisted; this may happen either automatically if the browser determines that the user engages with media frequently, or manually through preferences or other user interface features if the autoplay feature policy is used to grant autoplay support to an <iframe> and its document. otherwise, the playback will likely be blocked. the exact situations that result in blocking, and the specifics of how sites become whitelisted vary from browser to browser, but the abov...
... 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, ...
...ll probably want to be able to tell when it autoplay didn't begin. unfortunately, in the case of the autoplay attribute, recognizing whether or not autoplay successfully began is tricky. there's not an event triggered when autoplay fails. nor is there an exception thrown or a callback you can set up or even a flag on the media element that tells you if autoplay worked. all you can really do is examine a few values and make an educated guess as to whether or not autoplay worked. a better approach, if you're able to adjust the direction you look at things from, is to instead rely on knowing that playback of the media has successfully started, instead of when it fails to start. you can do this easily, by listening for the play event to be fired on the media element. the play event is sent both...
...And 2 more matches
Digital video concepts - Web media technologies
eing far less detailed. in essence, our eyes are like a camera with two image sensor chips: one greyscale and one color. the greyscale sensor is 120 megapixels, while the color sensor is only about 7 megapixels. these sensors physically occupy the same surface, called the retina, at the back of the eye. there are three types of cones, each of which responds to a particular wavelength band of incoming light, but also to the intensity of the light at that wavelength. each type of cone, then, captures the relative reponse peaks at various wavelengths, and the brain uses this data to figure out the intensity and hue of the color of the light arriving at that part of the retina. as our eyes capture a scene, they essentially take two photos at once: a finely-detailed greyscale image and a somewha...
...ution than the luma, when decoding the video to draw it to the screen each pixel's color is computed by calculating an appropriate color given the u and v values for the 4x2 block of 8 pixels in which the pixel resides. this decoding operation must mirror the method used during encoding, which is represented by three numbers separated by colons (":"). the first number specifies the number of luminance samples per row encoded from the 4x2 pixel block. this value is essentially always 4, meaning "use all of the luminance samples." the second number specifies how many chroma samples are used to represent the colors of the pixels in the first row. the third number indicates how many chroma samples are used to represent the colors of the pixels in the second row. the table below shows examp...
...aning "use all of the luminance samples." the second number specifies how many chroma samples are used to represent the colors of the pixels in the first row. the third number indicates how many chroma samples are used to represent the colors of the pixels in the second row. the table below shows examples of three chroma subsampling models. 4:2:0 4:2:2 4:4:4 luminance chroma (u and v) decoded pixels in all of these, all four pixels of each row in the block of luminance data are used in the decoded image. looking at 4:2:0 chroma subsampling, in the first column, the value 2 indicates that the first row of chroma data has two samples in it; the 0 indicates that the second row has no chroma samples ...
...And 2 more matches
Progressive web app structure - Progressive web apps (PWAs)
en pages is smooth because the client can re-render the page with only the parts that have changed. pwas can be built using any approach you like, but some will work better than the others. the most popular approach is the "app shell" concept, which mixes ssr and csr in exactly the way described above, and in addition follows the "offline first" methodology which we will explain in detail in upcoming articles and use in our example application. there is also a new approach involving the streams api, which we'll mention briefly. app shell the app shell concept is concerned with loading a minimal user interface as soon as possible and then caching it so it is available offline for subsequent visits before then loading all the contents of the app. that way, the next time someone visits the ap...
..., safe in the knowledge that the app will still work ok if they are not supported by the user's browser — this is the beauty of progressive enhancement. the website feels like a native app with instant interaction and solid performance while keeping all the benefits of the web. being linkable, progressive and responsive by design it's important to remember the pwa advantages and keep them in mind when designing the application. the app shell approach allows websites to be: linkable: even though it behaves like a native app, it is still a website — you can click on the links within the page and send a url to someone if you want to share it. progressive: start with the "good, old basic website” and progressively add new features while remembering to detect if they are available in ...
...s grid. different concept: streams an entirely different approach to server- or client-side rendering can be achieved with the streams api. with a little help from service workers, streams can greatly improve the way we parse content. the app shell model requires all the resources to be available before the website can start rendering. ...
...And 2 more matches
Structural overview of progressive web apps - Progressive web apps (PWAs)
ween pages is smooth because the client can re-render the page with only the parts that have changed. pwas can be built using any approach you like, but some will work better than the others. the most popular approach is the app shell concept, which mixes ssr and csr in exactly the way described above, and in addition follows the "offline first" methodology which we will explain in detail in upcoming articles and use in our example application. there is also a new approach involving the streams api, which we'll mention briefly. the app shell concept the app shell concept is concerned with loading a minimal user interface and content as soon as possible, caching it so it's available offline for subsequent visits before then loading the remainder of the app's contents. that way, the next tim...
... safe in the knowledge that the app will still work ok if they are not supported by the user's browser — this is the beauty of progressive enhancement. the website feels like a native app with instant interaction and solid performance while keeping all the benefits of the web. being linkable, progressive, and responsive by design it's important to remember the pwa advantages and keep them in mind when designing the application. the app shell approach allows websites to be: linkable: even though it behaves like a native app, it is still a website — you can click on the links within the page and send a url to someone if you want to share it. progressive: start with the "good, old basic website” and progressively add new features while remembering to detect if they are available in ...
...ss grid. another approach: streams an entirely different approach to server- or client-side rendering can be achieved with the streams api. with a little help from service workers, streams can greatly improve the way we parse content. the app shell model requires all the resources to be available before the website can start rendering. it's different with html, as the browser is actually streaming the data already and you can see when the elements are loaded and rendered on the website. to have the javascript actually work, however, it has to be downloaded in its entirety. the streams api allows developers to have direct access to data streaming from the server. if you want to perform an operation on the data (for example, adding a filter to a video), you no longer need to wait for all o...
...And 2 more matches
SVG Presentation Attributes - SVG: Scalable Vector Graphics
svg presentation attributes are css properties that can be used as attributes on svg elements. ...
...-bidi vector-effect visibility word-spacing writing-mode attributes alignment-baseline it specifies how an object is aligned along the font baseline with respect to its parent. value: auto|baseline|before-edge|text-before-edge|middle|central|after-edge|text-after-edge|ideographic|alphabetic|hanging|mathematical|inherit; animatable: yes baseline-shift it allows repositioning of the dominant-baseline relative to the dominant-baseline of the parent text content element. value: auto|baseline|super|sub|<percentage>|<length>|inherit; animatable: yes clip deprecated it defines what portion of an element is visible. value: auto|<shape()>|inherit; animatable: yes clip-path it binds the element it is applied to with a given <clippath> element. value: none|<funciri>|inherit; animata...
... of the parent text content element. value: auto|baseline|super|sub|<percentage>|<length>|inherit; animatable: yes clip deprecated it defines what portion of an element is visible. value: auto|<shape()>|inherit; animatable: yes clip-path it binds the element it is applied to with a given <clippath> element. value: none|<funciri>|inherit; animatable: yes clip-rule it indicates how to determine what side of a path is inside a shape in order to know how a <clippath> should clip its target. value: nonezero|evenodd|inherit; animatable: yes color it provides a potential indirect value (currentcolor) for the fill, stroke, stop-color, flood-color and lighting-color presentation attributes. value: <color>|inherit; animatable: yes color-interpolation it specifies the color space for grad...
...And 2 more matches
<symbol> - SVG: Scalable Vector Graphics
Web › SVG › Element › symbol
; default value: xmidymid ...
...y:0.4" /> <use xlink:href="#mydot" x="65" y="5" style="opacity:0.2" /> </svg> attributes height this attribute determines the height of the symbol. value type: <length>|<percentage> ; default value: auto; animatable: yes preserveaspectratio this attribute defines how the svg fragment must be deformed if it is embedded in a container with a different aspect ratio. value type: (none| xminymin| xmidymin| xmaxymin| xminymid| xmidymid| xmaxymid| xminymax| xmidymax| xmaxymax) (meet|slice)? ...
...>|<percentage> ; default value: auto; animatable: yes preserveaspectratio this attribute defines how the svg fragment must be deformed if it is embedded in a container with a different aspect ratio. value type: (none| xminymin| xmidymin| xmaxymin| xminymid| xmidymid| xmaxymid| xminymax| xmidymax| xmaxymax) (meet|slice)? ; default value: xmidymid meet; animatable: yes refx this attribute determines the x coordinate of the reference point of the symbol. value type: <length>|<percentage>|left|center|right ; default value: 0; animatable: yes refy this attribute determines the y coordinate of the reference point of the symbol. value type: <length>|<percentage>|top|center|bottom ; default value: 0; animatable: yes viewbox this attribute defines the bound of the svg viewport for the curre...
...And 2 more matches
Modules - Archive of obsolete content
of these things using the built-in components object provided by xulrunner application such as firefox and thunderbird. to improve encapsulation, each module should be defined in the scope of its own global object. this is made possible by the use of sandboxes. each sandbox lives in its own compartment. a compartment is a separate memory space. each compartment has a set of privileges that determines what scripts running in that compartment can and cannot do. we will show how sandboxes and compartments can be used to improve security in our module system. 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...
...the object it passed to the loadsubscript function is an ordinary object, which has the global object of the loading script as its prototype. this breaks encapsulation, as it allows the script being loaded to access the built-in constructors of the loading script, which are defined on its global object. the problem with breaking encapsulation like this is that malicious scripts can use it to g...
...eparate compartment. compartments are a fairly recent addition to spidermonkey, and can be seen as a separate memory space. objects living in one compartment cannot be accessed directly from another compartment: they need to be accessed through an intermediate object, known as a wrapper. ...
...passing an xul url will result in a compartment with chrome privileges (note, however, that if you ever actually do this in any of your code, gabor will be forced to hunt you down and kill you). otherwise, the compartment will have content privileges by default. ...
jpm - Archive of obsolete content
addon-dir - directory for your source code, defaulting to the current directory installation jpm is distributed with the node package manager npm. installing npm there are two ways to get npm. download and install node.js from nodejs.org. node.js includes npm. or, if you have a package manager like apt, install npm via that. for example, in an ubuntu or debian terminal window, enter sudo apt-get install nodejs nodejs-legacy npm. to test your installation, run: /usr/bin/env node -v if you get an error message saying /usr/bin/env: node: no such file or directory and you have installed nodejs through a package manager, nodejs may have been installed under a different executable name. to ensure compatibility with jpm, however, it must be present in your pat...
...o apt-get install nodejs-legacy on other distributions, you may have to create a local symlink to nodejs manually: sudo ln -s "$(which nodejs)" /usr/local/bin/node installing jpm after you have npm installed and node on your path, install jpm just as you would any other npm package. installing jpm globally npm install jpm --global depending on your setup, you might need to run this as an administrator: sudo npm install jpm --global installing jpm locally if you do not wish to, or are unable to, install jpm globally, you may instead install it locally: cd $home && npm install jpm to run jpm from a terminal when installed locally, you must add the directory "$home/node_modules/.bin/" to your terminal's path first. add the following line to the end of the file $home/.profile to add it...
...ish to, or are unable to, install jpm globally, you may instead install it locally: cd $home && npm install jpm to run jpm from a terminal when installed locally, you must add the directory "$home/node_modules/.bin/" to your terminal's path first. 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. note that unlike cf...
... jpm is available in every command prompt you start, as long as you installed it with the --global flag. install a different version of firefox as of firefox 48, it is not possible to use unsigned add-ons (i.e. any add-on which you are in the process of developing) in the branded release or beta versions of firefox. thus, you will need to download and install a different version of firefox. assuming you don't want an old version of firefox, your options are firefox developer edition, firefox nightly, unbranded beta, or unbranded release. when testing your add-on, you will need to use the -b option to jpm run. see selecting a browser version. problems? if you do not see this, ask for help. sdk users and project team members discuss problems and proposals on the project mailing list. someo...
Examples and demos from articles - Archive of obsolete content
ep track of all events started and then to stop them when appropriate through the cleartimeout() function. a possible approach to solve this problem is to nest all the informations needed by each animation to start, stop, etc. etc. in different objects and then to create a constructor for such class of objects in order to standardize and simplify the instantiation of them. here is a possible and minimalist example of such abstraction, which for this reason we named minidaemon. [article] image preview before upload [html] the filereader.prototype.readasdataurl() method is useful, for example, to get a preview of an image before uploading it. [article] note: the filereader() constructor was not supported by internet explorer for versions before 10. for a full compatibility code, see also ou...
...[article] css pure-css dropdown menu [html] with the :hover pseudo-class you can create complex cascade algorithms. ...
...ototype.readasdataurl() method is useful, for example, to get a preview of an image before uploading it. [article] note: the filereader() constructor was not supported by internet explorer for versions before 10. for a full compatibility code, see also our crossbrowser possible solution for image preview. determine if an element has been totally scrolled [html] this example shows how to determine whether a user has completely scrolled an element or not. [article] css pure-css dropdown menu [html] with the :hover pseudo-class you can create complex cascade algorithms. this is a common technique used, for example, in order to create pure-css dropdown menus (that is only css, without using javascript). .[article] pure-css web gallery based on the :hover pseudoclass [zip] you can use...
...odify many properties of dom objects at the same time. filter the digitation into a form field, capture the digitation of a hidden word this example shows the use of the onkeypress event during a digitation into a form field. ajax – submitting forms and uploading files this paragraph shows how to submit forms in pure-ajax. multipage ajax navigation example this article provides a working (minimalist) example of a pure-ajax web site composed only of three pages. do something if current document has changed since last visit here is a possible example of how to show an alert message when current document changes. do something if an external page has changed since last visit here is a possible example of how to show an alert message when an external page changes. import scripts here...
How to convert an overlay extension to restartless - Archive of obsolete content
into a restartless (bootstrapped) extension that is also extractionless. requirements first off, what kind of add-on are we talking about here? well, xul overlays and windows, jsm files, chrome & resource mappings with localization, default preferences, but no xpcom components of your own. some of that will have to be replaced and the rest will need to be loaded differently. next, what's the minimum version of firefox we should require (preferably an esr)? this guide targets firefox 17 esr or later (or anything else gecko 17+, such as seamonkey 2.14+). this is two esrs back (as of this writing), which should be plenty. 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. there will be no usage o...
...olves using firebug.sdk. the next is example of the code: var overlay = toolbarbutton(toolbarbuttonattrs, panel({'id': 'thepanel', 'type': 'arrow'}, hbox({'align': 'start'}, vbox( hbox({'class': 'pixel-hbox'}, description({'value': this.stringbundle.getstringfromname('firexpixel.opacity')}), htmlinput({'id': 'opacity-range', 'type': 'range', 'min': '0', 'max': '10'}) ), hbox({'id': 'pixel-coords', 'class': 'pixel-hbox'}, label({'control': 'coord-x', 'value': 'x:'}), textbox({'id': 'coord-x', 'class': 'coord-box', 'placeholder' : '0'}), label({'control': 'coord-y', 'value': 'y:'}), textbox({'id': 'coord-y', 'class': 'coord-box', 'placeholder': '0'}) ... that way...
...xpcomutils.jsm"); xpcomutils.definelazygetter(this, "strings", function() { return loadpropertiesfile("chrome://myaddon/locale/mystrings.properties"); }); function loadpropertiesfile(path) { /* hack: the string bundle cache is cleared on addon shutdown, however it doesn't appear to do so reliably. errors can erratically happen on next load of the same file in certain instances. (at minimum, when strings are added/removed) the apparently accepted solution to reliably load new versions is to always create bundles with a unique url so as to bypass the cache. this is accomplished by passing a random number in a parameter after a '?'. (this random id is otherwise ignored) the loaded string bundle is still cached on startup and should still be cleared out of the ...
...js:startup() rather than a "load" handler in a xul overlay. your localization handling should be unaffected by your transition to a restartless/extractionless add-on so long as you properly clear the chrome cache on add-on shutdown and load your properties files using the method listed above. your property files and dtd files loaded from chrome:// uris should work just as before. this is all assuming a minimum version of firefox 17+ (or other gecko 17+ application) which you should remember to state explicitly in your install.rdf. just remember that whatever you start you also need to have the ability to undo. in order for your add-on to reliably update without a restart it needs to be able to shutdown/disable cleanly. also note that once you do get this all up and running, your users will...
Multiple item extension packaging - Archive of obsolete content
file extension) and themes (e.g. jar file extension). the basic structure is shown below: /install.rdf install manifest /extension1.xpi extension /extension2.xpi extension /theme1.jar theme /theme2.jar theme ... the extension manager will read the install.rdf install manifest to determine if this is a multiple item package and then start the installation of the individual packages it contains automatically. no other files besides the install.rdf install manifest and the files with a jar and xpi file extension will be extracted or utilized. install.rdf a multiple item package does not have the same requirements as an extension for its install.rdf. the only required properties ar...
... automatically. no other files besides the install.rdf install manifest and the files with a jar and xpi file extension will be extracted or utilized. install.rdf a multiple item package does not have the same requirements as an extension for its install.rdf. the only required properties are em:id, em:targetapplication, and em:type. for the firefox and thunderbird 1.5 extension manager to determine that the package is a multiple item package, the em:type specified in your install.rdf must be 32 and specified as <em:type nc:parsetype="integer">32</em:type>. the xml namespace xmlns:nc="http://home.netscape.com/nc-rdf#" must also be declared in your install.rdf as shown below. ... <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:nc="http://home.netscape.com/nc-rdf#" x...
...erbird 2.0 extension manager you can use the above syntax or <em:type>32</em:type> as shown below. ... <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest"> <!-- nsiupdateitem type for a multiple item package --> <em:type>32</em:type> ... when specifying em:targetapplication the minversion specified should be the highest minversion and the maxversion specified should be the lowest maxversion from all of the installable bundles contained by the multiple item package for the em:targetapplication. if this is not done, any items that are not compatible will not be installed unless a compatibility check discovers updated compatibility information. installation installation can ...
...tem packages, all internal add-ons need to be signed, but the container doesn't need to be signed. this means that the contained add-ons need to be submitted to amo individually for signing. additionally, the container add-on id must not be the same as the id of any of the contained add-ons. official references for toolkit api official references. do not add to this list without contacting benjamin smedberg. note that this page is included from the pages listed below. so: don't add breadcrumbs! structure of an installable bundle: describes the common structure of installable bundles, including extensions, themes, and xulrunner applications extension packaging: specific information about how to package extensions theme packaging: specific information about how to package themes multiple...
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
underbird, choose "comm. central". calling xpcom from xpconnect use the xpconnect technology to use xpcom in javascript. listing 1 shows how you can use xpconnect to acquire references to xpcom services and create new xpcom objects. each component is identified with a contract id in the form @domain_name/module_name/component_name;version_number, and implements one or more interfaces that determine what functions can be called on these components. interfaces names usually have the forms nsixxx. in order to have access to the corresponding functions, it is necessary to use the component with the interface you want to use. some xpcom components are services, that means only one instance in memory. for instance, this is the case for the bookmarks component, which is actually a service. it let...
... the file's scripts without manual confirmation, add the contents of listing 3 to the prefs.js file in the user profile folder. opening test.xul will show the local file url in the location bar. copy and paste this into the appropriate spot in listing 3. note: the location of the user profile will vary depending on your system. ...
...ameter gives the access privileges to that file using unix-style octal values. note: windows ignores the privileges parameter; other platforms may do so as well. the nsilocalfile object includes methods that return virtual state values for the current file, as shown in table 1. table 1: methods for checking file states method name description nsilocalfile.exists() determines whether or not the file exists. nsilocalfile.iswriteable() determines whether or not the file can be written to. nsilocalfile.isreadable() determines whether or not the file can be read. nsilocalfile.isexecutable() determines whether or not the file can be executed. nsilocalfile.ishidden() determines whether or not the file is hidden. nsi...
...s. nsilocalfile.iswriteable() determines whether or not the file can be written to. nsilocalfile.isreadable() determines whether or not the file can be read. nsilocalfile.isexecutable() determines whether or not the file can be executed. nsilocalfile.ishidden() determines whether or not the file is hidden. nsilocalfile.isdirectory() determines whether or not the reference is to a directory. nsilocalfile.isfile() determines whether or not the reference is to a file. nsilocalfile.issymlink() determines whether or not the reference is to a symlink. traversing directories moving into a directory use the nsilocalfile.append() method to drill down into a directory (or file). see listing 8. listing 8: trave...
Appendix D: Loading Scripts - Archive of obsolete content
oad arbitrary code into components.utils.sandbox objects. javascript files or urls may be loaded in this manner by first retrieving their contents into memory using an xmlhttprequest. this is the method used by jetpack's securable module system to load nearly all executable code. advantages namespacing: since scripts executed via evalinsandbox run in a defined namespace, global namespace contamination and the resultant extension compatibility issues are not usually a problem. flexibility: the evalinsandbox method accepts several parameters, including the url, line number, and javascript version of the file from which the code being evaluated was extracted. this information is invaluable for debugging, and the flexibility with which it can be specified makes this method useful for extract...
...l associated with the target object. these scripts execute with the same privileges and restrictions of the global associated with the target object, and this method can therefore also be used when with sandbox objects with the same effect as evalinsandbox and into content windows with the same effect as injecting script tags into their documents. advantages namespacing: global namespace contamination and the resultant extension compatibility issues can often be avoided by loading sub-scripts into private namespaces. flexibility: the sub-script loader can load scripts into a variety of different namespaces for a wide variety of uses, and as of gecko 2 allows the character set of the script to be specified. performance: as of gecko 8.0, scripts loaded via mozijssubscriptloader.loadsubscr...
...ance: javascript modules are stored in a pre-compiled format in a cache, and therefore load with significantly less overhead than other types of scripts. additionally, scripts are loaded only once globally per session, and therefore have virtually no overhead for multiple imports. namespacing: javascript modules, like javascript components, are loaded into their own private scope. namespace contamination and the resulting compatibility issues are only an issue when they are imported into shared global namespaces. data sharing: as modules are loaded only once globally, every import has access to the same data and global variables no matter what context or window it was imported from. javascript modules can therefor be used for communication and data sharing between otherwise isolated context...
...iple callbacks. safety: as workers have no access to objects which might cause a crash or deadlock when executed re-entrantly or by spinning the event loop, there are significant safety advantages over other methods of asynchronous execution. disadvantages limited scoping: as data from the main thread may only be accessed via json message passing, there are significant difficulties in performing many operations in worker scopes. dom access: as there is no dom access in worker scopes, xmlhttprequests may not easily be used with xml or html sources, and should instead only be used with json or other text-based sources. debugging: jsd knows nothing about workers and no javascript debuggers work on them. ...
Intercepting Page Loads - Archive of obsolete content
r code snippets page. in a nutshell, from the chrome code in the overlay we add an event listener for the load event. this._loadhandler = function() {that._onpageload(); }; gbrowser.addeventlistener("load", this._loadhandler, true); gbrowser is a global object that corresponds to the tabbrowser element in the main browser window. it is full of useful functions, so you should always keep it in mind when you want to handle tabs and web content windows. attaching the load event handler to gbrowser allows us to listen to these events for all tabs, without having to worry how many tabs are open. gbrowser exists in every browser window. we store the handler function in a private variable because later we want to remove it when we do not need it anymore. gbrowser.removeeventlistener("load", thi...
...om service or jsm module). otherwise you have to make sure to avoid duplicated work if you have 2 or more windows open. there are 2 http topics you can listen to, as specified in the observer notifications page: topic description http-on-modify-request called as an http request is made. the channel is available to allow you to modify headers and such. http-on-examine-response called after a response has been received from the webserver. headers are available on the channel. the subject argument on the observe method is the nsihttpchannel object that corresponds to the http channel being opened or already opened, depending on the topic. observe : function(asubject, atopic, adata) { if (topic_modify_request == atopic) { let url; asubject.
...proach for the typical greasemonkey-style extensions. notes on usage: efficiency is very important when adding http observers. remember that your observe method will be called for every http request made by firefox, usually several dozen per page visit. in the previous example, one of the first things we do is check if the url is of interest to us, otherwise we let it go. avoid heavy, time-consuming operations, or the user's browsing experience will become exasperating. . you have to take into account that a page load may involve several http requests, specially when redirects are involved. if you enter gmail.com in your browser, you will probably be redirected a few times before reaching the page that actually displays any content. all of these "hops" will involve a call to your observer...
...ned before applies here as well, except you'll be receiving all the events for all tabs and windows in a single object, and you don't have to worry about adding and removing listeners every time a tab is opened or closed. this also has the advantage of detecting page loads anywhere in the application, not only in browser windows. if you are building a web filtering extension, you should keep in mind that xul windows such as the dom inspector window and the add-ons manager window allow (limited) web navigation. other extensions might add xul windows that allow navigation as well, so in those cases it's best to use a global solution like this one. content policy finally, there is the option of implementing nsicontentpolicy. you can create an xpcom component that extends nsicontentpolicy and...
Using Dependent Libraries In Extension Components - Archive of obsolete content
, it is in the libraries/ directory. extension-directory/install.rdf extension-directory/libraries/dependent1.dll extension-directory/libraries/dependent2.dll extension-directory/libraries/component.dll extension-directory/components/interface1.xpt extension-directory/components/interface2.xpt extension-directory/components/bsmedberg_stub.dll extensions/stub/makefile.in # copyright (c) 2005 benjamin smedberg <benjamin@smedbergs.us> depth = ../.. srcdir = @srcdir@ topsrcdir = @top_srcdir@ vpath = @srcdir@ include $(depth)/config/autoconf.mk module = bsmedberg library_name = bsmedberg_stub is_component = 1 force_shared_lib = 1 requires = \ xpcom \ string \ $(null) cppsrcs = bdsstubloader.cpp extra_dso_ldopts += \ $(dist)/lib/$(lib_prefix)xpcomglue_s.$(lib_suffix) \ $(xpcom_frozen_ld...
...berg_stub is_component = 1 force_shared_lib = 1 requires = \ xpcom \ string \ $(null) cppsrcs = bdsstubloader.cpp extra_dso_ldopts += \ $(dist)/lib/$(lib_prefix)xpcomglue_s.$(lib_suffix) \ $(xpcom_frozen_ldopts) \ $(nspr_libs) \ $(null) include $(topsrcdir)/config/rules.mk defines += -dmoz_dll_prefix=\"$(dll_prefix)\" extensions/stub/bdsstubloader.cpp // copyright (c) 2005 benjamin smedberg <benjamin@smedbergs.us> #include "nscore.h" #include "nsmodule.h" #include "prlink.h" #include "nsilocalfile.h" #include "nsstringapi.h" #include "nscomptr.h" static char const *const kdependentlibraries[] = { // dependent1.dll on windows, libdependent1.so on linux moz_dll_prefix "dependent1" moz_dll_suffix, moz_dll_prefix "dependent2" moz_dll_suffix, nsnull // note: if the...
...) with the flag nsaddimage_option_match_filename_by_installname. the following are the necessary modifications you will need in order to write a stub loader for an os x extension. you will also need to make sure you are properly linking the xpcom glue libraries. see xpcom glue for the proper flags on how to link to the glue libraries. /* * os x stubloader * original stubloader code by benjamin smedberg <benjamin@smedbergs.us> copyright (c) 2005 * adapted for os x by walter johnson <zinkyu@gmail.com>, sept. 2008 */ //include the stuff from mozilla glue that we need #include "nsilocalfile.h" #include "nsstringapi.h" #include "nscomptr.h" //include things from the mach-o libraries that we need for loading the libraries. #include <mach-o/loader.h> #include <mach-o/dyld.h> static char...
...on't care if this failed! if you update your dependencies in your component, // but forget to remove a dependant library in the stubloader, then we don't want to // fail loading the component since the dependant library isn't required. // // 2) we are going to leak this library. we don't care about that either. // nsaddimage adds the image to the process. when the process terminates, the library // will be properly unloaded. } library->setnativeleafname(ns_literal_cstring(krealcomponent)); rv = library->getnativepath(path); if (ns_failed(rv)) return rv; const mach_header * componentlib = nsaddimage(path.get(), nsaddimage_option_return_on_error | nsaddimage_option_with_searching | nsaddimage_option_match_filename_by_installname); if (co...
Creating a Release Tag - Archive of obsolete content
warning: the content of this article may be out of date. it has not been updated for usage of mercurial. here are directions for creating a release from a linux system. note that there are a couple of extra files for win32 and macintosh that aren't pulled by the normal script and need to be pulled by hand. the mini-branch is created so you can check in the build scripts with the necessary changes without touching the original branch. ...
... you can check in the build scripts with the necessary changes without touching the original branch. check out mozilla from the branch you want to tag. remember to also check out extra mac and win32 files that aren't normally checked out on linux or the tag won't build on those platforms. ...
...heck out extra mac and win32 files that aren't normally checked out on linux or the tag won't build on those platforms. cvs co -r netscape_6_2_release mozilla/client.mk cd mozilla gmake -f client.mk checkout create a mini branch for the pull scripts on all three platforms so we can change them without changing anything on the original branch. cd .. cvs tag -b mozilla_0_9_4_1_release_mini_branch mozilla/client.mk delete the existing build scripts and repull them from the mini-branch you just created. rm mozilla/client.mk cvs co -r mozilla_0_9_4_1_release_mini_branch mozilla/client.mk in each of the build scripts find the variables defining the branch and change it from the branch you originally pulled from to the new tag you are creating. mozilla/client.mk ...
... cvs ci mozilla/client.mk create the tag. find . ...
New Skin Notes - Archive of obsolete content
including required graphics. -- dria when will these fixes be on the live site? --nickolay 10:38, 31 aug 2005 (pdt) existing fixes should be on test/docs/ now. --dria stuff that's been fixed note that while i've made these fixes, they haven't necessarily been checked in yet. edit page textarea needs to 'scale' better with page width (so large whitespace area's are non-existant), suggest min-width:some-em-size; width: 88%; and max-width set to 95% or something like that. --callek i tried this, but it gets totally screwed up in ie for some reason. i'll try again, but can't guarantee this will be fixed for the initial upgrades. --dria took two days, but i finally got this sorted out. when the skin is updated on test/docs, editform textarea should be resizeable in all browsers. yay! -...
...ally feel like buttons; maybe add a pseudo-class for onhover that gives them an underline? --beltzner the "+" item under the "views" menu of a discussion page looks really out of place. can we replace it with "add section" or something? --beltzner i'll look into it, but i think this is one of those "don't hold your breath" things because that's not managed by the skin. i could probably just eliminate it entirely. that'd work, too; you'd mentioned that it was very rarely used --beltzner the category template must be improved, it looks very unpolished comparing to rest of devmo. -- gandalf unfortunately the category styling is very much embedded into the mediawiki code. there are some other changes i need to make, however, so i'll try to fix it up a bit while i'm digging around in ther...
... we can mobe the "main page" scrollbar to the actual "content area" of the page, so that the sidebar `stays` when in-use, and on dynamic pages (such as the preferences page) if you toggle between something that needs a verticle scrollbar and something that doesnt, you get screen-jitter; if this is not-feasable, perhaps some method to have a viewport scrollbar always appear for the vert direction. minor-nit. --callek i couldn't find a quick "logout" link accessible from everywhere. --mmondor 12:25, 26 aug 2005 (pdt) what pages can you not find a logout link from, i see it on nearly all devmo wiki pages in the "upper right: along with "my talk" "preferences" etc. oh, i went back to login page, logged in and then from there went to the /test/ pages and it's like the old look (with menu bar a...
...d to english version. it's a bug. --gandalf 00:39, 31 aug 2005 (pdt) link url fixed for wiki skin only. tab text will currently remain untranslated ("documentation"). devnews and webwatch are not currently being localised so shall remain as they are, with link to english wiki. --dria further notes and ideas (future) skin designed more for the editorial crowd, with the editor tools more prominently placed in the skin. the core format would be the same as "default", however. skin designed with simplicity in mind -- minimal header, nav, footer -- plausibly good for alternate or small screen display, or people who prefer more straight-up formatting for on-screen docs. skin designed specifically with accessibility in mind. might want to consult with aaronlev to see what would be best. ...
Static Analysis for Windows Code under Linux - Archive of obsolete content
we highly recommend you to read the cross compiling manual and the dehydra build manual before you start the following reading. build gcc corss-compiler with plugin support by default gcc does not support plugins. ...
...difference with building one for a linux native compiler. so, please follow this link exactly. check the build make check if all tests past, you have gotten a workable dehydra. build treehydra build the treehydra plugin building treehydra for a cross compiler is something tricky. that is because the gcc with plugin support is needed to produce treehydra shared library. but we just made a mingw cross compiler, that means it can't produce the correct shared library. so, we should make a linux native compiler with plugin support to make treehydra! this sound crazy, but it may be the only right way to do this. just follow this and this to compile both dehydra and treehydra shared libraries. and these libraries can be used directly with our cross compiler. check the build run: make ch...
...ndows code static analysis is hooked into mozilla repository from mozilla 2. you can obtain mozilla 2 code by: hg clone http://hg.mozilla.org/mozilla-central/ and compose a .mozconfig file for cross-compiling mozilla with static analysis hooked: #specify the cross compile cross_compile=1 ac_add_options --enable-application=browser ac_add_options --host=i686-linux ac_add_options --target=i686-mingw32 ac_add_options --enable-default-toolkit=cairo-windows mk_add_options moz_objdir=@topsrcdir@/../mozilla-mingw # mozilla trunk uses many vista only features on windows, so we should disable some components to make it buildable with mingw32. ac_add_options --enable-debug ac_add_options --disable-optimize ac_add_options --disable-tests ac_add_options --disable-embedding-tests ac_add_options ...
...ater #change this to where your libidl-config file locate. host_libidl_config=/usr/bin/libidl-config #config your moztools position glib_prefix=$home/moztools libidl_prefix=$home/moztools #disable xpcom stdcall calling convention because of gcc 4.3.0 bug cppflags="-dmoz_disable_xpcom_stdcall" #specify the cxx and static analysis #point cxx to the cross compile g++ with plugin support cxx=$home/mingw-install/bin/i686-mingw32-g++ ac_add_options --with-static-checking=$home/dehydra/dehydra-gcc/gcc_dehydra.so then, you can start building your mozilla. the static check will be done when compiling is going on. troubles you can post any question about static check to the mozilla.dev.static-analysis newsgroup and any question about cross compiling to the mozilla.dev.builds newsgroup. ...
Tamarin Build System Documentation - Archive of obsolete content
y. if an error or failure occurs on any slave in a phase the build stops. the next phase is started when all slaves have completed the previous phase successfully. the compile phase compiles all of the tamarin source code and builds all of the shell executables, any errors will stop the phase and a red box will appear on the slave where the error occurred. ...
...ops. the next phase is started when all slaves have completed the previous phase successfully. the compile phase compiles all of the tamarin source code and builds all of the shell executables, any errors will stop the phase and a red box will appear on the slave where the error occurred. the compile phase takes about 20-25 minutes. the smoke phase runs a set of tests on each platform until 2 minute is exceeded. the set of smoke tests can contain any shell build and any test suite (including performance). the smoke test list is constantly updated to contain the most recent failures, most frequent failures, and the newest testcases. the idea is to catch test failures in a few minutes rather than running the complete test run (1h 45m). the smoke test including downloading the shell take...
...ded. the set of smoke tests can contain any shell build and any test suite (including performance). the smoke test list is constantly updated to contain the most recent failures, most frequent failures, and the newest testcases. the idea is to catch test failures in a few minutes rather than running the complete test run (1h 45m). the smoke test including downloading the shell takes about 3-4 minutes. the test phase runs all functional testcases including acceptance tests, cmdline tests, and selftests. the acceptance tests are the majority and are run on all shells (release, release-debugger, debug, debug-debugger). the test phase takes approximately 1 hour 45 minutes. the performance and deep phases do not run synchronously. the phases run when slaves are available and the other phase...
...mance and deep phases do not run synchronously. the phases run when slaves are available and the other phases do not wait for completion to start the next build. how are builds triggered? checkins (hg push) to http://hg.mozilla.org/tamarin-redux and sandbox requests will trigger a buildbot build when all build slaves are idle the next build begins before the build begins buildbot waits for 2 minutes of no checkin activity the build system prioritizes tamarin-redux checkins over sandbox builds when several tamarin-redux checkins occur the newest change is built including all checkins since the last build each sandbox build occurs in the order they were submitted, the submitter may cancel a build. how do i build a sandbox build? create a user repository, instructions are https://develo...
URIs and URLs - Archive of obsolete content
asis for protocols like "about". nssimpleuri contains setters and getters for the uri and the components of an uri: scheme and path (non-scheme). there are no pre written urlparsers for simple uris, because of it's simple structure. nsstandardurl the most important implementation of nsiurl is nsstandardurl which is the basis for protocols like http, ftp, ... these schemes support a hierarchical naming system, where the hierarchy of the name is denoted by a "/" delimiter separating the components in the path. nsstandardurl also contains the facilities to parse these typ of urls, to break the specification of the url "spec" down into the most basic segments. the spec consists of prepath and path. the prepath consists of scheme and authority. the authority consists of prehost, host and port. the...
...lowing syntax: scheme://username:password@host:port/directory/filebasename.fileextension;param?query#ref for performance reasons the complete spec is stored in escaped form in the nsstandardurl object with pointers (position and length) to each basic segment and for the more global segments like path and prehost for example. necko provides pre written urlparsers for schemes based on hierachical naming systems. escaping to be able to parse an url safely it is sometimes necessary to "escape" certain characters, to hide them from the parser. an escaped character is encoded as a character triplet, consisting of the percent character "%" followed by the two hexadecimal digits representing the octet code. for example, "%20" is the escaped encoding for the us-ascii space character. another quote fr...
...rfc 2396: a uri is always in an "escaped" form, since escaping or unescaping a completed uri might change its semantics. normally, the only time escape encodings can safely be made is when the uri is being created from its component parts; each component may have its own set of characters that are reserved, so only the mechanism responsible for generating or interpreting that component can determine whether or not escaping a character will change its semantics. likewise, a uri must be separated into its components before the escaped characters within those components can be safely decoded. this implies that the segments of urls are escaped differently. this is done by ns_escapeurl which is now part of xpcom, but started as part of necko. the information how to escape each segment is stored ...
...this decision is based on an email by roy t. fielding, one of the authors of rfc 2396, stating that the given example is wrong. details can be found at bug 90439. registry-based authoritys currently necko's url-objects only support host based authoritys or urls with no authoritys. registry-based authoritys as defined in rfc 2396 many uri schemes include a top hierarchical element for a naming authority, such that the namespace defined by the remainder of the uri is governed by that authority. this authority component is typically defined by an internet-based server or a scheme-specific registry of naming authorities. ... the structure of a registry-based naming authority is specific to the uri scheme, but constrained to the allowed characters for an authority component. are not sup...
Elements - Archive of obsolete content
: 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. keep in mind that the binding is still required to have an id even though you're not referencing it. in addition, data: urls are only supported from chrome code (in other words, from the application or an extension). note: the normal same-origin policy is used for web sites; they can only link to xbl files on the same domain, or within the chrome. for clarity's sake, here's what the embedded xml in the pre...
...entifier. field <!element field empty> <!attlist field id id #implied name cdata #required readonly (true|false) #implied > a field is similar to a property, except that it should not have a getter or setter. it is useful as a simple holder for a value. the field element must have content which is code that determines the initial value of the field. the field tag must be inside the implementation tag. id - the id attribute is a document-unique identifier. name - the name of the field. this is the name used to refer to the field on the bound element. readonly - if true, this field is read-only. if this attribute is omitted, the field will be readable and writable. note: the readonly attribute did not w...
...ibute is a document-unique identifier. event - the event attribute describes the specific event that this handler is listening for. its value can be any legal dom event name (including custom events created using the documentevent interface of the dom). action - the action attribute contains script that is invoked when the handler fires. the type attribute on the enclosing handlers element determines the language of the script. the handler script can also be specified as a child of the handler element. phase - this attribute specifies the phase of the event flow that this handler should monitor. the possible values are capturing, bubbling, and target. if a phase is specified, the handler will only be invoked during that phase of the event handling process. if no phase is specified, a defau...
...rol-altx. key="x" modifiers="control any shift" - the handler will match if the shift key is pressed, whether or not the control key is pressed. this will match shift-x or control-shift-x, but no other combinations. keycode - the keycode attribute imposes a filter on key handlers. its value is a key identifier for a specific keycode, e.g., vk_enter. [editor's note: a forthcoming dom events specification will presumably outline the list of valid keycode strings.] if this attribute is present, then its value must match the keycode field of the dom key event object in order for the handler to fire. charcode - the charcode attribute imposes a filter on key handlers. its value is a single character, e.g., "z". if this attribute is present, then its value must match the ch...
ContextMenus - Archive of obsolete content
upopup for the context menu as a child of the element the menu is associated with instead of referring to the menupopup by id. this may be useful, for example, when a context menu is associated with only 1 element. it is also useful in xbl bindings, as you wouldn't want to refer to a popup by id in this case. if the context attribute is set to the value '_child', the context menu is found by examining the children of the element instead of looking for a menupopup with the given id. for example: <vbox context="_child"> <label value="hello"/> <menupopup> <menuitem label="cut"/> <menuitem label="copy"/> <menuitem label="paste"/> </menupopup> </vbox> in this sample, the context menu is found as the child of the vbox, because the context attribute is set to '_child'. note th...
...ren. another alternative is to disable the menuitem instead of hiding it, by setting the item's disabled property. deleteitem.disabled = (rows.childnodes.length == 0); for this example, using the disabled property is more suitable. items should be disabled when they don't apply in certain circumstances, but should be hidden when they would never apply to the element that was clicked on. determining what was context clicked it is important to remember that a context menu may be opened in other ways than just with the mouse. however, even when using the keyboard, there will still be a node (the context) that the menu applies to, which will be the element that is currently focused. when the mouse is used, the context will be the element that is clicked. you can retrieve this element using...
...applies to, which will be the element that is currently focused. when the mouse is used, the context will be the element that is clicked. you can retrieve this element using the popup's triggernode property. in firefox 3.6 and earlier, the document's popupnode property was used; this is now deprecated. in this example, the triggernode property is checked for a popup attached to a browser to determine whether an image is clicked: <script> function showhideitems(aevent) { // aevent.target is the popup for which the popupshowing event fired. var element = aevent.target.triggernode; var isimage = (element instanceof components.interfaces.nsiimageloadingcontent && element.currenturi); document.getelementbyid("enlarge").hidden = !isimage; document.getelementbyid("detail...
...upopup id="contentareacontextmenu" onpopupshowing="showhideitems(event)"> <menuitem label="copy"/> <menuitem id="enlarge" label="enlarge image"/> <menuitem id="details" label="image details"/> </menupopup> <browser src="http://www.mozilla.org" context="contentareacontextmenu"/> when the popupshowing event is fired, the showhideitems function is called. the triggernode is retrieved and examined to see if it is an image. the nsiimageloadingcontent interface is implemented by all types of images. this is useful instead of comparing the tag, as several different tags support images. the test also checks to ensure that the element has a uri set. finally, the hidden state of two menuitems are adjusted based on whether the context is an image or not. the result is that context clicking on ...
RDF Query Syntax - Archive of obsolete content
item" object="?relateditem"/> </query> <rule> ... </rule> </template> </vbox> this query has two statements, each specified with a different tag. the template won't generate anything yet since we still need to fill in the content to be generated which goes in the missing part inside the rule. however, the template builder will be able to compile the rules and examine them as described earlier. the builder needs to start with a single result as the seed result. this is done with the content tag. it indicates that we are going to use a starting point when navigating the graph. obviously, since you need to start somewhere, you will have to use a content tag and it should be the first statement. also, because we can only have one starting point, only one content...
...it indicates that we are going to use a starting point when navigating the graph. obviously, since you need to start somewhere, you will have to use a content tag and it should be the first statement. also, because we can only have one starting point, only one content tag can be used. the seed result will be created like this: (?start = http://www.xulplanet.com/rdf/a) the variable ?start is determined from the tag's 'uri' attribute. you can use any variable you want; it's common to use the variable ?uri. however, all rules must use the same starting point variable. so if a second rule were used, it would also need to use the ?start variable. the value of ?start is set to 'http://www.xulplanet.com/rdf/a'. you'll notice that this is the value of the ref attribute which is the desired starting ...
... the value of the ref attribute which is the desired starting node in the rdf graph. thus, the ?start variable becomes the container or reference variable. actually, in the current template implementation, the above description isn't quite correct. the seed is actually an internal variable set to the container, in this case, the vbox, and the ?start variable is set to the ref later, but that is a minor detail that doesn't make templates more understandable. for this discussion, assume that so far we have a single potential result as above. the content tag doesn't do anything else at this point, meaning it doesn't add anything else to the network of potential results, so processing continues on to the next statement, the triple, which looks like this: <triple subject="?start" predicate...
...ent is used to follow arcs or arrows in the rdf graph. the predicate attribute specifies the labels of the arrows to follow. in the triple used here, the predicate is 'http://www.xulplanet.com/rdf/relateditem', so we know that the builder will look for arrows with that label. the builder can either follow the arrows in a forward or backward direction, but only one direction per statement. it determines which direction to use by examining which data is known and which data is not known yet. recall the data in the potential results set: (?start = http://www.xulplanet.com/rdf/a) this was the seed data created by the content statement. you might be able to guess that the builder fills in the value of the ?start variable as the triple's subject, giving something like this: <triple subject="http:/...
Result Generation - Archive of obsolete content
tent would be generated for each of these results. say you start at a. you could navigate to b, c and d and generate three blocks of output by following the arrows forward. or, you could start at d and follow two arrows back (and only following arrows backwards). this will get one result, a. look at the graph to see if you can see why one result would be generated in this case. in xul template terminology, the starting point is called the container or reference point and the endpoint is called the member. it is so called because it is most common to gather the list of the members, or children, of a container. but this doesn't have to be the case. any starting point and ending points will do. nodes in rdf are identified by a string value. there are two types of nodes in rdf, resources which us...
...rmation remains for the lifetime of the template, or until it is rebuilt. the template builder uses a method based on the rete algorithm to match data. this allows for a fairly efficient means of updating results when, for instance, a new statement is added to the rdf graph. rather than rebuild the entire template, the algorithm allows only specific parts of the network of information to be re-examined. a similar method can be used when removing rdf statements. while the information network created by the template builder contains a number of different pieces of necessary information, for the purposes of this discussion, we will only be interested in the list of possible results. the builder begins with a single possible result, called the seed. the builder processes each of a query's stateme...
...he builder iterates over the possible results found so far and either accepts each result or rejects each result. for the first statement, only the seed will be available as a possible result. at each step, new possible results may be added, or more information pertaining to an existing result may be added to the network. naturally, a rejected result will be removed. ...
...y, a rejected result will be removed. once all results have been examined, the builder moves on to the next statement in the query. once all statements have been analyzed, any results which still remain go on to become matches. the matches are the endpoints and will cause content to be generated. so, to summarize: start out with a one possible result as the seed iterate over the results determined so far and augment them with additional data add any new possible results remove any rejected results repeat steps 2 to 4 for each query statement once done, all remaining results become matches each possible result is made up of a set of variable-value pairs. for instance, a result would look something like the following: (?name = fred, ?age = 5) this result has two variables, ?name ...
Template Logging - Archive of obsolete content
for example, if you spell a value wrong, no data may be returned, but the template system won't know that that this was because of a spelling error, or simply that there shouldn't be any data anyway. fortunately, some debugging and logging support is provided with templates that may help. logging template results there are two main ways in which template errors may be detected. ...
...ve the generated content for that result if you want to further study the content that was generated. the example also specifies 'query 2 matching rule 1'. this indicates that the result is for the second <query> element. if only one <query> is used, naturally this will always indicate a query of 1. in addition, this result matches the first <rule> of query 2. this information may be used to determine if results are not matching the correct rules. if you, for example, were expecting rule 2 to match, examine the rules and ensure that the logic is correct. the final piece of information is the phrase 'new active result'. this indicates first, that this is a new result, as opposed to a result being removed, and second, that this result is 'active'. being active means that the result is not being...
...this allows us to narrow down what query and rule is being used to generate the content. if the query was inactive, the log would say 'new inactive query'. ...
...ng a custom query processor, it may indicate that it is not installed or set up properly. unexpected <queryset> element a <queryset> element was placed in an invalid location; they should be placed directly inside the <template> element with no other kinds of elements as siblings. no member variable found. action body should have an element with uri attribute the member variable could not be determined. you should specify an element inside the first <action> body with a uri attribute. you can also specify the member attribute on the template. either way, the member variable isn't known so it isn't clear what value to use for each generated result id. <where> element is missing a subject attribute every <where> should have a subject attribute that specifies what you are comparing. <where> elem...
Box Model Details - Archive of obsolete content
« previousnext » we've seen a lot of features of the box model. here, we'll find out some more details with some examples. more layout details the style properties such as min-width and max-height can be applied to any element. we've added them to buttons and textboxes, but we can also add them to spacers or boxes. in addition, the flex attribute can be applied to any element. example 1 : source view <hbox flex="1"> <button label="left" style="min-width: 100px;" flex="1"/> <spacer flex="1"/> <button label="right" style="min-width: 100px;" flex="1"/> </hbox> in the example above, all three elements will resize themselves as they are all flexible. the two buttons indicate a minimum width of 100 pixels. the buttons will never be smaller than this size but they may grow la...
... behavior on a horizontal box. you can also prevent this stretching by placing a maximum height on the elements or, better, on the box itself. if a box has a maximum height, the elements inside it are constrained by this. however, the problem with this is that you need to know how big the element will be beforehand. example 2 : source view <hbox flex="1" align="top"> <button label="left" style="min-width: 100px;" flex="1"/> <spacer flex="1"/> <button label="right" style="min-width: 100px;" flex="1"/> </hbox> summary of the box model to achieve complicated layouts, you will generally need to add nested boxes, specify minimum and maximum sizes on some elements, and make certain elements flexible. the best interface is one that can be displayed at various sizes without problems. the box m...
...the first one, instead of beside it. a find text dialog example 5 : source view <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="findtext" title="find text" orient="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <vbox flex="3"> <label control="t1" value="search text:"/> <textbox id="t1" style="min-width: 100px;" flex="1"/> </vbox> <vbox style="min-width: 150px;" flex="1" align="start"> <checkbox id="c1" label="ignore case"/> <spacer flex="1" style="max-height: 30px;"/> <button label="find"/> </vbox> </window> here, two vertical boxes are created, one for the textbox and the other for the check box and button. the left box has a flexiblity that is 3 times greater th...
...> <spacer flex="1" style="max-height: 30px;"/> <button label="find"/> </vbox> </window> here, two vertical boxes are created, one for the textbox and the other for the check box and button. the left box has a flexiblity that is 3 times greater than the right one so it will always receive 3 times as much of the extra space when the window size is increased. the right box enforces a minimum width of 150 pixels. the textbox is flexible so it will resize as the window resizes. the textbox also enforces a minimum width of 100 pixels. the check box appears in the right box along with its label. just below the check box is a spacer. the spacer will grow and shrink but not exceed 30 pixels. the result is that the check box and the find button will be spaced apart from each other by so...
More Event Handlers - Archive of obsolete content
for a full list, see the reference. we already saw the event's target property in the last section. ...
...ent object. 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'. in the addeventlistener form, the first argument passed to the listener function will be the event object. other arguments can be passed to a listener function, if required. the event object has a number of properties which can be examined during an event. for a full list, see the reference. we already saw the event's target property in the last section. it holds a reference to the element where the event occurred. a similar property currenttarget holds the element that is currently having its event listeners handled. in the example below, currenttarget is always the vbox, whereas target would be the specific element, either the ...
...r is moved onto an element. you could use this to highlight the element, however css provides a way to do this automatically so you shouldn't do it with an event. you might, however, want to display some help text on a status bar. mousemove called when the mouse pointer is moved while over an element. the event may be called many times as the user moves the mouse so you should avoid performing lengthy tasks from this handler. mouseout called when the mouse pointer is moved off of an element. you might then unhighlight the element or remove status text. there are also a set of drag related events, which occur when the user holds down a mouse button and drags the mouse around. those events are described in drag and drop. mouse button event properties when a mouse button event o...
... the mouse pointer is moved off of an element. you might then unhighlight the element or remove status text. there are also a set of drag related events, which occur when the user holds down a mouse button and drags the mouse around. those events are described in drag and drop. mouse button event properties when a mouse button event occurs, a number of additional properties are available to determine which mouse buttons were pressed and the location of the mouse pointer. the event's button property can be used to determine which button was pressed, where possible values are 0 for the left button, 1 for the middle button and 2 for the right button. if you've configured your mouse differently, these values may be different. the detail property holds the number of times the button has been clic...
Splitters - Archive of obsolete content
tter is dragged, the farthest element after it will change size. in this case, frame 4 will change size. a value has not been specified for resizebefore so it will default to a value of closest. in this case, there is only one frame before the splitter, so frame 1 will change size. frames 2 and 3 will only change size if you drag the splitter far enough to the right that frame 4 has reached its minimum size. this image shows the 4 panels with the splitter in a collapsed state. this image shows the 4 panels with the splitter resized to the right. notice how the middle two panels have not changed size. only panel 1 and panel 4 have changed size. you can just see part of the fourth panel. if you continue to drag the splitter to the right, the other two panels will shrink. you can use the...
...hows the 4 panels with the splitter in a collapsed state. this image shows the 4 panels with the splitter resized to the right. notice how the middle two panels have not changed size. only panel 1 and panel 4 have changed size. you can just see part of the fourth panel. if you continue to drag the splitter to the right, the other two panels will shrink. ...
...ed state. this image shows the 4 panels with the splitter resized to the right. notice how the middle two panels have not changed size. only panel 1 and panel 4 have changed size. you can just see part of the fourth panel. if you continue to drag the splitter to the right, the other two panels will shrink. you can use the style properties such as min-width, max-height on the iframes to specify minimum or maximum widths or heights in the box. ...
... panel 1 and panel 4 have changed size. you can just see part of the fourth panel. if you continue to drag the splitter to the right, the other two panels will shrink. you can use the style properties such as min-width, max-height on the iframes to specify minimum or maximum widths or heights in the box. if you do, the splitter will detect this and not allow the user to drag the splitter past the minimum and maximum sizes. for example, if you specified a minimum width of 30 pixels on panel 4 above, it would not shrink below that size. the other two panels would have to shrink. if you set the minimum width of panel 1 to 50 pixels, you would only be able to drag the splitter 10 pixels to the left (as it starts at 60 pixels wide). you can still collapse the splitter however. you can also place...
XUL Questions and Answers - Archive of obsolete content
so how can i do this same way as <iframe>? you can't right now i w...
... so how can i do this same way as <iframe>? you can't right now i want to create dynamically multiple elements wi...
... so how can i do this same way as <iframe>? you can't right now i want to create dynamically multiple elements with datasource attribute. ...
...m the rdf datasource create the element, set the datasources attribute then add the element to the document. this should then create the database. xulrunner questions these don't really belong on this page. is there a way to check what directory "application.ini" is in? use directory service the key to the folder where application.ini resides is "resource:app". i get the error: gecko minversion requirement not met. visit http://developer.mozilla.org/en/docs...pplication.ini to find out how to properly set up the application.ini file. how can i use other fonts on xulrunner applications which are not installed on the current machine? in order to do this, you must first attach the font file as a bundle with the xulrunner application as a bundle. you also have to write css code ...
XUL Event Propagation - Archive of obsolete content
l from one element within the interface to another. in this case, the event raised was the "click" event, but a variety of events can be raised by the button element. when the mouse moves over the button, for example, the "hover" event is raised. and sometimes elements raise different events for the pressing down of the click and the release. the events raised by a particular element are pre-determined. the click event is just a message. it's passive in that it doesn't look for a listener; it propagates or "bubbles up" the hierarchy of nodes within the interface until it is either handled in some way or passes out of the interface unhandled. any element that is interested in the event -- any part of the interface, in other words, that needs to know about and respond to the user's click actio...
...dled in some way or passes out of the interface unhandled. any element that is interested in the event -- any part of the interface, in other words, that needs to know about and respond to the user's click action on the button -- "handles" the event with an event handler, or chunk of code to be executed when the given event is "heard". the availability of event listeners is also somewhat pre-determined, though xul provide generalized event listeners (i.e., oncommand event listeners) for most of the elements in the widget hierarchy. event handlers are written by you, the developer of the interface. very often, the event raised by the element is heard by the element itself and handled right there before it bubbles up any higher. this is the case in the example code in the diagram, where the on...
...bubbles up the hierarchy. for example, when you click the new menuitem from the file menu, the event handlers display alerts for "new item alert", "menu handler", "box handler", and "window handler." any or all of these event handler locations might be useful in your interface development. ...
...nt to be useful somewhere higher up, however, it is very often necessary to determine which element below the handler actually raised the event. for example, if an event handler at the menu is handling an event raised by one of the menu items, then the menu should be able to identify the raising element and take the appropriate action, as in the following example, where a javascript function determines which menuitem was selected and responds appropriately: <script> function docmd(el) { v = el.getattribute("value"); if (v == "new") alert("new clicked"); else if (v == "open") alert("open clicked"); else alert("close clicked"); } </script> ... <menu class="menu" value="file" oncommand="docmd(event.target)"> <menupopup> <menuitem oncommand="alert('new item alert')" value="ne...
action - Archive of obsolete content
hing result from a query. the action should be contained within a query or rule element. one descendant of the action body should have a uri attribute set to the member variable. this element and its descendants may use variables in place of attribute values. variables are a question mark followed by a name. for a matched rule, each variable will be a reference to data within the datasource, determined from the query. if the same variable appears multiple times, it will have the same value in each place. for more information, see actions. examples example needed attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, ...
...have the same value in each place. for more information, see actions. ...
...me value in each place. for more information, see actions. ...
...uerytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getbound...
column - Archive of obsolete content
it is common to use columns only to define width and flexibility for the grid column and not place elements directly inside the column. more information is available in the xul tutorial. example see grid for an example. ...
...column. more information is available in the xul tutorial. example see grid for an example. ...
...re information is available in the xul tutorial. example see grid for an example. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
deck - Archive of obsolete content
Archive › Mozilla › XUL › deck
more information is available in the xul tutorial. ...
...ex type: integer gets and sets the index of the currently selected panel. the first item is at index 0. inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties selectedindex type: integer returns the index of the currently selected item. you may select...
...l type: element holds a reference to the currently selected panel within a deck element. assigning a value to this property will modify the selected panel. ...
...pe: element holds a reference to the currently selected panel within a deck element. assigning a value to this property will modify the selected panel. ...
dropmarker - Archive of obsolete content
ker, that when pressed, will reveal a popup menu. ...
...hen pressed, will reveal a popup menu. examples properties accessibletype attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the element. ...
... top, uri, wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the element. ...
...wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the element. ...
keyset - Archive of obsolete content
if this attribute is set, the element is disable...
...if this attribute is set, the element is disabled. disabled...
...have a disabled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. ...
...bled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. ...
listhead - Archive of obsolete content
nd menuitems, is normally preferred to use of the attribute, as it may need to update additional state. ...
...s, is normally preferred to use of the attribute, as it may need to update additional state. inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the element. ...
... a value indicating the type of accessibility object for the element. disabled type: boolean gets and sets the value of the disabled attribute. ...
...dicating the type of accessibility object for the element. disabled type: boolean gets and sets the value of the disabled attribute. ...
listheader - Archive of obsolete content
e value of this attribute is copied to the menulist.value property upon user selection of the menuitem. ...
...this attribute is copied to the menulist.value property upon user selection of the menuitem. inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the element. ...
... top, uri, wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the element. ...
...wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the element. ...
member - Archive of obsolete content
is available in the xul tutorial. ...
...e in the xul tutorial. ...
... that is expected to be a container. if the variable is the same as the uri attribute on the content element, the resource must be a container element in order to match. ...
...pected to be a container. if the variable is the same as the uri attribute on the content element, the resource must be a container element in order to match. ...
preferences - Archive of obsolete content
h default values. attribute nsiprefbranch2 rootbranchinternal; the root prefs branch (nsiprefbranch2). ...
...alues. attribute nsiprefbranch2 rootbranchinternal; the root prefs branch (nsiprefbranch2). ...
...also executes code specified in onchanged attribute of the element. see also the d...
...also executes code specified in onchanged attribute of the element. see also the description ...
row - Archive of obsolete content
Archive › Mozilla › XUL › row
« xul reference home [ examples | attributes | properties | methods | related ] a single row in a rows element. each child of the row element is placed in each successive cell of the grid. the row with the most child elements determines the number of columns in each row, which may be smaller or larger than the number of column elements defined in the grid. more information is available in the xul tutorial. example see grid for an example. ...
...e grid. more information is available in the xul tutorial. example see grid for an example. ...
...re information is available in the xul tutorial. example see grid for an example. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
scrollbox - Archive of obsolete content
nt to programmatically scroll in addition to the automatic scroll bars. note: avoid nested scroll boxes; it's maddening for the experienced user and confusing for the less experienced user. instead, figure out some other way to lay things out. scrolling a child element into view see element.scrollintoview. prior to gecko 19, scrollintoview() didn't exist in xul. do this instead: var xpcominterface =scrollbox_element.boxobject.queryinterface( components.interfaces.nsiscrollboxobject); xpcominterface.ensureelementisvisible(child_element_to_make_visible); see the nsiscrollboxobject api for other scroll-related methods. attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, c...
...element_to_make_visible); see the nsiscrollboxobject api for other scroll-related methods. ...
...make_visible); see the nsiscrollboxobject api for other scroll-related methods. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
stack - Archive of obsolete content
Archive › Mozilla › XUL › stack
that bottom and right attributes, unlike rect, are relative to the bottom and right of the stack. 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. more information is available in the xul tutorial. examples <stack> <hbox flex="1"> <image src="chrome://xulschoolhello/skin/stack-bg.png" flex="1"left="10"right="10" top="10" bottom="10"/> </hbox> <hbox> <!-- some content here. --> </hbox> </stack> in this example, the re...
...> </hbox> <hbox left="0" right="200" > <!-- some content here. ...
... <hbox left="0" right="200" > <!-- some content here. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
statusbar - Archive of obsolete content
[ examples | attributes | properties | methods | related ] an element used to create a status bar, usually placed along the bottom of a window. it is virtually equivalent to a standard box, but may be rendered differently. contains statusbarpanels. ...
...gressmeter mode="determined" value="82"/> <statusbarpanel label="right panel"/> </statusbar> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the eleme...
...t, top, uri, wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the element. ...
..., wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the element. ...
<statusbarpanel> - Archive of obsolete content
is often used with a short label or icon to indicate status, for instance whether the user is online or whether there are new messages. attributes crop, image, label properties image, label style classes statusbarpanel-iconic, statusbarpanel-iconic-text, statusbarpanel-menu-iconic examples <statusbar> <statusbarpanel label="left panel"/> <spacer flex="1"/> <progressmeter mode="determined" value="82"/> <statusbarpanel label="right panel"/> </statusbar> attributes crop type: one of the values below if the label of the element is too big to fit in its given space, the text will be cropped on the side specified by the crop attribute. an ellipsis will be used in place of the cropped text. if the box direction is reversed, the cropping is reversed. ...
...ty (or the maxwidth attribute) to override this size. for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } image type: uri the uri of the image to appear on the element. if this attribute is empty or left out, no image appears. the position of the image is determined by the dir and orient attributes. label type: string the label that will appear on the element. if this is left out, no text appears. for an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. properties image type: image url gets and sets the value of the image attribute. ...
...e type: image url gets and sets the value of the image attribute. label type: string gets and sets the value of the label attribute. ...
...pe: image url gets and sets the value of the image attribute. label type: string gets and sets the value of the label attribute. ...
titlebar - Archive of obsolete content
properties inherited properties align, ,...
... properties inherited properties align, , allowevent...
...xt, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width note: the allowevents attribute did not work for title bars prior to firefox 3. ...
...template, tooltip, tooltiptext, top, uri, wait-cursor, width note: the allowevents attribute did not work for title bars prior to firefox 3. ...
toolbarspacer - Archive of obsolete content
nly a space between toolbar items. ...
...e between toolbar items. properties accessibletype examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the element. ...
... top, uri, wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the element. ...
...wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the element. ...
toolbarspring - Archive of obsolete content
space between toolbar items. ...
...en toolbar items. properties accessibletype examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the element. i...
...t, top, uri, wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the element. ...
..., wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the element. ...
tree - Archive of obsolete content
Archive › Mozilla › XUL › tree
| attributes | properties | methods | related ] a container which can be used to hold a tabular or hierarchical set of rows of elements. the tree may contain any number of rows and any number of columns. each row of the tree may contain child rows which are displayed indented from the parent. unlike other elements, the data to display inside the tree is not specified using tags, but is determined from a view object. the view object implements the nsitreeview interface. the view is queried for the data to appear in the tree. there are several ways in which trees are used, as listed below. the second column lists the interfaces available via the tree's view property. the third column indicates whether treeitem element are used. if you would like to allow the tree to be horizontally scrol...
...ct. tree type view interfaces has dom nodes? description content tree nsitreeview, nsitreecontentview yes this tree has treeitem elements placed within the treechildren element. in this situation, a content view (which implements the interface nsitreecontentview) which is a more specialized type of view, uses the treeitem elements and their descendants to determine the data to display in the tree. however, the treeitems are not displayed directly; they are used only as data to the content view. however, the content view will automatically update the tree if treeitems are changed. rdf tree nsitreeview, nsixultreebuilder no this tree is generated from an rdf datasource. it is used when a tree has a datasources attribute, and has dont-build-...
...ee. for trees with focus, the caret's position is indicated by the focus ring, but unfocused trees won't show a focus ring, naturally. for unfocused trees, the (undrawn) caret's position can still be obtained by this property. if the caret isn't present for any row (for example, because the tree has never been focused), the value will be -1. you cannot rely on this property to change or determine a tree selection, except for trees with seltype="single". (all trees have seltype="multiple" by default.) to reliably change or determine a selection, instead use the nsitreeselection interface methods available via tree.view.selection. disabled type: boolean gets and sets the value of the disabled attribute. disablekeynavigation type: boolean gets or sets the...
...e boxobject property. view type: nsitreeview the view for the tree, which is the object which generates the data to be displayed. you can assign an object which implements nsitreeview to this property. trees built from rdf or those which use treeitems directly will already have a view. functions available in the view allow one to retrieve the data within the cells, and determine which rows are nested within others. for a complete list of view functions, see the nsitreeview interface. methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattri...
treecols - Archive of obsolete content
es pickertooltiptext type: string the text for the tooltip on the column picker. ...
... pickertooltiptext type: string the text for the tooltip on the column picker. inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the element. ...
... top, uri, wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the element. ...
...wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the element. ...
triple - Archive of obsolete content
if the assertion does not exist, the rule will not match. both the subject and object attributes may be variables. the subject of a triple is an rdf resource. in an rdf file this would usually be an rdf description element. ...
...subject type: string the subject of the element. it can be a variable reference or an rdf resource uri. ...
...pe: string the subject of the element. it can be a variable reference or an rdf resource uri. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
window - Archive of obsolete content
on in the window chrome to allow the user to switch the window into full screen mode. supported on mac os x 10.7 lion and later and on windows. the window receives a "fullscreen" event once the change has been made. height type: string (representing an integer) the preferred height of the element in pixels. the actual displayed height may be different if the element or its contents have a minimum or maximum height. the css height property may also be used. hidechrome type: boolean set this attribute to true to have the chrome including the titlebar hidden. id type: unique id a unique identifier so that you can identify the element with. you can use this as a parameter to getelementbyid() and other dom functions and to reference the element in style sheets. inac...
...can have one of the following values: maximized the window is maximized, and occupies the full size of the screen. normal the window appears in a normal state at the desired size. this attribute is used to save and restore the state of a window (together with the persist attribute) and for css styles (e.g. to hide the resizer grippy on maximized windows). note: when a window is minimized, the sizemode attribute is not updated. this is done so that if a window is closed while minimized, its persisted sizemode attribute wouldn't be minimized. setting this attribute does not change the window state. use window.maximize(), window.restore(), or window.minimize() to change the window state. to get the window state from javascript code, use window.windowstate. listen to the size...
...ge event dispatched to the dom window to get notified when the window state changes. title type: string the text to appear in the title bar of the window. width type: string (representing an integer) the preferred width of the element. the value should not include a unit as all values are in pixels. the actual displayed width may be different if the element or its contents have a minimum or maximum width, or the size is adjusted by the flexibility or alignment of its parent. the css width property may also be used. windowtype type: string set to a string which can be used to identify the type of window. this might be used, for example, to distinguish between a browser window and an editor window. some of mozilla's window handling functions use this attribute...
...er - looks like if window has gbrowser it has this window type devtools:scratchpad - scratchpad windows navigator:view-source - the view source windows properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
Building XULRunner with Python - Archive of obsolete content
xulrunner provides python script access to the dom and xpcom in addition to the usual java script. this gives access to python features and modules and builds on mark hammond's pyxpcom work from active state. xpcom components can also be created in python. currently (mar 07) python is not enabled by default so a custom build of mozilla is needed. this page provides instructions in the hope of eliminating much trial and error. 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. of particular interested is access to msaa and iaccessible2 via the python comtypes package. development mach...
...(msvc71) which is not longer officially available. the issue is that xulrunner must be built with the same version of c as python and with python 2.5 that is msvc71. both must use the same version of the c runtime library msvcrt?.dll or crashes will ensue. the alternative is to build python with msvc8 as well asmozilla, but that may be problematic. it might also be possible to use the open source mingw compiler with the correct msvc run time but that is apparently not recommended. apply any service packs and for msvc71 sp 1 is available. the matching platform sdk is also needed and for msvc71 that is .net framework sdk 1.1. the latest mozilla build system is easy to use. install the included python distro usingpython25\python-2.5.msi. it doesn't need to be installed for the build but will b...
... msvc71 that is .net framework sdk 1.1. the latest mozilla build system is easy to use. install the included python distro usingpython25\python-2.5.msi. it doesn't need to be installed for the build but will be useful later when installing python packages which look for entries in the windows' registry. building the batch filestart-msvc71.bat is used to launch the build console (msys from the mingw project ). if you plan to checkout often into empty folders you could modify it to set the cvsroot environment variable. set cvsroot=:pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot having created amozilla project directory (e.g.c:\projects\mozilla or/c/projects/mozilla in msys) create the following .mozconfig file. note this is complete and does not require the checkout of any other proje...
...ce) .logstringmessage(str); } function jserror(str) { components.utils.reporterror(str); } a final tip is to use task manager to check for a zombie xulrunner process after a crash. a zombie will keep old code open and cause confusion when you make changes and run xulrunner again. deploying python must be installed on the target machine. perhaps eventually a xulrunner with a minimal python installation can be generated with something like py2exe or pyinstaller. untill then simply deploy thedist\bin folder and the xul application. don't copy any.pyo files that exist for python modules in the application or errors will occur on the target machine. it is possible to test for python in a batch file using something like rem check python 2.5 installed reg query "hklm\softwar...
Archived Mozilla and build documentation - Archive of obsolete content
ld be added on the devmo talk:1.0 launch roadmap page. further details on smaller tasks being done are available at user:dria:todo page. see also current events. download manager improvements in firefox 3 firefox 3 offers improvements to the download manager that allow multiple progress listeners, use of the storage api for data management, download resuming, and more. in addition, you can augment or replace the download manager's user interface by implementing the new nsidownloadmanagerui interface. download manager preferences there are several preferences used by the download manager. this article provides a list of them. drag and drop this section describes how to implement objects that can be dr...
...javascript technical review completed. existing content this is a list of existing mozilla.org documentation. it needs to be checked, prioritized, and migrated. extension frequently asked questions this is quick set of answers to the most common issues with extension development. they are currently written with mostly firefox in mind, but most if not all should easily translate to seamonkey, thunderbird or any of the other applications. for thunderbird, you may also find the extension howto or faq pages helpful. firefox sync sync refers to a family of related components and services which provide synchronization of data between mozilla application instances. these components and ser...
...le or distribution, then you should consult an attorney with expertise in the particular laws and regulations that apply in your jurisdiction. mozprocess mozprocess provides python process management via an operating system and platform transparent interface to mozilla platforms of interest. mozprocess aims to provide the ability to robustly terminate a process (by timeout or otherwise), along with any child processes, on windows, os x, and linux. mozprocess utilizes and extends subprocess.popen to these ends. nanojit nanojit is a small, cross-platform c++ library that emits machine code. both the tamarin jit and the spidermonkey jit (a.k.a. tracemonkey) use nanojit as their back end. new skin notes...
...ger is responsible for keeping track of where space is taken up and where it is available. this information is used by block layout to correctly compute where other floated elements should be placed, and how much space is available to normal in-flow elements that flow around the floated bits. standalone xpcom standalone xpcom is a tree configuration that builds a minimal set of libraries (shared mostly) that can be used to get all features of xpcom. the contents of this standalone xpcom in general are: stress testing consume.exe from the windows server 2003 resource kit tools can consume various resources: physical memory, cpu time, page file, disk space and even the kernel pool. although for win2003, it should install into ...
Extentsions FAQ - Archive of obsolete content
etely separate explorer window. however, it's functional and does allow for the explorer to be handling the display of the folder contents, and all of the right-click context menu support is present so it should meet my needs. what is the valid location and things needed to to release a mozilla extension on mozallia site? you must remove updateurl from the install.rdf and use a known to amo minversion/maxversion. no confirmation that the answer given worked yet. is it possible to open the url in a new tab? var tab = gbrowser.addtab( url ); // and if you want it to load in the foreground: gbrowser.selectedtab = tab; is it possible to read the html-code of the current url/site? yes, this is possible. use the dom api (http://www.w3schools.com/dom/default.asp has a good tutorial). ...
...button[myexten-toolbar-button="off"] { list-style-image: url("chrome://myexten/skin/toolbar-button-off.png"); -moz-image-region: rect(0px 24px 24px 0px);} to implement a third i would simply change add an attribute and the corresponding css see http://www.w3.org/tr/rec-css2/cascade.html#cascade friday, october 13 - 20, 2006 (↑ top) how to get a refenece to the sidebar window assuming you have chrome privileges, this should work: var ci = components.interfaces; var toplevelwindow = window.queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsiwebnavigation) .queryinterface(ci.nsidocshelltreeitem) .roottreeitem .queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsidomwindow) .queryinterface(ci.nsidomchromewindow); var si...
... asking about the feasibility of making an extension that has the same functionality as “trace route”. friday, september 29 - october 6, 2006 (↑ top) how can we programmatically extract the subject, sender, date and the body of an e- mail when you are reading one...
...can we programmatically extract the subject, sender, date and the body of an e- mail when you are reading one (in thunderbird presumably)? could someone make an addressbook enhancer extension that has the ability to put pictures on a contact and other features the thunderbird address book lacks. ...
Browser Feature Detection - Archive of obsolete content
an experimental approach to discovering degree of support for standards. 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. this test takes that idea to the extreme and tests a large number of properties and methods to determine the level of support a browser has for particular standards and reports a rating as the percentage of names the browser defines. this article has generally never been more than a way to show off firefox web compatibility, rather than something truly informative in a broader sense. therefore, given that it's also badly out of date, it's been archived. you should not rely on any information here. browse...
...vation true false false emptycells true false true fontsizeadjust true false true fontstretch true false true left true true true markeroffset true false true marks true false true maxheight true ie7 only true maxwidth true ie7 only true minheight true true true minwidth true ie7 only true orphans true false true outline true false true outlinecolor true false true outlinestyle true false true outlinewidth true false true overflow true true true page true false true pagebrea...
... textshadow true false true top true true true unicodebidi true true true visibility true true true voicefamily true false true volume true false true widows true false true zindex true true true test code // document properties that are used to determine // support levels var _features = { 'domcore1': [ {name: 'doctype', 'supported': false}, {name: 'implementation', 'supported': false}, {name: 'documentelement', 'supported': false}, {name: 'createelement', 'supported': false}, {name: 'createdocumentfragment', 'supported': false}, {name: 'createtextnode', 'supported': false}, {name: 'createcomment', 'supported': false}, {name: 'c...
..., {name: 'elevation', 'supported': false}, {name: 'emptycells', 'supported': false}, {name: 'fontsizeadjust', 'supported': false}, {name: 'fontstretch', 'supported': false}, {name: 'left', 'supported': false}, {name: 'markeroffset', 'supported': false}, {name: 'marks', 'supported': false}, {name: 'maxheight', 'supported': false}, {name: 'maxwidth', 'supported': false}, {name: 'minheight', 'supported': false}, {name: 'minwidth', 'supported': false}, {name: 'orphans', 'supported': false}, {name: 'outline', 'supported': false}, {name: 'outlinecolor', 'supported': false}, {name: 'outlinestyle', 'supported': false}, {name: 'outlinewidth', 'supported': false}, {name: 'overflow', 'supported': false}, {name: 'page', 'supported': false}, {name: 'pagebreakafter', '...
JSObject - Archive of obsolete content
ass netscape.javascript.jsobject and passed to java. jsobject allows java to manipulate javascript objects. when a javascript object is sent to java, the runtime engine creates a java wrapper of type jsobject; when a jsobject is sent from java to javascript, the runtime engine unwraps it to its original javascript object type. the jsobject class provides a way to invoke javascript methods and examine javascript properties. any javascript data brought into java is converted to java data types. when the jsobject is passed back to javascript, the object is unwrapped and can be used by javascript code. see the core javascript 1.5 guide for more information about data type conversions. method summary the netscape.javascript.jsobject class has the following methods: call calls a javascript...
...ny javascript data brought into java is converted to java data types. when the jsobject is passed back to javascript, the object is unwrapped and can be used by javascript code. see the core javascript 1.5 guide for more information about data type conversions. method summary the netscape.javascript.jsobject class has the following methods: call calls a javascript method. equals determines if two jsobject objects refer to the same instance. (what's the problem with == ?) eval evaluates a javascript expression. getmember retrieves the value of a property of a javascript object. getslot retrieves the value of an array element of a javascript object. removemember removes a property of a javascript object. setmember sets the value of a property of a java...
... tostring converts a jsobject to a string. the netscape.javascript.jsobject class has the following static method: getwindow gets a jsobject for the window containing the given applet. call method. calls a javascript method. equivalent to "this.methodname(args[0], args[1], ...)" in javascript. declaration public object call(string methodname, object args[]) equals method. determines if two jsobject objects refer to the same instance. overrides: equals in class java.lang.object declaration public boolean equals(object obj) backward compatibility javascript 1.3. in javascript 1.3 and earlier versions, you can use either the equals method of java.lang.object or the == operator to evaluate two jsobject objects. in more recent versions, the same jsobject can appear as di...
...rides: equals in class java.lang.object declaration public boolean equals(object obj) backward compatibility javascript 1.3. in javascript 1.3 and earlier versions, you can use either the equals method of java.lang.object or the == operator to evaluate two jsobject objects. in more recent versions, the same jsobject can appear as different java objects. you can use the equals method to determine whether two jsobjects refer to the same instance. eval method. evaluates a javascript expression. the expression is a string of javascript source code which will be evaluated in the context given by "this". declaration public object eval(string s) getmember method. retrieves the value of a property of a javascript object. equivalent to "this.name" in javascript. declaration public objec...
Implementation Status - Archive of obsolete content
xpath expressions in xforms section title status notes bugs 7.1 xpath datatypes supported 7.2 evaluation context partial ...
...xpath expressions in xforms section title status notes bugs 7.1 xpath datatypes supported 7.2 evaluation context partial 7.3 references, dependencies, and dynam...
...9; 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. xpath expressions in xforms section title status notes bugs 7.1 xpath datatypes supported 7.2 evaluation context partial 7.3 references, dependencies, and dynamic dependencies partia...
....6 binding examples supported 7.5 xforms core function library supported 7.6.1 boolean-from-string() supported 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() supp...
Archived open Web documentation - Archive of obsolete content
konqueror is listed below the table, which seems inconsistent. ...
... 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. e4x ecmascript for xml (e4x) is a programming language extension that adds native xml support to javascript. it does this by providing access to the xml document in a form that feels natural for ecmascript programmers. the goal is to provide an alternative, simpler syntax for accessing xml documents than via dom interfaces. a valid alternative to e4x is a non-native jxon algorithm. e4x tutorial ...
...n alternative, simpler syntax for accessing xml documents than via dom interfaces. a valid alternative to e4x is a non-native jxon algorithm. e4x tutorial this tutorial walks you through the basic syntax of e4x (ecmascript for xml). with e4x, programmers can manipulate an xml document with a syntax more familiar to javascript programming. talk:array.foreach() ok, in the end i didn't remove the old code as it isn't hosted anywhere (i thought the github reference contained the code) but inserted a faster implementation above while retaining the rest of the document. iterator the iterator function returns an object which implements legacy iterator...
...) old proxy api proxies are objects for which the programmer has to define the semantics in javascript. the default object semantics are implemented in the javascript engine, often written in lower-level languages like c++. proxies let the programmer define most of the behavior of an object in javascript. they are said to provide a meta-programming api. parallelarray the goal of parallelarray was to enable data-parallelism in web applications. the higher-order functions available on parallelarray attempted to execute in parallel, though they may fall back to sequential execution if necessary. to ensure that your code executes in parallel, it is suggested that the functions should be lim...
Using the Right Markup to Invoke Plugins - Archive of obsolete content
in fact, the above usage will also work for ie, which understands mime type invocations for certain mime types such as flashin addition to activex-style classid invocations. since the use of mime type for flash will work for both ie and netscape 7, you can use the above markup to invoke the flash plugin for both ie and netscape 7. 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. you cannot use a codebase attribute to link to a signed cab file for the activex component, since this won't work in mozilla...
...ing the codebase attribute. if you don't specify a codebase attribute, and the plugin is not installed,the browser will display only the alternate innermost text. it won't attempt to retrieve a missing plugin using the netscape plugin finder service. this behavior is not incorrect according to the html 4.01 specification, but it obliges web authors to diligently specifyobtainment mechanisms. at a minimum, web authors will have to nest some alternate text inside their object elements telling users where to obtain the missing component. adding an additional layer of convenience in the form of automatic retrieval is the subject of a bug 180411 in the mozilla open source code. some plugins don't understand all the param elements that their documentation suggests should configure them in mozil...
...o tell the flash player which animation to start playing. in order to work around this, developers are encouraged to use the data attribute to the object element: <object type="application/x-shockwave-flash" data="animation.swf"..../>. the fact that the flash player doesn't understand this param is a macromedia flash player bug that is bug 180378. recommendation in order to overcome the shortcomings that you can't nest object elements in ie and that there isn't a way you can simply use one object element in a cross-browser way (with architecture specific obtainment mechanisms), the best course of action is to dynamically write object elements based on architecture. for example, on browsers that support activex, such as ie, create an object element with a classid attribute, and on browsers ...
...a are governed by the plugin finder service preference. under edit | preferences | navigator | helper applications is a preference to use netscape's plugin finder service. if the user has checkedalways use the netscape plugin finder service to get plugins then whether these attributes are specified or not makes no difference -- the browser willalways consult with the plugin finder service to determine if it has a plugin to handle the missing mime type. if the preference is unchecked, the plugin finder service will be consulted only if the web page authordoes not specify either of these attributes. original document information author(s): arun k. ranganathan, netscape communications last updated date: 14. nov 2002 copyright information: copyright © 2001-2003 netscape. all rights reserve...
Game distribution - Game development
erver to provide players with the updated code almost instantly. direct link distribution and instant play you don't have to tell people to search for your game in an app store with html5 games. you can just send them a direct url to access the game, which they can then click to play the game right away without the need to use third party plugins or download and install a large package. bear in mind that downloading the game might still take a bit of time depending on the size of the game and your network speed. in any case, it's a lot easier to promote the game if you can drive traffic directly where you want it and don't have to jump through lots of hoops to play. desktop vs mobile the vast majority of the traffic we are interested in — people playing html5 games — comes from mobile...
...it. self-hosting if you are a front-end developer, you may already know what to do. an html5 game is just another website. you can upload it to a remote server, grab a catchy domain name, and host it yourself. if you want to make money out of game dev, you should secure your source code one way or another against people who could easily take it and sell it as their own. you can concatenate and minify the code to make it smaller and uglify it so it's a lot harder to reverse engineer your game. another good measure to take is to provide an online demo if you're planning on packaging it and selling it in a closed store like itunes or steam. if you're working on a side project just for fun, then leaving the source open will benefit those who would like to learn from what you've created. you d...
...'s the apple app store for ios, google play for android and all the rest of the competition. native stores are already filled with established devs selling great games, so you have to be talented and lucky to get noticed. the ios app store is quite hard to get into as there are strict requirements games have to meet, and you'll have to wait a week or two to get accepted. plus, it's the most prominent mobile store, with hundreds of thousands of apps, so it's extremely hard to stand out from the crowd. google play's requirements are less strict, so the store is polluted with low quality games. it's still quite hard to be noticed there as the number of apps submitted daily is huge. it's harder to earn money here too — most of the paid games from ios are published as free games on android, ...
...th hundreds of thousands of apps, so it's extremely hard to stand out from the crowd. google play's requirements are less strict, so the store is polluted with low quality games. it's still quite hard to be noticed there as the number of apps submitted daily is huge. it's harder to earn money here too — most of the paid games from ios are published as free games on android, with monetization coming from in-app purchases (iaps) or ads. other stores for native mobile platforms like windows phone or blackberry are working hard to get a piece of the cake, and are way behind the competition. it can be good to submit your game there as it will be a lot easier to be noticed. if you're looking for more information about the different types of app stores you can check the list of mobile software...
Unconventional controls - Game development
conventional ways to control your web game, some more unconventional than others. tv remote playing games on a tv screen doesn't always have to be done through consoles. there's already a gamepad api working on the desktop computers, so we can imitate the experience, but we can go even further. modern smart tvs can handle html5 games, because they have a built-in browser that can be used as a gaming platform. smart tvs are shipped with remote controls, which can be used to control your games if you know how. the earliest demo of captain rogers: battle at andromeda was adjusted to work on a huge tv. interestingly enough, the first captain rogers game (asteroid belt of sirius) was optimized for low-end, small-screen, cheap smartphones running firefox os, so you can see the difference three y...
...: { // pause the game break; } case 588: { // detonate bomb break; } // ... } }, this); you can see it in action by watching this video. leap motion have you ever thought about controlling a game only with your hands? it's possible with leap motion, an immersive controller for games and apps. leapmotion is becoming more and more popular due to very good integration with vr headsets — demoing rainbow membrane on an oculus rift with leap motion attached to it was voted one of the best webvr experiences by javascript developers visiting demo booths at conferences around the world. as well as being great for virtual interfaces, it can also be used for a casual 2d gaming experiences. it would be very difficu...
...ies: doppler.init(function(bandwidth) { var diff = bandwidth.left - bandwidth.right; }); the diff would be the difference between the initial position of the hand and the final one. this approach won't give us the full flexibility of using a gamepad, or even leap motion, but it's definitely an interesting, unconventional alternative. you can use it to scroll a page hands-free, or play theremin, but it should also be enough to move the ship up and down the screen if implemented correctly. proximity api another interesting idea is to use the built-in proximity sensors of your hardware to detect how far an object, for example a hand, is from the given sensor. it could work similar to the doppler effect in terms of manipulating the player's ship on the screen by moving your hand closer o...
...n proximity sensors of your hardware to detect how far an object, for example a hand, is from the given sensor. it could work similar to the doppler effect in terms of manipulating the player's ship on the screen by moving your hand closer or further from the device. an event listener for device proximity would look like this: window.addeventlistener('deviceproximity', function(event) { var min = event.min; var max = event.max; var proximity = event.value; }); the min and max values are the minimum and the maximum distances respectively between which the sensor can detect the exact proximity value. all three are calculated in centimetres. note: see the deviceproximityevent reference page for more details. makey makey if you want to go completely bananas you can use makey m...
Class - MDN Web Docs Glossary: Definitions of Web-related terms
in object-oriented programming, a class defines an object's characteristics. class is a template definition of an object's properties and methods, the "blueprint" from which other more specific instances of the object are drawn. learn more general knowledge class-based vs. ...
... in object-oriented programming, a class defines an object's characteristics. class is a template definition of an object's properties and methods, the "blueprint" from which other more specific instances of the object are drawn. learn more general knowledge class-based vs. ...
... in object-oriented programming, a class defines an object's characteristics. class is a template definition of an object's properties and methods, the "blueprint" from which other more specific instances of the object are drawn. learn more general knowledge class-based vs. ...
... defines an object's characteristics. ...
Accessible multimedia - Learn web development
if the media is not playing, when the fwd button is pressed. if either conditions are true, we simply stop the video, to avoid the user interface going wrong if they attempt to fast forward when the video is not playing, or fast forward past the end of the video. ...
... simply stop the video, to avoid the user interface going wrong if they attempt to fast forward when the video is not playing, or fast forward past the end of the video. last of all, add the following to the end of the code, to control the time elapsed display: player.ontimeupdate = function() { let minutes = math.floor(player.currenttime / 60); let seconds = math.floor(player.currenttime - minutes * 60); let minutevalue; let secondvalue; if (minutes<10) { minutevalue = "0" + minutes; } else { minutevalue = minutes; } if (seconds<10) { secondvalue = "0" + seconds; } else { secondvalue = seconds; } mediatime = minutevalue + ":" + secondvalue; timelabel.textcontent = mediatime; }; each time the time updates (once per second), we fire this function. ...
... further reading this gives you a basic idea of how to add custom player functionality to video/audio player instances. ...
... further reading this gives you a basic idea of how to add custom player functionality to video/audio player instances. ...
Debugging CSS - Learn web development
and devtools will show you an autocomplete list of matching properties. after selecting font-size, enter the value you want to try. you can also click the + button to add an additional rule with the same selector, and add your new rules there. note: there are other useful features in the rules view too, for example declarations with invalid values are crossed out. you can find out more at examine and edit css. understanding the box model in previous lessons we have discussed the box model, and the fact that we have an alternate box model that changes how the size of elements are calculated based on the size you give them, plus the padding and borders. devtools can really help you to understand how the size of an element is being calculated. the layout view shows you a diagram of the ...
...the value that takes the size you give the element and then adds on the padding and border width. the element with a class of box2 is using border-box, so here the padding and border is subtracted from the size that you have given the element. this means that the space taken up on the page by the box is the exact size that you specified — in our case width: 400px. note: find out more in examining and inspecting the box model. solving specificity issues sometimes during development, but in particular when you need to edit the css on an existing site, you will find yourself having a hard time getting some css to apply. no matter what you do, the element just doesn't seem to take the css. what is generally happening here is that a more specific selector is overriding your changes, and ...
...reat help when solving css problems, so when you find yourself in a situation where css isn't behaving as you expect, how should you go about solving it? the following steps should help. take a step back from the problem any coding problem can be frustrating, especially css problems because you often don't get an error message to search for online to help with finding a solution. if you are becoming frustrated, take a step away from the issue for a while — go for a walk, grab a drink, chat to a co-worker, or work on some other thing for a while. sometimes the solution magically appears when you stop thinking about the problem, and even if not, working on it when feeling refreshed will be much easier. do you have valid html and css? browsers expect your css and html to be correctly writt...
...ll be much easier. do you have valid html and css? browsers expect your css and html to be correctly written, however browsers are also very forgiving and will try their best to display your webpages even if you have errors in the markup or stylesheet. if you have mistakes in your code the browser needs to make a guess at what you meant, and it might make a different decision to what you had in mind. in addition, two different browsers might cope with the problem in two different ways. a good first step therefore is to run your html and css through a validator, to pick up and fix any errors. css validator html validator is the property and value supported by the browser you are testing in? browsers simply ignore css they don't understand. if the property or value you are using is not...
CSS values and units - Learn web development
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. this means that if you see <color> as valid you don't need to wonder which of the different types of color value can be used — keywords, hex values, rgb() functions, etc. you can use any available <color> values assuming they are supported by your browser. the page on mdn for each value will give you information about browser support. for example, if you look at the page for <color> you will see that the browser compatibility section lists different types of color value and support for them. let's have a look at some of the types of value and unit you may frequently encounter, with examples so that you can try ...
..., and font size of the element itself, in the case of other properties like width. ex x-height of the element's font. ch the advance measure (width) of the glyph "0" of the element's font. rem font size of the root element. lh line height of the element. vw 1% of the viewport's width. vh 1% of the viewport's height. vmin 1% of the viewport's smaller dimension. vmax 1% of the viewport's larger dimension. exploring an example in the example below you can see how some relative and absolute length units behave. the first box has a width set in pixels. as an absolute unit this width will remain the same no matter what else changes. the second box has a width set in vw (viewport width) units. th...
...ot treated as strings. there are places where you use strings in css, for example when specifying generated content. in this case the value is quoted to demonstrate that it is a string. in the below example we use unquoted color keywords along with a quoted generated content string. functions the final type of value we will take a look at is the group of values known as functions. in programming, a function is a reusable section of code that can be run multiple times to complete a repetitive task with minimum effort on the part of both the developer and the computer. functions are usually associated with languages like javascript, python, or c++, but they do exist in css too, as property values. we've already seen functions in action in the colors section — rgb(), hsl(), etc. the valu...
...loper and the computer. functions are usually associated with languages like javascript, python, or c++, but they do exist in css too, as property values. we've already seen functions in action in the colors section — rgb(), hsl(), etc. the value used to return an image from a file — url() — is also a function. a value that behaves more like something you might find in a traditional programming language is the calc() css function. this function gives you the ability to do simple calculations inside your css. it's particularly useful if you want to work out values that you can't define when writing the css for your project, and need the browser to work out for you at runtime. for example, below we are using calc() to make the box 20% + 100px wide. the 20% is calculated from the width o...
What is a web server? - Learn web development
a web server is a computer that stores web server software and a website's component files. (for example, html documents, images, css stylesheets, and javascript files) a web server connects to the internet and supports physical data interchange with other devices connected to the web. on the software side, a web server includes several parts that control how web users access hosted files. at a minimum, this is an http server. an http server is software that understands urls (web addresses) and http (the protocol your browser uses to view webpages). an http server can be accessed through the domain names of the websites it stores, and it delivers the content of these hosted websites to the end user's device. at the most basic level, whenever a browser needs a file that is hosted on a web ...
...roubles, a dedicated web server is always connected to the internet. a dedicated web server can have the same ip address all the time. this is known as a dedicated ip address. (not all isps provide a fixed ip address for home lines) a dedicated web server is typically maintained by a third-party. for all these reasons, finding a good hosting provider is a key part of building your website. examine the various services companies offer. choose one that fits your needs and budget. (services range from free to thousands of dollars per month.) you can find more details in this article. once you have web hosting service, you must upload your files to your web server. communicating through http second, a web server provides support for http (hypertext transfer protocol). as its name implies, ...
...later. for now, just be aware of these things: only clients can make http requests, and then only to servers. servers can only respond to a client's http request. when requesting a file via http, clients must provide the file's url. the web server must answer every http request, at least with an error message. on a web server, the http server is responsible for processing and answering incoming requests. upon receiving a request, an http server first checks if the requested url matches an existing file. if so, the web server sends the file content back to the browser. if not, an application server builds the necessary file. if neither process is possible, the web server returns an error message to the browser, most commonly 404 not found. (the 404 error is so common that some web ...
...a website. there are so many application servers that it's difficult to suggest a particular one. some application servers cater to specific website categories like blogs, wikis, or ecommerce; others, called cmss (content management systems), are more generic. if you're building a dynamic website, take the time to choose technology that fits your needs. unless you want to learn web server programming (which is an exciting area in itself!), you don't need to create your own application server. that's just unknown prefix: wikipedia.. next steps now that you are familiar with web servers, you could: read up on how much it costs to do something on the web learn more about various software you need to create a website move on to something practical like how to upload files on a web server.
HTML forms in legacy browsers - Learn web development
in the mobile world, when neither the browser nor the os can be updated such as on older android phones or iphones, the stock browsers that don't update are also legacy browsers. dealing with this wilderness is part of the job. ...
...on ux for the masses, explains it well. graceful degradation is web developer's best friend graceful degradation and progressive enhancement are development patterns that allow you to build great stuff by supporting a wide range of browsers at the same time. when you build something for a modern browser, and you want to be sure it will work, one way or another, on legacy browsers, you are performing graceful degradation. let's see some examples related to html forms. html input types the input types added in html5 are all useable, even in ancient browsers, because the way they degrade is highly predictable. if a browser does not know the value of the type attribute of an <input> element, it will fall back as if the value were text. <label for="mycolor"> pick a color <input type="col...
...iding a missing api. a polyfill is a bit of javascript that "fills in the holes" in the functionality of legacy browsers. while they can be used to improve support for any functionality, using them for javascript is less risky than for css or html; there many cases where javascript can break (network issues, script conflicts, etc.). but for javascript, if you work with unobstructive javascript in mind, if polyfills are missing, it's no big deal. the best way to polyfill missing api is by using the modernizr library and its spin-off project: yepnope. modernizr is a library that allows you to test the availability of functionality in order to act accordingly. yepnope is a conditional loading library. here is an example: modernizr.load({ // this tests if your browser supports the html5 form...
... are very sensitive to it: basically, they are slow and the more polyfills they need, the more javascript they have to process. so they are doubly burdened compared to modern browsers. test your code with legacy browsers to see how they actually perform. sometimes, dropping some functionality leads to a better user experience than having exactly the same functionality in all browsers. as a last reminder, just always think about the end users. conclusion as you can see, considering browser and operating system default form control appearance is important. there are many techniques to handle these issue; however mastering all of them is beyond the scope of this article. the basic premise is to consider whether altering the default implemenation is worth the work before embarking on the challe...
Document and website structure - Learn web development
ly once per page, and put it directly inside <body>. ideally this shouldn't be nested within other elements. <article> encloses a block of related content that makes sense on its own without the rest of the page (e.g., a single blog post). <section> is similar to <article>, but it is more for grouping together a single part of the page that constitutes one single piece of functionality (e.g., a mini map, or a set of article headlines and summaries). it's considered best practice to begin each section with a heading; also note that you can break <article>s up into different <section>s, or <section>s up into different <article>s, depending on the context. <aside> contains content that is not directly related to the main content but can provide additional information indirectly related to it ...
...rt of the main content of the page. so a <div> is fine in this case. we've included a heading as a signpost to aid screenreader users in finding it. warning: divs are so convenient to use that it's easy to use them too much. as they carry no semantic value, they just clutter your html code. take care to use them only when there is no better semantic solution and try to reduce their usage to the minimum otherwise you'll have a hard time updating and maintaining your documents. line breaks and horizontal rules two elements that you'll use occasionally and will want to know about are <br> and <hr>: <br> creates a line break in a paragraph; it is the only way to force a rigid structure in a situation where you want a series of fixed short lines, such as in a postal address or a poem. for ex...
... earlier in the course, html ignores most whitespace); with <br> elements in the code, the markup renders like this: <hr> elements create a horizontal rule in the document that denotes a thematic change in the text (such as a change in topic or scene). visually it just looks like a horizontal line. as an example: <p>ron was backed into a corner by the marauding netherbeasts. scared, but determined to protect his friends, he raised his wand and prepared to do battle, hoping that his distress call had made it through.</p> <hr> <p>meanwhile, harry was sitting at home, staring at his royalty statement and pondering when the next spin off series would come out, when an enchanted distress letter flew through his window and landed in his lap. he read it hazily and sighed; "better get back to wo...
...gical step is to try to work out what content you want to put on a whole website, what pages you need, and how they should be arranged and link to one another for the best possible user experience. this is called information architecture. in a large, complex website, a lot of planning can go into this process, but for a simple website of a few pages, this can be fairly simple, and fun! bear in mind that you'll have a few elements common to most (if not all) pages — such as the navigation menu, and the footer content. if your site is for a business, for example, it's a good idea to have your contact information available in the footer on each page. note down what you want to have common to every page. next, draw a rough sketch of what you might want the structure of each page to look lik...
From object to iframe — other embedding technologies - Learn web development
re or embed map option. select the embed map option, which will give you some <iframe> code — copy this. insert it into the input box below, and see what the result is in the output. if you make a mistake, you can always reset it using the reset button. if you get really stuck, press the show solution button to see an answer. ...
..., you can always reset it using the reset button. if you get really stuck, press the show solution button to see an answer. ...
...ple first though — try loading the previous example we showed above into your browser — you can find it live on github (see the source code too.) you won't actually see anything displayed on the page, and if you look at the console in the browser developer tools, you'll see a message telling you why. in firefox, you'll get told load denied by x-frame-options: /docs/glossary does not permit framing. this is because the developers that built mdn have included a setting on the server that serves the website pages to disallow them from being embedded inside <iframe>s (see configure csp directives, below.) this makes sense — an entire mdn page doesn't really make sense to be embedded in other pages unless you want to do something like embed them on your site and claim them as your own — or...
...ded, and other content such as images and video have much better, easier elements to handle those. plugins and these embedding methods are really a legacy technology, and we are mainly mentioning them in case you come across them in certain circumstances like intranets, or enterprise projects. ...
Introducing asynchronous JavaScript - Learn web development
the third console.log() statement run async as well. this can be done by moving it inside another .then() block chained onto the end of the second one, or by simply moving it inside the second then() block. try fixing this now. note: if you get stuck, you can find an answer here (see it running live also). you can also find a lot more information on promises in our graceful asynchronous programming with promises guide, later on in the module. conclusion in its most basic form, javascript is a synchronous, blocking, single-threaded language, in which only one operation can be in progress at a time. but web browsers define functions and apis that allow us to register functions that should not be executed synchronously, and should instead be invoked asynchronously when some kind of event o...
...ng an operation that takes time however, like querying a database and using the results to populate templates, it is better to push this off the main thread and complete the task asynchronously. ...
...he main thread and complete the task asynchronously. over time, you'll learn when it makes more sense to choose an asynchronous technique over a synchronous one. ...
...usly. over time, you'll learn when it makes more sense to choose an asynchronous technique over a synchronous one. ...
Basic math in JavaScript — numbers and operators - Learn web development
cially true when we are learning to program javascript (or any other language for that matter) — so much of what we do relies on processing numerical data, calculating new values, and so on, that you won't be surprised to learn that javascript has a full-featured set of math functions available. this article discusses only the basic parts that you need to know now. types of numbers in programming, even the humble decimal number system that we all know so well is more complicated than you might think. we use different terms to describe different types of decimal numbers, for example: integers are whole numbers, e.g. 10, 400, or -5. floating point numbers (floats) have decimal points and decimal places, for example 12.5, and 56.7786543. doubles are a specific type of floating point nu...
...n a–f in each column. you may have encountered these numbers before when setting colors in css. before you start to get worried about your brain melting, stop right there! for a start, we are just going to stick to decimal numbers throughout this course; you'll rarely come across a need to start thinking about other types, if ever. the second bit of good news is that unlike some other programming languages, javascript only has one data type for numbers, both integers and decimals — you guessed it, number. this means that whatever type of numbers you are dealing with in javascript, you handle them in exactly the same way. note: actually, javascript has a second number type, bigint, used for very, very large integers. but for the purposes of this course, we'll just worry about number v...
...num2 = 50; 9 * num1; num1 ** 3; num2 / num1; last for this section, try entering some more complex expressions, such as: 5 + 10 * 3; num2 % 9 * num1; num2 + num1 / 8 + 2; some of this last set of calculations might not give you quite the result you were expecting; the section below might well give the answer as to why. operator precedence let's look at the last example from above, assuming that num2 holds the value 50 and num1 holds the value 10 (as originally stated above): num2 + num1 / 8 + 2; as a human being, you may read this as "50 plus 10 equals 60", then "8 plus 2 equals 10", and finally "60 divided by 10 equals 6". but the browser does "10 divided by 8 equals 1.25", then "50 plus 1.25 plus 2 equals 53.25". this is because of operator precedence — some operators are ...
...2; as a human being, you may read this as "50 plus 10 equals 60", then "8 plus 2 equals 10", and finally "60 divided by 10 equals 6". but the browser does "10 divided by 8 equals 1.25", then "50 plus 1.25 plus 2 equals 53.25". this is because of operator precedence — some operators are applied before others when calculating the result of a calculation (referred to as an expression, in programming). operator precedence in javascript is the same as is taught in math classes in school — multiply and divide are always done first, then add and subtract (the calculation is always evaluated from left to right). if you want to override operator precedence, you can put parentheses round the parts that you want to be explicitly dealt with first. so to get a result of 6, we could do this: (num...
Perceived performance - Learn web development
y take a long time, though, there are ways to make it seem faster. there are several tips to improving perceived performance. improving perceived performance understanding networking, how the browser works, user perception of time, etc., can help you better understand how to improve the user interaction. however, you don't have to know the ins and outs of how everything, including how the human mind works, to improve the perception of speed. how fast or slow something feels like it's taking depends a lot on whether the user is actively or passively waiting for this thing to happen. waits can have an active and passive phase. when the user is active - moving the mouse, thinking, being entertainted, they are in an active phase. the passive phase occurs when the user is passively waiting, lik...
...e user is active - moving the mouse, thinking, being entertainted, they are in an active phase. the passive phase occurs when the user is passively waiting, like staring at a monochrome screen. if both the passive and active waits time were objectively equal, users would estimate that the passive waiting period was longer than the active. if a load, render, or response time can not be objectively minimized any further, turning the wait into an active wait instead of a passive wait can make it feel faster. there are tips and tricks to follow. some of these quick tips have full articles if you want to dive deeper. displaying content, or at least some part of the page with an indication that content is loading, as quickly as possible, is essential to improving perceived performance. for exampl...
... wait can make it feel faster. there are tips and tricks to follow. some of these quick tips have full articles if you want to dive deeper. displaying content, or at least some part of the page with an indication that content is loading, as quickly as possible, is essential to improving perceived performance. for example, because page render is blocked by loading and parsing css and javascript, minimizing the amount of css and js that needs to be loaded on initially will have a major impact on improving perceived performance. even though the bytes might be the same, not blocking the page from rendering makes the load feel faster. here are a few tips and tricks to help improve performance: minimize initial load to improve perceived performance, minimize the original page load. in other wo...
... actually show, but only the stuff you are actually using, then download the rest. if you're downloading all the assets in the end, the weight of all your assets hasn't improved -- in fact, you may need to add some code -- but because the download of non-immediately necessary assets are delayed in a manner that is not perceptible the the user, the user will feel like the download was faster. to minimize the assets required for initial load, separate interactive functionality from content so that required content -- the text, styles, and images visible at initial load -- can be loaded first. delay, or lazy load, the rest of the assets. don't load images or scripts that aren’t used or visible on the initial page load. either delay their load, loading them when the page becomes usable, or,...
Routing in Ember - Learn web development
previous overview: client-side javascript frameworks next in this article we learn about routing, or url-based filtering as it is sometimes referred to. we'll use it to provide a unique url for each of the three todo views — "all", "active", and "completed". prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line. a deeper understanding of modern javascript features (such as classes, modules, etc), will be extremely beneficial, as ember makes heavy use of them. objective: to learn about implementing routing in ember. url-based filtering ember comes with a routing system that has a tight integration with the browser url...
...pplication has a default "application" route, which is tied to the app/templates/application.hbs template. because that application template is the entry point to our todo app, we'll need to make some changes to allow for routing. creating the routes let's start by creating three new routes: "index", "active" and "completed". to do this you’ll need to enter the following commands into your terminal, inside the root directory of your app: ember generate route index ember generate route completed ember generate route active the second and third commands should have not only generated new files, but also updated an existing file, app/router.js. it contains the following contents: import emberrouter from '@ember/routing/router'; import config from './config/environment'; export default cl...
...behaves as a "sitemap" for developers to be able to quickly see how the entire app is structured. it also tells ember how to interact with your route, such as when loading arbitrary data, handling errors while loading that data, or interpreting dynamic segments of the url. since our data is static, we won't get to any of those fancy features, but we'll still make sure that the route provides the minimally required data to view a page. creating the "index" route did not add a route definition line to router.js, because like with url navigation and javascript module loading, "index" is a special word that indicates the default route to render, load, etc. to adjust our old way of rendering the todolist app, we'll first need to replace the todolist component invocation from the application tem...
...h <todolist /> so at this point, if you try the app again and visit any of the three routes localhost:4200 localhost:4200/active localhost:4200/completed you'll see exactly the same thing. at each url, the template that corresponds to the specific path ("active", "completed", or "index"), will render the <todolist /> component. the location in the page where <todolist /> is rendered is determined by the {{ outlet }} inside the parent route, which in this case is application.hbs. so we have our routes in place. great! but now we need a way to differentiate between each of these routes, so that they show what they are supposed to show. first of all, return once more to our todo-data.js file. it already contains a getter that returns all todos, and a getter that returns incomplete todos.
Componentizing our Svelte app - Learn web development
previous overview: client-side javascript frameworks next in the last article we started developing our todo list app. the central objective of this article is to look at how to break our app into manageable components and share information between them. we'll componentize our app, then add more functionality to allow users to update existing components. prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line. you'll need a terminal with node + npm installed to compile and build your app. objective: to learn how to break our app into components and share information among them. code along with us git clone the github repo (if you ...
...items completed" status heading will no longer update accordingly. that's because our todo component is receiving the todo via the prop, but it's not sending any information back to its parent. we'll fix this later on. sharing data between components: props-down, events-up pattern the bind directive is pretty straightforward and allows you to share data between a parent and child component with minimal fuss. however, when your application grows larger and more complex it can easily get difficult to keep track of all your bound values. a different approach is the "props-down, events-up" communication pattern. basically, this pattern relies on child components receiving data from their parents via props and parent components updating their state by handling events emitted from child componen...
...pe' && oncancel()}> <div class="form-group"> <label for="todo-{todo.id}" class="todo-label">new name for '{todo.name}'</label> <input bind:value={name} type="text" id="todo-{todo.id}" autocomplete="off" class="todo-text" /> </div> <div class="btn-group"> <button class="btn todo-cancel" on:click={oncancel} type="button"> cancel<span class="visually-hidden">renaming {todo.name}</span> </button> <button class="btn btn__primary todo-edit" type="submit" disabled={!name}> save<span class="visually-hidden">new name for {todo.name}</span> </button> </div> </form> {:else} [...] when the user presses the edit button, the editing variable will be set to true, and svelte will remove the markup in the {:else} part of the dom and repl...
...pe' && oncancel()}> <div class="form-group"> <label for="todo-{todo.id}" class="todo-label">new name for '{todo.name}'</label> <input bind:value={name} type="text" id="todo-{todo.id}" autocomplete="off" class="todo-text" /> </div> <div class="btn-group"> <button class="btn todo-cancel" on:click={oncancel} type="button"> cancel<span class="visually-hidden">renaming {todo.name}</span> </button> <button class="btn btn__primary todo-edit" type="submit" disabled={!name}> save<span class="visually-hidden">new name for {todo.name}</span> </button> </div> </form> {:else} <!-- markup for displaying todo: checkbox, label, edit and delete button --> <div class="c-cb"> <input type="checkbox" id="todo-{todo.id}" on:click...
Creating our first Vue component - Learn web development
omponents, passing data to them via props, and saving data state. note: if you need to check your code against our version, you can find a finished version of the sample vue app code in our todo-vue repository. for a running live version, see https://mdn.github.io/todo-vue/dist/. prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. vue components are written as a combination of javascript objects that manage the app's data and an html-based template syntax that maps to the underlying dom structure. for installation, and to use some of the more advanced features of vue (like single file components or render functions), you'll need a terminal with node + npm installed. objective: to learn ...
...we'll add is a type property. set the value for this property as the javascript string type (note the capital "s"). this tells vue that we expect the value of this property to be a string. now on to the done prop. first add a default field, with a value of false. this means that when no done prop is passed to a todoitem component, the done prop will will have a value of false (bear in mind that this is not required — we only need default on non-required props). next add a type field with a value of boolean. this tells vue we expect the value prop to be a javascript boolean type. your component object should now look like this: <script> export default { props: { label: { required: true, type: string }, done: { default: false, type: boolean } } }...
...serve as a record of whether the checkbox is checked or not. however, it's important that props serve as one-way data binding — a component should never alter the value of its own props. there are a lot of reasons for this. in part, components editing props can make debugging a challenge. if a value is passed to multiple children, it could be hard to track where the changes to that value were coming from. in addition, changing props can cause components to re-render. so mutating props in a component would trigger the component to rerender, which may in-turn trigger the mutation again. to work around this, we can manage the done state using vue’s data property. the data property is where you can manage local state in a component, it lives inside the component object alongside the props pr...
...lly set the id in the component data. we can use the lodash package's uniqueid() method to help keep the index unique. this package exports a function that takes in a string and appends a unique integer to the end of the prefix. this will be sufficient for keeping component ids unique. let’s add the package to our project with npm; stop your server and enter the following command into your terminal: npm install --save lodash.uniqueid note: if you prefer yarn, you could instead use yarn add lodash.uniqueid. we can now import this package into our todoitem component. add the following line at the top of todoitem.vue’s <script> element: import uniqueid from 'lodash.uniqueid'; next, add add an id field to our data property, so the component object ends up looking like so (uniqueid() ...
Handling common HTML and CSS problems - Learn web development
besides. linters can generally be customized to be stricter or more relaxed in their error/warning reporting. there are many online linter applications, the best of which are probably dirty markup (html, css, javascript), and css lint (css only). these allows you to paste your code into a window, and it will flag up any errors with crosses, which can then be hovered to get an error message informing you what the problem is. dirty markup also allows you to make fixes to your markup using the clean button. however, it is not very convenient to have to copy and paste your code over to a web page to check its validity several times. what you really want is a linter that will fit into your standard workflow with the minimum of hassle. many code editors have linter plugins. github's atom code...
...d, which won't work in old versions of ie. now download mootools and selectivizr, and save them in the same directory as your sample html. put the following code into the head of your html document, just before the opening <style> tag: <script type="text/javascript" src="mootools-core-1.6.0.js"></script> <!--[if (gte ie 6)&(lte ie 8)]> <script type="text/javascript" src="selectivizr-min.js"></script> <![endif]--> if you try running this in an old version of ie, it should work fine. handling css prefixes another set of problems comes with css prefixes — these are a mechanism originally used to allow browser vendors to implement their own version of a css (or javascript) feature while the technology is in an experimental state, so they can play with it and get it rig...
... of problems, but there are still some that need attention. if you insist on using prefixed features, make sure you use the right ones. you can look up what browsers require prefixes on mdn reference pages, and sites like caniuse.com. if you are unsure, you can also find out by doing some testing directly in browsers. try this simple example: open up google.com, or another site that has a prominent heading or other block-level element. right/cmd + click on the element in question and choose inspect/inspect element (or whatever the option is in your browser) — this should open up the dev tools in your browser, with the element highlighted in the dom inspector. look for a feature you can use to select that element. for example, at the time of writing, the main google logo had an id of ...
...o need to be investigated if you were to try to support ie that far back). however, they are not really meant for layout purposes — using floats the way we do is really a hack — and they do have some serious limitations (e.g. see why flexbox?) more recently, dedicated layout mechanisms have appeared, like flexbox and css grids, which make common layout tasks far easier and remove such shortcomings. these however are not as well-supported in browsers: css grids are very new; at the time of writing, they were only supported in the very newest versions of modern browsers. flexbox is well-supported in modern browsers, but provides problems in older browsers. ie 9 doesn't support it at all, and ie 10 and old versions of ios/desktop safari respectively support incompatible old versions of ...
Client-side tooling overview - Learn web development
les, ideally automatically fixing errors that they find. prettier is a very popular example of a code formatter, which we’ll make use of later on in the module. bundlers/packagers these are tools that get your code ready for production, for example by “tree-shaking” to make sure only the parts of your code libraries that you are actually using are put into your final production code, or "minifying" to remove all the whitespace in your production code, making it as small as possible before it is uploaded to a server. parcel is a particularly clever tool that fits into this category — it can do the above tasks, but also helps to package assets like html, css, and image files into convenient bundles that you can then go on to deploy, and also adds dependencies for you automatically w...
...m of a tool that will automatically run tests against your code to make sure it is correct before you go any further (for example, when you attempt to push changes to a github repo). this can including linting, but also more sophisticated procedures like unit tests, where you run part of your code, making sure they behave as they should. frameworks for writing tests include jest, mocha, and jasmine. automated test running and notification systems include travis ci, jenkins, circle ci, and others. deployment tools deployment systems allow you to get your website published, are available for both static and dynamic sites, and commonly tend to work alongside testing systems. for example, a typical toolchain will wait for you to push changes to a remote repo, run some tests to see if the c...
... changes are ok, and then if the tests pass, automatically deploy your app to a production site. netlify is one of the most popular deployment tools right now, but others include vercel and github pages. ...
...development experience and likely improve the overall quality of your code. it often takes some time for new developer tools to settle down in their complexity. one of the best known tools, webpack, has a reputation for being overly complicated to work with, but in the latest major release there was a huge push to simplify common usage so the configuration required is reduced down to an absolute minimum. there's definitely no silver bullet that will guarantee success with tools, but as your experience increases you'll find workflows that work for you or for your team and their projects. once all the kinks in the process are flattened out, your tool chain should be something you can forget about and it should just work. how to choose and get help with a particular tool most tools tend to g...
Accessibility API cross-reference
ed with html, which tends to have distinct named elements for its roles. for all these reasons, aria and html are given separate columns. aria abstract roles should not be used by content authors. the gnome accessibility architecture is implemented via atk and at-spi, and was implemented by sun microsystems. it will be reused for kde accessibility via at-spi . we find that it uses very similar naming conventions as java accessibility, and for those purposes the two to be nearly the same. however, only about one third of the states and roles in sun's accessibility api's are the same as in msaa. to do fill out mac api column.(mac os x - carbon accessibility api and accessibility constants) finish aria column - add explanation of the term 'abstract role' fill out html column create aom c...
... sectionhead (abstract role) a form widget that allows the user to make selections from a set of choices. select (abstract role) a line that splits 2 areas from each other separator (either in menu or splits panes) separator (in menu only) separator separator <hr> adjust in increments from min to max values slider slider slider slider <input type=range> a system sound sound n/a n/a n/a no default semantics in html, but semantics and other accessibility features may be provided with aria. see also div n/a n/a n/a <span> span kind of like a dial, but controls the value in a relate...
...y used for sliders, scrollbars, toolbars, tablists... n/a horizontal horizontal aria-orientation=horizontal indicates whether the element is exposed to an accessibility api. ...
...scrollbars, toolbars, tablists... n/a horizontal horizontal aria-orientation=horizontal indicates whether the element is exposed to an accessibility api. note the reversed logic in some apis invisible visible visible aria-hidden hidden (boolean attribute) indicates whether the object is in an iconified or minimized state. ...
Accessibility Features in Firefox
we are optimistic that jaws support will catch up this year. ...
...enefit from firefox's powerful features today, as caret and focus tracking are fully enabled. mozilla corporation is currently reaching out to work with ai squared, the makers of zoomtext, in order to enable complete support of advanced zoomtext features such as the doc reader and app reader. we are also optimistic that the the makers of magic and lunar/supernova will add firefox support in the coming year. mozilla has support for dragon naturally speaking. some users of the professional version are happily playing with dragon and firefox. we are optimistic that nuance will work to improve access to the user interface in the coming year. firefox on linux currently boasts the best onscreen keyboard support in the industry via gok, the gnome onscreen keyboard. basic screen reader accessibilit...
...the search field on the desired website. integrated web search via ctrl+k is much faster to use than first going to the search tool's web site. custom searches can be added to this quick search bar and the user can switch between them by choosing from a drop down available via the standard alt+down arrow key combination. the built-in text zoom feature can be accessed with the ctrl+plus and ctrl+minus hotkeys. the accessibility extension may be installed on top of firefox, allowing keyboard access to document structure. the find bar allows for quick navigation to links and text searching without opening a separate dialog -- this allows more convenient use by screen magnification users because there is a single point of regard for the search. it also assists users of input aids because ther...
...t control: mozilla gives you the ability to fine tune what javascript is allowed to do while you browse. for example, you can disable functions that websites use to move or resize windows, or to remove your status bar, to disable right-click contextual menus, change the status bar text, etc. you can furthermore control javascript capabilities to remove scrollbars, toolbars or system buttons like minimize, close and maximize by editing the about:config related properties or by editing accordingly the user.js file as explained in this "disable other javascript window features" document. moving back and forward by web page (alt+left and alt+right) occurs near-instantaneously the download manager provides keyboard access to all of your recent downloads operating system "look and feel" support...
Multiprocess on Windows
he first place! enter the interceptor to achieve the best of both worlds, we wrote our own code to facilitate the safe handing off of an inbound rpc from the content process's mta to the content main thread's sta. this uses a com technology called the interceptor. interceptors are, essentially, wrapper objects which implement the same interfaces as the object that they are wrapping. when an incoming rpc invokes a method on an interceptor, the interceptor dispatches a callback that allows us to do whatever we want with that request. our callback implementation forwards the method call to the main thread in order to invoke the method on the wrapped object. the interceptor is also aware that any outparams, which contain interfaces, must also be wrapped with interceptors of their own. this cod...
...finition }, { // second arraydata definition } }; mozilla::mscom::registerarraydata(kmyarraydata); each arraydata struct corresponds to one function; with length_is and/or size_is annotations. if your interface contains two functions with those annotations, then you will need to add two arraydata entries. arraydata contains seven fields: iid miid; ulong mmethodindex; ulong marrayparamindex; vartype marrayparamtype; iid marrayparamiid; ulong mlengthparamindex; flag mflag; miid is the uuid of the interface owning the function. mmethodindex is the vtable index of the function within its interface. this index must take into account the vtable(s) of parent interfaces. for example, if interface ifoo inherits from iunknown, the lowest possible mmethodindex for ifoo could ...
...e uuid of the interface owning the function. mmethodindex is the vtable index of the function within its interface. this index must take into account the vtable(s) of parent interfaces. for example, if interface ifoo inherits from iunknown, the lowest possible mmethodindex for ifoo could be 3, because indices 0, 1, and 2 are occupied by the functions that ifoo inherited from iunknown. marrayparamindex is the index of the parameter that contains the array (excluding the this pointer). marrayparamtype is the expected variant type of the outparam. this should usually be set to vt_unknown | vt_byref, which is telling the interceptor that the outparam is an iunknown**. marrayparamiid is the uuid of the interface that the outparam array uses. this should be the iid that we want the interceptor ...
...cluding the this pointer). marrayparamtype is the expected variant type of the outparam. this should usually be set to vt_unknown | vt_byref, which is telling the interceptor that the outparam is an iunknown**. marrayparamiid is the uuid of the interface that the outparam array uses. this should be the iid that we want the interceptor to actually use when wrapping the array element. mlengthparamindex is the index of the out parameter that contains the length of the array (excluding the this pointer). the interceptor needs to be able to read this parameter to know how many interface pointers exist in the array. mflag may currently be set to one of two values: arraydata::flag::enone or arraydata::flag::eallocatedbyserver. setting eallocatedbyserver signals to the interceptor that the array ...
The Firefox codebase: CSS Guidelines
doing and the shorthand can also hide some unwanted default values. it is good to privilege expanded syntax to make your intentions explicit. do this: border-color: red; not this: border: red; put multiple selectors on different lines do this: h1, h2, h3 { font-family: sans-serif; text-align: center; } not this: h1, h2, h3 { font-family: sans-serif; text-align: center; } naming standards for class names lower-case-with-dashes is the most common. but camelcase is also used sometimes. try to follow the style of existing or related code. other tips assume ="true" in attribute selectors. example: use option[checked], not option[checked="true"]. avoid id selectors unless it is really the wanted goal, since ids have higher specificity and therefore are ...
...ble like inheriting or using the currentcolor keyword? using inheriting or using currentcolor will prevent repetition of the value and it is usually good practice to do so. in general, it's good to first think of how some css could be written cleanly without the css variable(s) and then think of how the css variable could improve that css. using variables use the variable according to its naming do this: xul|tab:hover { background-color: var(--in-content-box-background-hover); } not this: #certificateerrordebuginformation { background-color: var(--in-content-box-background-hover); } localization text direction for margins, padding and borders, use inline-start/inline-end rather than left/right. example: use margin-inline-start: 3px; instead of margin-left: 3px. for rtl...
... shared directory, instead of writing the same css for the 3 platform specific directories, especially for large blocks of css. content css vs. theme css the following directories also contain css: browser/base/content/ toolkit/content/ these directories contain content css, that applies on all platforms, which is styling deemed to be essential for the browser to behave correctly. to determine whether some css is theme-side or content-side, it is useful to know that certain css properties are going to lean one way or the other: color - 99% of the time it will be theme css, overflow - 99% content. 99% theme 70% theme 70% content 99% content font-*, color, *-color, border-*, -moz-appearance [1] line-height, padding, margin cursor, width, max-width, top,...
...ent, avoid setting the opacity property on text as it will cause text to be aliased differently. hdpi support it's recommended to use svg since it keeps the css clean when supporting multiple resolutions. see the svg guidelines for more information on svg usage. however, if only 1x and 2x png assets are available, you can use this @media query to target higher density displays (hdpi): @media (min-resolution: 1.1dppx) ...
Displaying Places information using views
derlying data changes, the view will automatically update itself so that it displays the new data. this update is handled by logic between the view and its results. all places views implement or own an instance of interface nsinavhistoryresultviewer, which is the point of interaction between a view and its results. results themselves observe places changes, and if on a places change a result determines that its data specifically has changed, it notifies its view by calling an appropriate method of nsinavhistoryresultviewer. once notified, the view is responsible for updating itself. note: starting in gecko 2.0, nsinavhistoryresultviewer has been replaced by the more powerful nsinavhistoryresultobserver. tree view create a built-in tree view by setting the type attribute to "places" on a ...
... require more control over your view, you may need to write your own. see creating custom views below. using the tree view so you've got a built-in tree view. how do you ask it about the data it displays? first, see nsiplacesview. like all places views, the built-in tree view implements this interface, which provides broad methods such as getting the view's nsinavhistoryresult instance and examining the view's selection. second, know this: when it comes to trees, "view" is an overloaded word. this document describes places views. places views are just xul elements; the built-in places tree view is just a tree element whose type attribute is equal to "places", as described above. but recall that all trees—places view or not—display their data using another kind of view, nsitreeview. t...
... the toolbaritem and toolbar references and toolbars tutorial for general information about toolbars. using a view so you've got a places view. how do you interact with it? because it is fairly complex, the built-in tree view provides uniquely tailored interfaces to make it easier to use. if you write your own complex view, you might do something similar. but all places views should provide a minimal interface so that you and controllers have a consistent, general way to interact with them. for this reason views implement interface nsiplacesview. it allows you to do things like getting the nsinavhistoryresult instance that a view displays and examining its selected nodes. in fact the special place property described above is a property of this interface. creating custom views if you nee...
...ating custom views if you need greater flexibility than a built-in view provides, you can create a custom view. good reasons for needing a custom view might include (but are in no way limited to): displaying custom columns alongside those provided by the built-in tree view. changing the way a built-in view displays dates or other data. inserting information into the display that is not determined by the underlying data. displaying places information in an element not covered by one of the built-in views. potentially bad reasons for creating a custom view might include (but are not limited to): changing only the superficial appearance of a built-in view rather than the content it displays. try css here. hiding columns of the built-in tree view. just leave out the treecol elements ...
Assert.jsm
the assert.jsm javascript code module implements the commonjs unit testing specification version 1.1, which provides a basic, standardized interface for performing in-code logical assertions with optional, customizable error reporting. to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://testing-common/assert.jsm"); the assert class offers methods for performing common logical assertions. method overview undefined ok(value, message); undefined equal(actual, expected, message); undefined notequal(actual, expected, message); undefined deepequal(actual, expected, message); undefined notdeepequal(actual, expected, message); undefined strictequal(actual, expected, message); ...
...creates a new assert object. let assert = new assert(reporterfunc); the new assert instance, assert, uses reporterfunc to report assertion results or throws an assertionerror when an assertion fails, as default behavior. ok, equal, notequal, deepequal, notdeepequal, strictequal, notstrictequal, throws, setreporter, report methods ok() pure assertion tests whether a value is truthy, as determined by !!guard. this statement is equivalent to assert.equal(true, !!guard, message_opt);. to test strictly for the value true, use assert.strictequal(true, guard, message_opt);. undefined ok( actual, message ); parameters actual test subject to be evaluated as truthy message short explanation of the expected result equal() the equality assertion tests shallow, coercive equality wi...
...ected, message ); parameters actual test subject to be evaluated as not equivalent to expected expected test reference to evaluate against actual message short explanation of the expected result deepequal() the equivalence assertion tests a deep equality relation. we check using the most exact approximation of equality between two objects to keep the chance of false positives to a minimum. json.stringify is not designed to be used for this purpose; objects may have ambiguous tojson() implementations that would influence the test. undefined deepequal( actual, expected, message ); parameters actual test subject to be evaluated as equivalent to expected, including nested properties expected test reference to evaluate against actual message short explanation of t...
...ence assertion tests for any deep inequality. undefined notdeepequal( actual, expected, message ); parameters actual test subject to be evaluated as not equivalent to expected, including nested properties expected test reference to evaluate against actual message short explanation of the expected result strictequal() the strict equality assertion tests strict equality, as determined by ===. undefined strictequal( actual, expected, message ); parameters actual test subject to be evaluated as strictly equivalent to expected expected test reference to evaluate against actual message short explanation of the expected result notstrictequal() the strict non-equality assertion tests for strict inequality, as determined by !==. undefined notstrictequal( actu...
OS.File.Info
s last modification date, etc. due to differences between operating systems, the information available depends on the platform. instances of os.file.info may be obtained by: calling global method os.file.stat() either from the main thread or from a worker thread; calling instance method stat() of os.file either from the main thread or from a worker thread. ...
...n available depends on the platform. instances of os.file.info may be obtained by: calling global method os.file.stat() either from the main thread or from a worker thread; calling instance method stat() of os.file either from the main thread or from a worker thread. ...
...somepath| represents a directory } else if (info.issymlink) { // |somepath| represents a symbolic link } else { // |somepath| represents a regular file } }, function onfailure(reason) { if (reason instanceof os.file.error && reason.becausenosuchfile) { // |somepath| does not represent anything } else { // some other error } } ) example: determining the owner of a file let promise = os.file.stat() promise.then( function onsuccess(info) { if ("unixowner" in info) { // info.unixowner holds the owner of the file } else { // information is not available on this platform } } ); evolution of this example bug 802534 will introduce the ability to check whether field unixowner appears in os.file.info.prototype...
...a javascript date object. platform-specific attributes unix unixowner a number holding the identifier of the unix owner of this file. unixgroup a number holding the identifier of the unix group of this file. unixmode a number holding the unix access rights to this file. unixlaststatuschangedate date. this is the date of the latest write/renaming/mode change/... where ... is any write/set of inode information (such as owner, group, link count, mode, etc). windows winbirthdate a date representing the time at which the file was created. may not be exact on all file systems. winattributes hidden boolean readonly boolean system ...
Sqlite.jsm
. all operations are asynchronous. use of synchronous storage apis is discouraged because they block the main thread. all the functionality in sqlite.jsm is asynchronous. easier memory management. since sqlite.jsm manages statements for you, it can perform intelligent actions like purging all cached statements not in use, freeing memory in the process. there is even a shrinkmemory api that will minimize memory usage of the connection automatically. simpler transactions. sqlite.jsm exposes a transaction api built on top of task.jsm that allows transactions to be written as procedural javascript functions (as opposed to a series of callback driven operations). if the function throws, the transaction is automatically rolled back. this makes code easy to write and read. javascript-y api. sqli...
.... sharedmemorycache (optional) boolean indicating whether multiple connections to the database share the same memory cache. sharing the memory cache likely results in less memory utilization. however, sharing also requires connections to obtain a lock, possibly making database access slower. defaults to true. shrinkmemoryonconnectionidlems (optional) if defined, the connection will attempt to minimize its memory usage after this many milliseconds of connection idle. the connection is idle when no statements are executing. there is no default value which means no automatic memory minimization will occur. please note that this is not a timer on the idle service and this could fire while the application is active. openconnection(options) returns a promise that resolves to an opened connect...
... tables and database schema. getschemaversion() the user-set version associated with the schema for the current database. if no schema version has been set, this will return the string "0". setschemaversion(value) sets value as the new version associated with the schema for the current database. this is a wrapper around the pragma user_version statement. tableexists(name) this function determines whether a table exists in the current database. it returns a promise that is resolved with a boolean indicating whether the table exists. indexexists(name) this functions determines whether a named index exists in the current database. it returns a promise that is resolved with a boolean indicating whether the index exists. statement execution these apis facilitate execution of statements o...
...:paramb)", data); } }); transactions these examples demonstrate how transactions work. conn.executetransaction(async function simpletransaction() { await conn.execute("insert into mytable values (?, ?)", ["foo", "bar"]); await conn.execute("insert into mytable values (?, ?)", ["biz", "baz"]); }); the above will result in 2 insert statements being committed in a deferred transaction (assuming the inserts proceed without error, of course). let's do an example where we want to force a transaction rollback. conn.executetransaction(async function complextransaction() { await conn.execute("insert into mytable values (?, ?)", ["foo", "bar"]); let data = await conn.execute("select * from mytable"); if (data.length < 5) { throw new error("we don't have the expected 5 rows to perf...
Localizing with Mozilla Translator
you will always do better if you can export a partial glossary and reimport it as needed. see the following example. let's assume you have a firefox product in mt with the directory layout present in language packs, as you probably would need for a initial localization. the directory structure will look like this: (ab-cd jar root) locale |-- branding | |-- brand.dtd | ...
...it -> autotranslate. most of the strings will be automatically filled, although if you do this you should review them, because for en-us strings with several possible translations, mt will choose one of them, which could not be the one you want. from cvs to mercurial in mt so, you have a firefox product in mt with a platform neutral and, inside it, several directories (''components'' in mt terminology) more or less like the second sample above, checked out from cvs. now, you want to start working directly on mozilla-central (and l10n-central). what should you do? the first thing to do, once you have your mercurial local repository up and working, is create a new product... or more. with good oldie cvs, you could checkout just the locale content and, even more, you could checkout just ''t...
...i.e., linux or mac), you can create symbolic links in a separate directory so it contains just the locale part. thanks to alexandru szasz, from narro, [http://groups.google.com/group/mozil...bbffa5402ec819 for this inspiration]. see this example for browser. for the last two options, you should be able to adjust your current mt product paths so you can keep using it just like with cvs. keep in mind that mt doesn't really know if you are using cvs, svn, or mercurial. it is just instructed to read directory subtrees and ignore "cvs" and ".svn" directories it finds. if you have opted for the first solution, you will find yourself with some new products completely untranslated (once you update each of them). to migrate the existing translation in the old product, you need to export partial gl...
...nce you update each of them). to migrate the existing translation in the old product, you need to export partial glossaries from the old product, selecting the ''link'' origin (see the previous section) and importing them into the ''link'' target. defining symbolic links for browser this is an example just for browser, without shared components, but it should suffice to get the idea. ; assuming we are in a directory containing mozilla-central/ $ mkdir locale-only $ cd locale-only $ mkdir -p browser extensions/reporter other-licenses/branding/firefox/ $ cd browser; ln -s ../../mozilla-central/browser/locales/; cd .. $ cd extensions/reporter; ln -s ../../../mozilla-central/extensions/reporter/locales/; cd ../.. $ cd other-licenses/branding/firefox/; ln -s ../../../../mozilla-...
Using the viewport meta tag to control layout on mobile browsers
umber of pixels like width=600 or to the special value device-width, which is the width of the screen in css pixels at a scale of 100%. (there are corresponding height and device-height values, which may be useful for pages with elements that change size or position based on the viewport height.) the initial-scale property controls the zoom level when the page is first loaded. the maximum-scale, minimum-scale, and user-scalable properties control how users are allowed to zoom the page in or out. usage of user-scalable=no can cause accessibility issues to users with visual impairments such as low vision. a pixel is not a pixel in recent years, screen resolutions have risen to the size that individual pixels are hard to distinguish with the human eye. for example, recent smartphones gener...
...r a page at a larger size. to fix this, browsers will expand the viewport width if necessary to fill the screen at the requested scale. this is especially useful on large-screen devices like the ipad. (allen pike's choosing a viewport for ipad sites has a good explanation for web developers.) for pages that set an initial or maximum scale, this means the width property actually translates into a minimum viewport width. for example, if your layout needs at least 500 pixels of width then you can use the following markup. when the screen is more than 500 pixels wide, the browser will expand the viewport (rather than zoom in) to fit the screen: <meta name="viewport" content="width=500, initial-scale=1"> other attributes that are available are minimum-scale, maximum-scale, and user-scalable. th...
...all mobile browsers handle orientation changes in the same way. for example, mobile safari often just zooms the page when changing from portrait to landscape, instead of laying out the page as it would if originally loaded in landscape. if web developers want their scale settings to remain consistent when switching orientations on the iphone, they must add a maximum-scale value to prevent this zooming, which has the sometimes-unwanted side effect of preventing users from zooming in: <meta name="viewport" content="initial-scale=1, maximum-scale=1"> suppress the small zoom applied by many smartphones by setting the initial scale and minimum-scale values to 0.86. the result is horizontal scroll is suppressed in any orientation and the user can zoom in if they want to. <meta name="viewport" co...
...s from zooming in: <meta name="viewport" content="initial-scale=1, maximum-scale=1"> suppress the small zoom applied by many smartphones by setting the initial scale and minimum-scale values to 0.86. the result is horizontal scroll is suppressed in any orientation and the user can zoom in if they want to. <meta name="viewport" content="width=device-width, initial-scale=0.86, maximum-scale=3.0, minimum-scale=0.86"> common viewport sizes for mobile and tablet devices if you want to know what mobile and tablet devices have which viewport widths, there is a comprehensive list of mobile and tablet viewport sizes here. this gives information such as viewport width on portrait and landscape orientation as well as physical screen size, operating system and the pixel density of the device. speci...
Mozilla DOM Hacking Guide
elper class passed as third argument to the macro. nsiclassinfo *mcachedclassinfo: mcachedclassinfo holds an nsiclassinfo pointer to an instance of the relevant helper class. const nsiid *mprotochaininterface: pointer to the iid of the first interface available to javascript clients. this is used in global resolve functions, when xpconnect has to find the member function to call. const nsiid **minterfaces: pointer to the first element of an array of pointers to all the interfaces available through js for this class. pruint32 mscriptableflags: 31; : the fourth argument passed to ns_define_classinfo_data_with_name. prbool mhasclassinterface: 1; : help me? mname and mconstructorfptr, mscriptableflags and mhasinterface are initialized by ns_define_classinfo_data_with_name. mcachedclassinfo...
...rst element of an array of pointers to all the interfaces available through js for this class. pruint32 mscriptableflags: 31; : the fourth argument passed to ns_define_classinfo_data_with_name. prbool mhasclassinterface: 1; : help me? mname and mconstructorfptr, mscriptableflags and mhasinterface are initialized by ns_define_classinfo_data_with_name. mcachedclassinfo, mprotochaininterface and minterfaces, however, are initialized in nsdomclassinfo::init(), described in section 1.5. interface flattening one of the nicest -- and most important -- features of the xpconnect'ed dom is the interface flattening. "interface flattening is the ability to call methods on an object regardless of the interface it was defined on." for example, when we have the document object in javascript, we can ca...
...from the javascript benefits it provides. after that, we fill the blanks in the sclassinfodata array. if you remember the discussion in the introduction to class info, there is the main array, sclassinfodata, filled with objects of type nsdomclassinfodata. however when the array is created, three data members of the structure are left as null pointers: mcachedclassinfo, mprotochaininterface, and minterfaces. init() uses a set of macros to fill the blanks: the dom_classinfo_map family. each dom class needs to use these macros, otherwise bad things will happen. i will use the example of the window class to illustrate the use of the macros. here is the relevant piece of code. dom_classinfo_map_begin(window, nsidomwindow) dom_classinfo_map_entry(nsidomwindow) ... dom_classinfo_map_entry(nsidoma...
...d as arguments to the macro. in our window example, the interfaces are nsidomwindow, nsidomjswindow, nsidomeventreciever, nsidomeventtarget, nsidomviewcss, and nsidomabstractview. please see section 1.2 on interface flattening for an explanation of the use of these interfaces. the initialization for a class is finished by the dom_classinfo_map_end macro. #define dom_classinfo_map_end nsnull }; d.minterfaces = interface_list; } the interface_list array is terminated by a null pointer. the line d.minterfaces = interface_list assigns to minterfaces the address of the first element of the interface_list array, which is itself a pointer. minterfaces is thus correctly a pointer to a pointer to an object of type nsiid. to define the jsvals, init() simply calls definestaticjsvals(). to register t...
Mozilla Web Developer FAQ
browser defeats that purpose. when working with the dom, it is better to check for the existence of the methods and objects you are planning on using. for example, the existence of document.getelementbyid() can be checked as follows: if(document.getelementbyid) { /* code that uses document.getelementbyid() */ } why doesn’t mozilla display my alt tooltips? contrary to a popular belief stemming from the behavior of a couple browsers running on the windows platform, alt isn’t an abbreviation for ‘tooltip’ but for ‘alternative’. the value of the alt attribute is a textual replacement for the image and is displayed when the image isn’t. mozilla doesn’t display the alt attribute as a tooltip, because it has been observed that doing so encourages authors to misuse the attribu...
...r browser x does (where x is the favorite non-mozilla browser of whoever is presenting the counter argument). however, doing whatever browser x does in every conceivable case isn’t simple at all, even though it might appear to be simple when presented as a passing remark. different people have different ideas about what x should be. the second problem is that web authors are very creative in coming up with different ways of deviating from the standards. in fact, since the input to the browser can be of arbitrary length, there is no upper bound for the number of distinct ways of deviating from the standards. therefore, it is impossible to test whether mozilla reacts exactly like browser x to every possible input. (likewise, there is no upper bound for the number of ways different features o...
...out a mechanism that would ensure the well-formedness of the served documents. mechanisms that ensure well-formed output include serializing from a document tree object model (eg. dom) and xslt transformations that do not disable output escaping. when xhtml output has been retrofitted to a content management system that was not designed for xml from the ground up, the system usually ends up discriminating gecko users by serving tag soup labeled as xml to gecko (leading to a parse error) and serving the same soup labeled as text/html to ie (not leading to a parse error). how is the treatment of application/xhtml+xml documents different from the treatment of text/html documents? an xml parser (expat) is used instead of the tag soup parser. most well-formedness constraints are enforced...
...tead of entities. (numeric character references are safe, too.) document.write() is not supported. the stream that is going into the parser can’t be tampered with in mid-parse. things that look like xml comments are treated as xml comments—even inside script or style elements. elements need to be in the xhtml namespace in order to be treated as xhtml elements. meta tags are not examined for character encoding information. tbody, head, body, and html are not inferred if the tags are not explicitly present. cdata sections are supported. xml empty element notation (<foo/>) is supported. white space characters in attribute values are normalized to spaces at parse time, so the original white space never makes it to the dom. this affects data round tripping using hidden ...
Activity Monitor, Battery Status Menu and top
onsumption. careful investigation indicates that on mac os 10.10 and 10.11 it is computed with a formula that is machine model-specific, and includes the following factors: cpu usage, wakeup frequency, quality of service class usage, and disk, gpu, and network activity. the weightings of each factor can be found in one of the the files in /usr/share/pmenergy/mac-<id>.plist, where <id> can be determined with the following command. ioreg -l | grep board-id in contrast, on mac os 10.9 it is computed via a simpler machine model-independent formula that only factors in cpu usage and wakeup frequency. in both cases "energy impact" often correlates poorly with actual power consumption and should be avoided in favour of direct measurements that have clear physical meanings. what does "average ene...
...rmula to compute the "average energy impact", using measurements from the past 8 hours of wake time (i.e. if a laptop is closed for several hours and then reopened, those hours are not included in the calculation.) battery status menu when you click on the battery icon in the os x menu bar you get a drop-down menu that includes a list of “apps using significant energy”. this is crude but prominent, and therefore worth understanding — even though it's not much use for profiling applications. when you open this menu for the first time in a while it says “collecting power usage information” for a few seconds, and if you have top open during that time you'll see that, once again, systemstats is running and using a lot of cpu. furthermore, if you click on an application name in the ...
...nformation” for a few seconds, and if you have top open during that time you'll see that, once again, systemstats is running and using a lot of cpu. furthermore, if you click on an application name in the menu activity monitor will be opened and that application’s entry will be highlighted. based on these facts it seems reasonable to assume that “energy impact” is again being used to determine which applications are "using significant energy". testing shows that once an energy-intensive application is started it takes less than a minute for it to show up in the battery status menu. and once the application stops using high amounts of energy it takes a few minutes to disappear. the exception is when the application is closed, in which case it disappears immediately. and it appears tha...
...gram with an “energy impact” of roughly 20 or more will eventually show up as significant, and programs that have much higher “energy impact” values tend to show up more quickly. all of these battery status menu observations are difficult to make reliably and so should be treated with caution. it is clear, however, that the window used by the battery status menu is measured in seconds or minutes, which is much less than the 8 hour window used for “average energy impact” in activity monitor. top top is similar to activity monitor, but is a command-line utility. to see power-related measurements, invoke it as follows. top -stats pid,command,cpu,idlew,power -o power -d note: -a and -e can be used instead of -d to get different counting modes. see the man page for details. it ...
Gecko Profiler FAQ
profile startup code that regresses just a little (<10-15ms ts_paint/tpaint) [mstange] we currently don’t have a good way to do that. you can write your own tools to assist you in this process, though. i did something like this a few years ago with the old profiler and i think something similar would work here: i think there are three main challenges here. you need deterministic profiles that can be compared meaningfully, you need to gather enough data / samples, and you need a way to compare profiles. to increase determinism, you really want an automated way of gathering the data. and you’ll want to make sure the profiles only contain data for the time range you’re interested in. to stop the profiler from gathering more samples after the “st...
... profile comparison is tricky. the only way that i’ve tried before is to use a “difference calltree”: in the regular call tree, each node of the calltree is assigned a weight which is just the number of samples that were under this call stack. in a difference call tree, each node’s weight instead is computed as <number of samples under this stack in the “after” profile> minus <number of samples under this stack in the “before” profile>. that tree is then displayed in the usual way, with weights in decreasing order from top to bottom. then the call stacks whose cost increased the most in the “after” profile will be at the top, and those are the ones you usually want to look at if you caused a regression. in this view, the timestamps of individual sampl...
...’d hardware instead of artificially slowing down just the cpu. another approach to get more precision is also raising the sampling frequency to sub-millisecond ranges (it won’t work on windows.) high frequency sampling may also be an area where native profilers are a useful alternative tool to try. how do we profile "leaks" that show up after running firefox for > 40 mins? the gecko profiler has been designed specifically for the use case of having it run always in the background, and it’s pretty good at that! it is quite reasonable to actually run the browser for 40 minutes and once the said leaks have happened capture the profiles and study what went wrong. [ehsan] i have been profiling my real browser usage for months now, and so can...
...ic approach is: use it for a while, and if you notice slowness, profile it. pay attention to the red jank markers at the top. [ehsan] mike conley’s oh no reflow! add-on is helpful. how do we know when profiler output is statistically significant (for comparing across runs / across machines)? [mstange] hard to say. prefer to do comparisons by measuring your timings with code instead of by inspecting profiles. always keep in mind that profiler overhead has the potential to skew the results. is it better to profile across multiple platforms, or to focus time on windows (since that's the bulk of our users)? [mstange] in my opinion, as long as you double-check that the problems you find are actually present on windows, it doesn’t ma...
NSS Certificate Download Specification
one of these collections of multiple certificates they are handled in the following way: the first certificate is processed in a context specific manner, depending upon how it is being imported. for mozilla browsers, this handling will depend upon the mime content-type that is used on the object being downloaded. for nss-based servers it will depend upon the options selected in the server's administration interface. subsequent certificates are all treated the same. if the certificates contain a basicconstraints certificate extension that indicates they are ca certificates, and do not already exist in the local certificate database, they are added as untrusted cas. in this way they may be used for certificate chain validation, as long as there is a trusted ca somewhere along the chain.
...cates on web pages for download by other users who want to send them encrypted mail. note: the browser checks that the size of the object being downloaded matches the size of the encoded certificates. therefore it is important to ensure that no extra characters, such as nulls or linefeeds are added at the end of the object. importing certificates into nss-based servers consult your server's administration guide for the most accurate information. for some nss-base servers, the following information is correct. server certificates are imported via the server admin interface. certificates are pasted into a text input field in an html form, and then the form is submitted to the admin server. since the certificates are pasted into text fields, only the text formats described above are support...
...if a certificate chain is being imported then the first certificate in the chain must be the server or ca certificate, and any subsequent certificates will be added as untrusted ca certificates to the local database. ...
...if a certificate chain is being imported then the first certificate in the chain must be the server or ca certificate, and any subsequent certificates will be added as untrusted ca certificates to the local database. ...
NSS_3.12_release_notes.html
note: firefox 3 uses nss 3.12, but not the new sqlite-based shareable certificate and key databases. we missed the deadline to enable that feature in firefox 3. distribution information the cvs tag for the nss 3.12 release i...
...bug 357015: on windows, readsystemfiles reads 21 files as opposed to 10 files in c:\windows\system32. bug 361076: clean up the use_pthreads related code in coreconf/sunos5.mk. bug 361077: clean up the use_pthreads related code in coreconf/hp-ux*.mk. bug 402114: fix the incorrect function prototypes of ssl handshake callbacks ...
... single statically linked program bug 324740: add generation of sia and aia extensions to certutil bug 339737: libpkix ocsp checking calls cert_verifycert bug 358785: merge nss_libpkix_branch back to trunk bug 365966: infinite recursive call in vfy_verifydigestdirect bug 382078: pkix default http client returns error when try to get an ocsp response. ...
...bug 337088: coverity 405, pk11_paramtoalgid() in mozilla/security/nss/lib/pk11wrap/pk11mech.c bug 339907: oaep_xor_with_h1 allocates and leaks sha1cx bug 341122: coverity 633 sftk_destroyslotdata uses slot->slotlock then checks it for null bug 351140: coverity 995, pot...
NSS 3.14 release notes
the nss license has changed to mpl 2.0. previous releases were released under a mpl 1.1/gpl 2.0/lgpl 2.1 tri-license. ...
...ases/nss_3_14_rtm/src/. the cvs tag is nss_3_14_rtm. new in nss 3.14 the sections that follow discuss specific changes in nss 3.14 in more detail. support for tls 1.1 (rfc 4346) has been added (https://bugzilla.mozilla.org/show_bug.cgi?id=565047). to better support tls 1.1 and future versions of tls, a new version range api was introduced to allow applications to specify the desired minimum and maximum versions. these functions are intended to replace the now-deprecated use of the ssl_enable_ssl3 and ssl_enable_tls socket options. the following functions have been added to the libssl library included in nss 3.14 ssl_versionrangeget (in ssl.h) ssl_versionrangegetdefault (in ssl.h) ssl_versionrangegetsupported (in ssl.h) ssl_versionrangeset (...
...e certificate chains meet application-specific security policies, allowing libpkix to continue discovering certificate paths until it can find a chain that satisfies the policies. ...
...vantage of optimized assembly code for common operations. these changes have the observed effect of doubling rsa performance. bug 792681 - new default cipher suites the default cipher suites in nss 3.14 have been changed to better reflect the current security landscape. the defaults now better match the set that most major web browsers enable by default. bug 783448 - when performing an ssl renegotiation, the client_version that is sent in the renegotiation clienthello will be set to match the client_version that was sent in the initial clienthello. this is needed for compatibility with iis. certificate signatures that make use of the md5 hash algorithm will now be rejected by default. support for md5 may be manually enabled (but is discouraged) by setting the environment ...
NSS Sample Code Sample1
nss sample code 1: key generation and transport between servers. this is an example program that demonstrates how to do key generation and transport between cooperating servers. 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...
...e here shows how to create a permanent (token) // rsa key for this purpose. (this key will also be used for // storage of the keys, since nss does not support permanent symmetric // keys at the current time.) // 3. the secondary host sends its rsa public key to the primary host as // part of a request for a particular key, or to be added to a list // of secondary hosts. // 4. the administrator of the primary host verifies that the rsa key // that was received belongs to a valid secondary host. the adminstrator // may do this by checking that the key was received in a signed email // message, or by checking a digest value with the adminstrator of the // secondary host. [need support for digest check values] // 5. the primary host exports (wraps) the symmetric key u...
...the same methods outlined // in step 4 may be used here. // 7. the secondary host unwraps the the key using its own rsa private key. // note: currently nss does not support permanent symmetric keys. ...
... // wrapped keys are stored in data files. int generatekeys(); // gets the server's public key (wrapping key) to // send to another server. this becomes the input to // the exportkeys method on the remote server. int exportpublickey(secitem **pubkeydata); // export the encryption and key using the key // provided. the key should come from another server // in the cluster. (the admin should verify this.) // // in this example, the server must be started to perform // this function (see start()) int exportkeys(secitem *pubkey, secitem **wrappedenckey, secitem **wrappedmackey); // import the keys received from another server in the // cluster. the admin should make sure the keys actually // came from the correct source. int importkeys(secitem *wr...
PKCS11 FAQ
Mozilla › Projects › NSS › PKCS11 › FAQ
ficates are read from the token. other certificates on the token are also loaded (to allow building certificate chains), but it's not necessary to include the full chain, as long as the full chain is available in the regular certificate database. for the sake of completeness, it's also a good idea to expose public key objects. nss falls back to looking for for the existance of public keys to determine if the token may have the corresponding private key while the token is not logged in. how are permanent pkcs #11 objects found by nss? that is, which pkcs #11 attributes are used in the object searches? labels? key ids? key types? these are the general guidelines: user certificates are identified by their labels. certificates and keys are often looked up by the following methods: by ...
...ample, if the rsa slot unwraps a key, nss needs to move that key to a slot that can do the symmetric operations. nss itself uses two tokens internally--one that provides generic cryptographic services without authentication, and one that provides operations based on the keys stored in the user's database and do need authentication. nss does this to avoid having to prompt for a password when performing an rsa verify operation, des encryption, and so on. therefore, nss can move keys around when necessary and possible. when operating in fips mode, moving keys is significantly harder. in this case nss uses a single token to handle both key and cert storage and crypto operations. in general, you not should use different slots unless you have a good reason. much of nss's token selection is based o...
...nss softokn3 is not a complete pkcs #11 module, it was implemented only to support nss, though other products have managed to get it to work in their environment. there are a number of bugs against softoken's non-compliance, but these bugs have lower priority than fixing nss's non-complient uses of pkcs #11 or adding new features to nss. if multiple pkcs #11 modules are loaded, how does nss determine which ones to use for the mechanisms required by ssl? nss uses the first slot it finds that can perform all the required operations. on servers, it's almost always the slot that contains the server's private key. does nss support the use of pkcs #11 callbacks specified in the pnotify and papplication parameters for c_opensession? nss does not currently use any of the callbacks. nss applicati...
...he first slot it finds that can perform all the required operations. on servers, it's almost always the slot that contains the server's private key. does nss support the use of pkcs #11 callbacks specified in the pnotify and papplication parameters for c_opensession? nss does not currently use any of the callbacks. nss applications detect card insertion and deletion by means of polling to determine whether the card is still in the slot and whether the open session associated with that card is still valid, or by waiting on the c_waitforslotevent call. what must an x.509 certificate include to allow it to be recognized as an email certificate for use with s/mime? an email address must be included in the attribute of the subject dn or the mail attribute of the subject dn. if the subject dn ...
FC_GetInfo
_getinfo(ck_info_ptr pinfo); parameters fc_getinfo has one parameter: pinfo points to a ck_info structure description fc_getinfo returns general information about the pkcs #11 library. on return, the ck_info structure that pinfo points to has the following information: cryptokiversion: pkcs #11 interface version number implemented by the pkcs #11 library. ...
...urns general information about the pkcs #11 library. on return, the ck_info structure that pinfo points to has the following information: cryptokiversion: pkcs #11 interface version number implemented by the pkcs #11 library. the version is 2.20 (major=0x02, minor=0x14). manufacturerid: the pkcs #11 library manufacturer, "mozilla foundation", padded with spaces to 32 characters and not null-terminated. flags: should be 0. librarydescription: description of the library, "nss internal crypto services", padded with spaces to 32 characters and not null-terminated. libraryversion: pkcs #11 library version number, for example, 3.11 (major=0x03, minor=0x0b). a user may call fc_getinfo without logging into the token (to assume the nss user role). return value fc_getinfo always returns ckr_o...
..._list_ptr pfunctionlist; ck_rv crv; ck_info info; crv = fc_getfunctionlist(&pfunctionlist); assert(crv == ckr_ok); ... ...
... library:\n"); printf(" pkcs #11 version: %d.%d\n", (int)info.cryptokiversion.major, (int)info.cryptokiversion.minor); printf(" manufacturer id: %.32s\n", info.manufacturerid); printf(" flags: 0x%08lx\n", info.flags); printf(" library description: %.32s\n", info.librarydescription); printf(" library version: %d.%d\n", (int)info.libraryversion.major, (int)info.libraryversion.minor); printf("\n"); see also nsc_getinfo ...
sslerr.html
ssl_error_bad_cert_alert -12271 "ssl peer cannot verify your certificate." the remote system has received a certificate from the local system, and has rejected it for some reason. ssl_error_revoked_cert_alert -12270 "ssl peer rejected your certificate as revoked." the remote system has received a certificate from the local system, and has determined that the certificate has been revoked. ssl_error_expired_cert_alert -12269 "ssl peer rejected your certificate as expired." the remote system has received a certificate from the local system, and has determined that the certificate has expired. ssl_error_ssl_disabled -12268 "cannot connect: ssl is disabled." the local socket is configur...
...te that uses a key exchange algorithm for which the local server has no appropriate public key. this indicates a configuration error on the local server. ssl_error_token_insertion_removal -12205 "pkcs #11 token was inserted or removed while operation was in progress." a cryptographic operation required to complete the handshake failed because the token that was performing it was removed while the handshake was underway. another token may also have been inserted into the same slot. ssl_error_token_slot_not_found -12204 "no pkcs#11 token could be found to do a required operation." a cryptographic operation required a pkcs#11 token with specific abilities, and no token could be found in any slot, including the "soft token" in the intern...
...this probably indicates a flaw in the remote peer's implementation. ssl_error_rx_unknown_record_type ...
...ror_ocsp_unauthorized_request -8068 "the ocsp server has refused this request as unauthorized." sec_error_ocsp_unknown_response_status -8067 "the ocsp server returned an unrecognizable status." sec_error_ocsp_unknown_cert -8066 "the ocsp server has no status for the certificate." sec_error_ocsp_not_enabled -8065 "you must enable ocsp before performing this operation." sec_error_ocsp_no_default_responder -8064 "you must set the ocsp default responder before performing this operation." sec_error_ocsp_malformed_response -8063 "the response from the ocsp server was corrupted or improperly formed." sec_error_ocsp_unauthorized_response -8062 "the signer of the ocsp response is not authorized to give stat...
Installing Pork
mode. apply this patch: note: this doesn't seem necessary in the latest version; cppflags is already an argument. ...
...cd ${inc_dir}/mcpp-gcc" cd ${inc_dir}/mcpp-gcc if test ! ...
... echo " generating g*.h header files: ${cppflags}" + ${cc} ${cppflags} -e -xc -dm /dev/null | sort | grep ' *#define *_' \ > gcc${gcc_maj_ver}${gcc_min_ver}_predef_std.h - ${cc} -e -xc -dm /dev/null | sort | grep -e ' *#define *[a-za-z]+' \ + ${cc} ${cppflags} -e -xc -dm /dev/null | sort | grep -e ' *#define *[a-za-z]+' \ > gcc${gcc_maj_ver}${gcc_min_ver}_predef_old.h - ${cxx} -e -xc++ -dm /dev/null | sort | grep ' *#define *_' \ + ${cxx} ${cppflags} -e -xc++ -dm /dev/null | sort | grep ' *#define *_' \ > gxx${gcc_maj_ver}${gcc_min_ver}_predef_std.h - ${cxx} -e -xc++ -dm /dev/null | sort | grep -e ' *#define *[a-za-z]+' \ + ${cxx} ${cppflags} -e -xc++ -dm /dev/null | sort | grep -e ' *#define *[a-za-z]+' \ ...
... -xc++ -dm /dev/null | sort | grep ' *#define *_' \ + ${cxx} ${cppflags} -e -xc++ -dm /dev/null | sort | grep ' *#define *_' \ > gxx${gcc_maj_ver}${gcc_min_ver}_predef_std.h - ${cxx} -e -xc++ -dm /dev/null | sort | grep -e ' *#define *[a-za-z]+' \ + ${cxx} ${cppflags} -e -xc++ -dm /dev/null | sort | grep -e ' *#define *[a-za-z]+' \ > gxx${gcc_maj_ver}${gcc_min_ver}_predef_old.h fi if test ${host_system} = sys_cygwin; then if you don't do this, mcpp will get the wrong set of automatic definitions and you'll end up with an unpleasant hybrid x86-64/i686 build system. $ export path=/builds/gcc-3.4.6-installed/bin:$path $ export cppflags=-m32 $ cc=gcc34 cxx=g++34 cppflags=-m32 ldflags=-m32 ../src/configure --enable-replace-cpp --prefix=/builds/gcc-3.4.6...
Rhino overview
rhino 1.3 and greater conform to edition 3 of the standard. rhino 1.6 and greater implement ecma-357 ecmascript for xml (e4x). see the specification for more information on the standard, and rhino version 1.6r1 release notes for details on the implementation in rhino. in addition, rhino has implemented javaadapters, which allows javascript to implement any java interface or extend an...
...ascript object. see the enum.js example for more information. numerous books and tutorials on javascript are available. javascript: the definitive guide is recommended, and contains a chapter on rhino. deprecated language features several language features introduced in javascript 1.2 are now deprecated. these features allow "computational reflection": that is, the ability for a script to determine and influence aspects of the way it is evaluated. these features are generally not broadly useful, yet they impose significant constraints on implementations that hamper or prevent optimization. the deprecated features are the __proto__ and __parent__ properties, and the constructors with, closure, and call. attempts to invoke these constructors with the language version 1.4 will result in an er...
...ext that is created must be supplied an instance of an object that implements the securitysupport interface. this will provide rhino the support functionality it needs to perform security-related tasks. second, the value of the property security.requiresecuritydomain should be changed to true in the resource bundle org.mozilla.javascript.resources.security. the value of this property can be determined at runtime by calling the issecuritydomainrequired method of context. setting this property to true requires that any calls that compile or evaluate javascript must supply a security domain object of any object type that will be used to identify javascript code. in a typical client embedding, this object might be a string with the url of the server that supplied the script, or an object that co...
...t to obtain the security domain of the currently executing interpreted script or function. otherwise, it must be a generated class, and an embedding can call getsecuritydomain() in the class implementing securitysupport. when the class was defined and loaded, the appropriate security domain was associated with it, and can be retrieved by calling this method. once the security domain has been determined, an embedding can perform whatever checks are appropriate to determine whether access should be allowed. ...
Scripting Java
this article shows how to use rhino to reach beyond javascript into java. scripting java has many uses. it allows us to write powerful scripts quickly by making use of the many java libraries available. we can test java classes by writing scripts. we can also aid our java development by using scripting for exploratory programming. exploratory programming is the process of learning about what a library or api can do by writing quick programs that use it. as we will see, scripting makes this process easier. note that the ecma standard doesn't cover communication with java (or with any external object system for that matter). all the functionality covered in this chapter should thus be considered an extension. accessing java packages and classes every piece of java code is part of a c...
...va.io.file[] listfiles(java.io.filefilter) */} this output shows that the file class defines three overloaded methods listfiles: one that takes no arguments, another with a filenamefilter argument, and a third with a filefilter argument. all the methods return an array of file objects. being able to view the parameters and return type of java methods is particularly useful in exploratory programming where we might be investigating a method and are unsure of the parameter or return types. another useful feature for exploratory programming is the ability to see all the methods and fields defined for an object. using the javascript for..in construct, we can print out all these values: js> for (i in f) { print(i) } exists parentfile mkdir tostring wait [44 others] note that not only the met...
...r a new java class that implements runnable and forwards all calls to its run method over to an associated javascript object. the object that implements this class is called a java adapter. because the forwarding to javascript occurs at runtime, it is possible to delay defining the methods implementing an interface until they are called. while omitting a required method is bad practice for programming in the large, it's useful for small scripts and for exploratory programming. the javaadapter constructor in the previous section we created java adapters using the new operator with java interfaces. this approach has its limitations: it's not possible to implement multiple interfaces, nor can we extend non-abstract classes. for these reasons there is a javaadapter constructor. the syntax of t...
... for example, to create an array of bytes, we must use the special field java.lang.byte.type: js> a = java.lang.reflect.array.newinstance(java.lang.character.type, 2); [c@7a84e4 the resulting value can then be used anywhere a java array of that type is allowed. js> a[0] = 104 104 js> a[1] = 105 105 js> new java.lang.string(a) hi java strings and javascript strings it's important to keep in mind that java strings and javascript strings are not the same. java strings are instances of the type java.lang.string and have all the methods defined by that class. javascript strings have methods defined by string.prototype. the most common stumbling block is length, which is a method of java strings and a dynamic property of javascript strings: js> javastring = new java.lang.string("java") java...
64-bit Compatibility
ze_t jsval jsuword, jsword length of a string, though the actual length cannot exceed 30 bits jsuintptr, jsintptr, jsptrdiff, jsuptrdiff, jssize, jsuword, jsword (let's not use these, kthx) the following types are 32-bit on 32-bit platforms. for all intents and purposes they are also 32-bit on 64-bit platforms: intn, uintn jsintn, jsuintn, jsbool general problems with pointers when performing bitwise operations on pointer values, make sure that both operands are 64-bit. the compiler can implicitly sign or zero extend operands with unintended side effects. for example, consider this code: #define pointer_tagbits 3 static inline uintptr_t unmaskpointer(uintptr_t v) { return v & ~pointer_tagbits; } the value 3 will be inverted to 0xfffffffc, then zero-extended to 0x00000000ffff...
...ues, make sure that both operands are 64-bit. the compiler can implicitly sign or zero extend operands with unintended side effects. ...
...if you use these bits to squirrel away a payload, they must be adjusted before attempting to dereference the pointer. for more information and platform specific details on virtual address widths, see this article on wikipedia. ...
... from an integer array, but it is not portable: lir->insload(lir_ldp, lir->ins2(lir_piadd, arrayins, lir->ins2i(lir_mul, indexins, sizeof(int)) ), 0); the sanityfilter will assert on a 64-bit platform because lir_piadd (which will be lir_qiadd) needs both operands to be 64-bit. ...
Property cache
spidermonkey's property cache is an internal data structure used to speed up property accesses in the interpreter and to communicate between the interpreter and jit. warning: the details below are obsolete. shape integers do not exist anymore. the property cache still exists, but it is simpler now. ...
...ies are being accessed; in cases where type inference does not find the exact shape of the object being accessed, spidermonkey uses a pic (polymorphic inline caches) to store the result of the lookup. the property cache is only used in the interpreter. the property cache was introduced in bug 365851. basics in general, accessing a property of a native object entails: a property lookup; examining the shape to see how the property can be accessed; actually carrying out the property access. the property cache is a per-thread cache of the results of steps 1 and 2. when executing certain property-accessing bytecode instructions, the interpreter populates the cache to speed future execution of the same instruction. the jit reads the property cache too, as it needs the same information w...
...(informally: if another variable or property shadows x'.p, the shape of x' will change.) o this object ...
...ce. entry value words for the .vword member of a non-adding property cache entry, one of the following is true: vword.isshape() vword.toshape() points to the js::shape that describes the property in question. this is the default type of vword generated when neither of the two special cases below applies. a cache hit of this type saves a property lookup, but the interpreter still has to examine vword.toshape() to determine what to do next. vword.isslot() the property has a slot which the interpreter can read directly. this special kind of entry is used only for jof_get instructions and only when the property has a stub getter and has a slot (i.e. it is not jsprop_shared). the slot index is vword.toslot(). vword.isobject() the property has a stub getter and its value is vw...
JS::CompileOptions
js_threadsafe build, the caller must be in a request on this jscontext. version jsversion javascript version used to compile the script. methods some methods of js::owningcompileoptions and js::compileoptions return the instance itself to allow method chain. methods of js::readonlycompileoptions method description bool mutederrors() const determines if errors are muted. the web platform allows scripts to be loaded from arbitrary cross-origin sources. 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. to counter this attack, html5 specifies ...
...of that attribute, a string. otherwise, this returns null. jsscript *introductionscript() const returns a pointer to jsscript which introduces the file. bool copy(jscontext *cx, const readonlycompileoptions &rhs) copy compile options from rhs. returns false if it failed to duplicate owning properties. bool setfile(jscontext *cx, const char *f) duplicate null-terminated string f for filename(). returns false if it failed to duplicate. bool setfileandline(jscontext *cx, const char *f, unsigned l) duplicate null-terminated string f for filename() and set lineno property. returns false if it failed to duplicate. bool setsourcemapurl(jscontext *cx, const char16_t *s) duplicate null-terminated string s for sourcemapurl. returns false if it...
...returns false if it failed to duplicate. owningcompileoptions &setline(unsigned l) sets each property and returns the instance itself. ...
...returns false if it failed to duplicate. methods of js::compileoptions method description jsobject *element() const same as js::owningcompileoptions. jsstring *elementattributename() co...
JS::IdentifyStandardInstance
this article covers features introduced in spidermonkey 31 determine if the given object is an instance/prototype/constructor for a standard class. syntax jsprotokey js::identifystandardinstance(jsobject *obj); jsprotokey js::identifystandardprototype(jsobject *obj); jsprotokey js::identifystandardinstanceorprototype(jsobject *obj); jsprotokey js::identifystandardconstructor(jsobject *obj); // added in spidermonkey 38 name type description obj jsobject * pointer to the instance/prototype/constructor object to determine. description js::identifystandardinstance determines if the given object is an instance for a standard class. if so, return the associated jsprotokey. ...
...bject *obj); // added in spidermonkey 38 name type description obj jsobject * pointer to the instance/prototype/constructor object to determine. description js::identifystandardinstance determines if the given object is an instance for a standard class. if so, return the associated jsprotokey. if not, return jsproto_null. js::identifystandardprototype determines if the given object is a prototype for a standard class. if so, return the associated jsprotokey. if not, return jsproto_null. ...
...if so, return the associated jsprotokey. if not, return jsproto_null. ...
...if so, return the associated jsprotokey. if not, return jsproto_null. ...
SpiderMonkey 1.8.5
t, etc.) have been replaced with a family of type-safe functions (js_addstringroot, js_removestringroot, etc.) that are easier to use correctly. js_newdouble, js_newdoublevalue, and js_newnumbervalue are gone. instead use double_to_jsval, int_to_jsval, and uint_to_jsval, which are faster and can't fail. js_getstringbytes and js_getstringchars are gone. there is no longer an infallible way to examine string characters. applications must use js_getstringcharsandlength or js_encodestring/js_free and check for errors. these and other changes are explained in detail below. new javascript language features javascript 1.8.5 adds support for ecmascript edition 5, including es5 strict mode. for details, see new in javascript 1.8.5. note that there are a very small number of incompatibilities betwe...
...e --enable-ctypes option and choose one of the configuration options to enable nspr (e.g. --with-system-nspr). garbage collection spidermonkey 1.8.5 introduces a conservative stack-scanning garbage collector. unlike the exact garbage collector, the new garbage collector will scan the c stack and registers in your embedding, looking for bits that it can treat as potential gc roots. the approach eliminates the need for the js_enterlocalrootscope api, and in many cases the need to explicitly root gc things or use the "root as you go" approach popular with earlier spidermonkey releases. since this is a conservative collector, it will often find "garbage" addresses which can trigger warnings from certain code analysis tools. if you are running valgrind on your embedding, be sure to build spiderm...
... releases. since this is a conservative collector, it will often find "garbage" addresses which can trigger warnings from certain code analysis tools. if you are running valgrind on your embedding, be sure to build spidermonkey with the --enable-valgrind option to suppress superflous error messages triggered by the garbage collector. this also means that objects will be finalized in a non-deterministic order in spidermonkey 1.8.5. this is not a bug, and, any embedding which depends upon deterministic finalization is fatally flawed. typed rooting api the rooting api has been changed from an error-prone void ** interface to an interface which accepts pointers to specific types. js_addroot has been replaced by js_addobjectroot, js_addvalueroot and js_addstringroot; similar changes were made ...
...tions in the javascript shell, mostly useful for testing spidermonkey. the scatter function has been removed, and a shell worker class (similar to html dom workers) has been added. known issues mac os x 10.5 (leopard) and xcode 3.2 spidermonkey will not build with certain builds of apple's gcc 4.2 c++ compiler. to check what version you are running, issue the command /usr/bin/g++-4.2 -v from a terminal window. the following builds are known to not work: i686-apple-darwin9-g++-4.2.1 (gcc) 4.2.1 (apple inc. build 5574) to work around this issue, either upgrade your xcode or use an alternate version of gcc, such as the one that shipped with leopard. to select an alternate c++ compiler, invoke configure thus: cxx=/usr/bin/g++-4.0 /path/configure --my-configuration-options js-config the new con...
Mork
Mozilla › Tech › Mork
it is structured as a comment so it can be safely ignored by the parser. the header is: // <!-- <mdb:mork:z v="1.4"/> --> this file is therefore version 1.4 of the zany mork format for the message database. ...
...ponding metastructures. meta-dictionaries are in practice only used to change the scope of alias definitions (the '(a=c)' that you can see in files). meta-tables are used to establish some facts about the table as well as the default row scope. meta-rows do not appear to be used at all, although the parser seems to consider setting the charset, row scope, and atom scope. some notes on further terminology: when referring to cells or aliases, the first component is the key and the second component is the value. expanding refers to taking a '^' hex buffer and replacing it with the alias value for the hex key (explained below). a mid has two components: the id itself, to the left of the colon, and the scope, to the right of the colon. there are two types of meta-rows, those of rows and those of...
...d). the presence of a row or rowreference in the meta-table indicates that said row is the meta-row of the table: it contains arbitrary properties for the entire table just like a normal row. for example, the message summary format files use a table for each thread, where the meta-rows represent information about the thread in general. the last important point about tables is the meaning of the minuses. a minus before the table id indicates that all the rows currently stored in the table should be removed before adding more rows. a minus sign before a row or rowreference indicates that said row should be removed from the table. rows for the most part, a row should not be seen outside of a table; the only time i have seen one outside a table is for table meta-rows. the first mid, as you shou...
...ow id, with the scope being an important part of the id, in that 1:scope1 is not the same row as 1:scope2. if the scope is not specified, then it is the default scope of the table (if it has one) or 'r' otherwise. these row ids are global, even if defined in a table. indeed, defining a row in a table is a shortcut for both defining a row and adding the row to the table. the presence of an initial minus means to delete all cells before adding new cells. a minus after the mid indicates that the next cell should be deleted. i haven't seen that case though, so it may not be an issue in practice. the rowreference is a mid that refers to a specific row. if it occurs in a table, you can treat it as adding that row to a table; in a meta-table, it is the same as making that row the meta-row of the tab...
Frecency algorithm
frecency is a score given to each unique uri in places, encompassing bookmarks, history and tags. this score is determined by the amount of revisitation, the type of those visits, how recent they were, and whether the uri was bookmarked or tagged. the word "frecency" itself is a combination of the words "frequency" and "recency." the default frecency value for all valid entries is -1. places with this value can show up in autocomplete results. invalid places have a frecency value of zero, and will not show up in autocomplete results. examples of invalid places are "place:" queries, and unvisited livemark feed entries. ...
...ecency." the default frecency value for all valid entries is -1. places with this value can show up in autocomplete results. invalid places have a frecency value of zero, and will not show up in autocomplete results. examples of invalid places are "place:" queries, and unvisited livemark feed entries. the frecency calculation process for the 10 most recent visits (where 10 is determined by places.frecency.numvisits): .. determine percentage bonus for type of visit (ie: the "transition type"): .... 0 (places.frecency.embedvisitbonus) .... 120 (places.frecency.linkvisitbonus) .... 200 (places.frecency.typedvisitbonus) .... 140 (places.frecency.bookmarkvisitbonus) .... 0 (places.frecency.downloadvisitbonus) .... 0 (pl...
... .... 120 (places.frecency.linkvisitbonus) .... 200 (places.frecency.typedvisitbonus) .... 140 (places.frecency.bookmarkvisitbonus) .... 0 (places.frecency.downloadvisitbonus) .... 0 (places.frecency.permredirectvisitbonus) .... 0 (places.frecency.tempredirectvisitbonus) .... 0 (places.frecency.defaultvisitbonus) .. determine weight, based on how recent the visit was: .... 100 (places.frecency.firstbucketweight, 4 days bucket size, in places.frecency.firstbucketcutoff) .... 70 (places.frecency.secondbucketweight, 14 days bucket size, in places.frecency.secondbucketcutoff) .... 50 (places.frecency.thirdbucketweight, 31 days bucket size, in places.frecency.thirdbucketcutoff) .... 30 ...
... the total visit count includes embedded, undefined, etc visits (does not exclude invalid or embedded visits). developer notes there are various development notes you can read about places that may offer additional insights: initial algorithm ideas implementation notes history the initial algorithm design was by mike connor and seth spi...
Component Internals
spective of a client of xpcom components, this chapter discusses components from the perspective of the software developer. read on to see how components are generally implemented in xpcom, or you can skip to the next chapter, where the weblock component tutorial takes you step by step through the component creation process. xxx mediawiki...xxx sucks creating components in c++ let's start by examining how xpcom components are written in c++. the most common type of component is one that is written in c++ and compiled into a shared library (a dll on a windows system or a dso on unix). the illustration below shows the basic relationship between the shared library containing the component implementation code you write and the xpcom framework itself. in this diagram, the outer boundary is that...
...led manifests to track and persist information about the components to the local system. there are two types of manifests that xpcom uses to track components: component manifests when xpcom first starts up, it looks for the component manifest, which is a file that lists all registered components, and stores details on exactly what each component can do. xpcom uses the component manifest to determine which components have been overridden. starting with mozilla 1.2, this file is named compreg.dat and exists in the components directory, but there are efforts to move it out of this location to a less application-centric (and thus more user-centric) location. any gecko-based application may choose to locate it elsewhere. xpcom reads this file into an in-memory database. component manifests th...
...s an interface is explicitly marked "frozen" in the idl comments, your component may possibly break or crash along with a version change. the glue library in general, you should avoid any interfaces, symbols in xpcom, or other part of gecko libraries that aren't frozen. however, there are some unfrozen tools in xpcom that are used so often they are practically required parts of component programming. the smart pointer class, nscomptr, for example, which makes reference counting less tedious and error-prone, is not actually frozen, and neither is nsdebug, a class for aiding in tracking down bugs, nor is nsmemory, a class to ensure that everyone uses the same heap, generic factory, and module. instead of asking every developer to find and copy these various files into their own application, ...
...o some string class or other in order to utilize certain gecko apis, but the string code that mozilla uses is highly complex and even more expensive than the glue code in terms of footprint (~100k). nsembedstring and nsembedcstring are available as very lightweight string implementations for component development, especially in small embedded applications. this string implementation does the bare minimum to support the nsastring/nsacstring functionality. in your own component, you can go "slim" and restrict yourself to the nsembedstring or go "hog wild" and use any of the the other strings. weblock restricts itself to using the simple nsembedstring family of classes. string classes and xpcom the glue library provides stub functions for the public functions that xpcom provides (see xpcom/...
Finishing the Component
suggest a supported alternative, or they may be able to notify you about pending changes. the interface that we need for this project is something called nsicontentpolicy. at the time this book was written, this interface was under review. an interface reaches this state when a group of module owners and peers are actively engaged in discussion about how best to expose it. usually there are only minor changes to interfaces marked with such a tag. even with interfaces marked "under review," however, it's still a good idea to contact the module owners responsible for the interfaces you are interested in using. copying interfaces into your build environment to get and implement interfaces that are not part of gecko in your component, simply create a new directory in the gecko sdk named unfroz...
... nsiuri *contentlocation, nsisupports *ctxt, nsidomwindow *window, prbool *_retval) uniform resource locators the method passes in an interface pointer of type nsiuri, which is based on the uniform resource identifier, or uri. this type is defined by the world wide web consortium as: the naming scheme of the mechanism used to access the resource. the name of the machine hosting the resource. the name of the resource itself, given as a path. in this context, uris are the strings used refer to places or things on the web. this specific form of uri is called a uniform resource locator, or url. see the intro to the html 4 specification for more information about uris and urls. gecko e...
...ead of extracting the string spec out of the nsiuri to do a string comparison, which would require you to do the parsing yourself, you can compare the nsiuri objects with each other, as in the following section. this ensures that the urls are canonical before they are compared. checking the white list the weblock implementation of the shouldload method starts by extracting the scheme of the incoming nsiuri. if the scheme isn't "http", "https", or "ftp", it immediately returns true, which continues the loading process unblocked. these three are the only kinds of uri that weblock will try to block. when it has one, it walks the linked list and creates a new nsiuri object for each string url in the list. from each object, shouldload() extracts the host and compares it to the uri. if they matc...
... nsnull, nsnull, getter_addrefs(uri)); this code wraps a c-string with a nsembedcstring, which you'll recall is a string class that many of the gecko apis require. see string classes in xpcom for more information about strings. once the url string is wrapped in a nsembedcstring, it can be passed to the method newuri. this method expects to parse the incoming string and create an object which implements an nsiuri interface. the two nsnull parameters passed to newuri are used to specify the charset of the string and any base uri to use, respectively. we are assuming here that the charset of the url string is utf-8, and also assuming that every url string is absolute. see the intro to the html 4 specification for more information about relative urls. ...
XPCOM Stream Guide
Mozilla › Tech › XPCOM › Guide › Streams
aracters, though: the characters may not all be available when you read from the stream. think of a water tank with a spout: the tank may be full, or it may be half-full, or it may be empty. the spout controls how much water you can get out of the tank at a time. the spout is a source of water. ...
...out of the tank at a time. the spout is a source of water. if we think of the water as data, then the spout represents an input stream: a controller for data coming out of something. at the same time, there may be some way to put water into the tank - say, a main water line. that water line represents an output stream: a controller for data going into something. the actual data going in to and coming out of an object isn't usually important to a stream. streams simply provide a way to read or write data to some object. in basic c++ programming for a console application, we usually talk about streams to access files, or to interact with the user. mozilla's use of streams is more complex. on the one hand, we don't interact with the user through streams. on the other hand, we use streams to ac...
...we even have streams that take input from other streams and transform the data within them to something more useful. primitive streams there are streams for several different types of data storage. ...
...rface how to bind to a primitive input stream multiplex concatenate multiple input streams into one. nsmultiplexinputstream @mozilla.org/io/multiplex-input-stream;1 nsimultiplexinputstream .appendstream(stream) .insertstream(stream, index) buffered read ahead in the underlying stream into a buffer, so that calls to the underlying stream are minimized. nsbufferedinputstream @mozilla.org/network/buffered-input-stream;1 nsibufferedinputstream .init(stream, buffersize) binary read binary data from the underlying stream, in "big-endian" order. nsbinaryinputstream @mozilla.org/binaryinputstream;1 nsibinaryinputstream .setinputstream(stream) object read a nsisupports object from the underlying st...
nsACString_internal
this type is not instantiated directly. a sub-class is instantiated instead. for example, see nststring. names: nsastring for wide characters nsacstring for narrow characters many of the accessors on nstsubstring are inlined as an optimization. ...
...37" href="http://developer.mozilla.org/en/ns_convertutf16toutf8" shape="rect" title="ns_convertutf16toutf8"> <area alt="" coords="309,293,445,341" href="http://developer.mozilla.org/en/nsadoptingcstring" shape="rect" title="nsadoptingcstring"> </map> method overview constructors beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char assign assignascii assignliteral(const char assignliteral(char operator= adopt replace replaceascii append ap...
...riting() - source nswritingiterator<char>& endwriting(nswritingiterator<char>&) - source parameters nswritingiterator<char>& iter char*& endwriting(char*&) - source parameters char*& iter data char* data() const - source accessors length pruint32 length() const - source isempty prbool isempty() const - source isvoid prbool isvoid() const - source isterminated prbool isterminated() const - source charat char charat(pruint32) const - source parameters pruint32 i operator[] char operator[](pruint32) const - source parameters pruint32 i first char first() const - source last char last() const - source countchar pruint32 countchar(char) const - source parameters char <anonymous> findchar print32 find...
...ascii prbool equalsascii(const char*, pruint32) const - source an efficient comparison with ascii that can be used even for wide strings. call this version when you know the length of 'data'. parameters char* data pruint32 len prbool equalsascii(const char*) const - source an efficient comparison with ascii that can be used even for wide strings. call this version when 'data' is null-terminated. parameters char* data equalsliteral(const char prbool equalsliteral(const char (&)[n]) const - source equalsliteral(char prbool equalsliteral(char (&)[n]) const - source lowercaseequalsascii prbool lowercaseequalsascii(const char*, pruint32) const - source parameters char* data pruint32 len prbool lowercaseequalsascii(const char*) const - source parameters char...
nsAString_internal
this type is not instantiated directly. a sub-class is instantiated instead. for example, see nststring. names: nsastring for wide characters nsacstring for narrow characters many of the accessors on nstsubstring are inlined as an optimization. ...
...,437" href="http://developer.mozilla.org/en/ns_convertutf8toutf16" shape="rect" title="ns_convertutf8toutf16"> <area alt="" coords="277,293,405,341" href="http://developer.mozilla.org/en/nsadoptingstring" shape="rect" title="nsadoptingstring"> </map> method overview constructors beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char assign assignascii assignliteral(const char assignliteral(char operator= adopt replace replaceascii append ap...
...dwriting(nswritingiterator<short unsigned int>&) - source parameters nswritingiterator<short unsigned int>& iter prunichar*& endwriting(prunichar*&) - source parameters prunichar*& iter data prunichar* data() const - source accessors length pruint32 length() const - source isempty prbool isempty() const - source isvoid prbool isvoid() const - source isterminated prbool isterminated() const - source charat prunichar charat(pruint32) const - source parameters pruint32 i operator[] prunichar operator[](pruint32) const - source parameters pruint32 i first prunichar first() const - source last prunichar last() const - source countchar pruint32 countchar(prunichar) const - source parameters prunichar <anonymous...
...ascii prbool equalsascii(const char*, pruint32) const - source an efficient comparison with ascii that can be used even for wide strings. call this version when you know the length of 'data'. parameters char* data pruint32 len prbool equalsascii(const char*) const - source an efficient comparison with ascii that can be used even for wide strings. call this version when 'data' is null-terminated. parameters char* data equalsliteral(const char prbool equalsliteral(const char (&)[n]) const - source equalsliteral(char prbool equalsliteral(char (&)[n]) const - source lowercaseequalsascii prbool lowercaseequalsascii(const char*, pruint32) const - source parameters char* data pruint32 len prbool lowercaseequalsascii(const char*) const - source parameters char...
IAccessibleValue
cessiblevalue interface represents a single numerical value and should be implemented by any class that supports numerical value like progress bars and spin boxes. this interface lets you access the value and its upper and lower bounds. method overview [propget] hresult currentvalue([out] variant currentvalue ); [propget] hresult maximumvalue([out] variant maximumvalue ); [propget] hresult minimumvalue([out] variant minimumvalue ); hresult setcurrentvalue([in] variant value ); methods currentvalue() returns the value of this object as a number. the exact return type is implementation dependent. typical types are long and double. [propget] hresult currentvalue( [out] variant currentvalue ); parameters currentvalue returns the current value represented by this object. see the se...
...type of the returned value is implementation dependent. it does not have to be the same type as that returned by method currentvalue(). [propget] hresult maximumvalue( [out] variant maximumvalue ); parameters maximumvalue returns the maximal value in an implementation dependent type. if this object has no upper bound then an empty object is returned. see the section about. return value s_ok. minimumvalue() returns the minimal value that can be represented by this object. the type of the returned value is implementation dependent. it does not have to be the same type as that returned by method currentvalue(). [propget] hresult minimumvalue( [out] variant minimumvalue ); parameters minimumvalue returns the minimal value in an implementation dependent type. if this object has no lower b...
...hresult setcurrentvalue( [in] variant value ); parameters value the new value represented by this object. the set of admissible types for this argument is implementation dependent. return value s_ok. ...
...inimal value in an implementation dependent type. if this object has no lower bound then an empty object is returned. see the section about. return value s_ok. setcurrentvalue() sets the value of this object to the given number. the argument is clipped to the valid interval whose upper and lower bounds are returned by the methods maximumvalue() and minimumvalue(), that is if it is lower than the minimum value the new value will be the minimum and if it is greater than the maximum then the new value will be the maximum. hresult setcurrentvalue( [in] variant value ); parameters value the new value represented by this object. the set of admissible types for this argument is implementation dependent. return value s_ok. ...
nsIAccessibleEvent
nd-drop mode. event_dragdrop_end 0x0023 0x0020 an application is about to exit drag-and-drop mode. event_dialog_start 0x0024 0x0021 a dialog box has been displayed. event_dialog_end 0x0025 0x0022 a dialog box has been closed. event_scrolling_start 0x0026 0x0023 scrolling has started on a scroll bar. event_scrolling_end 0x0027 0x0024 scrolling has ended on a scroll bar. event_minimize_start 0x0028 0x0025 a window object is about to be minimized or maximized. event_minimize_end 0x0029 0x0026 a window object has been minimized or maximized. event_document_load_complete 0x002b 0x0027 the loading of the document has completed. event_document_reload 0x002c 0x0028 the document contents are being reloaded. event_document_load_stopped 0x002d 0x0029 the loading o...
...041 a table's column header changed. event_table_column_insert 0x0046 0x0042 event_table_column_delete 0x0047 0x0043 event_table_column_reorder 0x0048 0x0044 event_window_activate 0x0049 0x0045 event_window_create 0x004a 0x0046 event_window_deactivate 0x004b 0x0047 event_window_destroy 0x004c 0x0048 event_window_maximize 0x004d 0x0049 event_window_minimize 0x004e 0x004a event_window_resize 0x004f 0x004b event_window_restore 0x0050 0x004c event_hyperlink_end_index_changed 0x0051 0x004d the ending index of this link within the containing string has changed. event_hyperlink_number_of_anchors_changed 0x0052 0x004e the number of anchors associated with this hyperlink object has changed. event_hyperlink_selected_link_change...
...7 event_capturestart 0x0008 event_captureend 0x0009 event_movesizestart 0x000a event_movesizeend 0x000b event_contexthelpstart 0x000c event_contexthelpend 0x000d event_dragdropstart 0x000e event_dragdropend 0x000f event_dialogstart 0x0010 event_dialogend 0x0011 event_scrollingstart 0x0012 event_scrollingend 0x0013 event_minimizestart 0x0016 event_minimizeend 0x0017 event_atk_property_change 0x0100 event_atk_selection_change 0x0101 event_atk_text_change 0x0102 event_atk_text_selection_change 0x0103 event_atk_text_caret_move 0x0104 event_atk_visible_data_change 0x0105 event_atk_table_model_change 0x0110 event_atk_table_row_insert 0x0111 event_atk_table_row_de...
... event_dom_destroy 0x0002 an object has been destroyed. event_dom_significant_change 0x0003 an object's properties or content have changed significantly so that the type of object has really changed, and therefore the accessible should be ...
nsIBlocklistService
appversion optional the version of the application we are checking in the blocklist. if this parameter is null, the version of the running ...
... appversion optional the version of the application we are checking in the blocklist. if this parameter is null, the version of the running application is used. ...
...rsion of the application we are checking in the blocklist. if this parameter is null, the version of the running application is used. toolkitversion optional the version of the toolkit we are checking in the blocklist. if this parameter is null, the version of the running toolkit is used. return value the blocklist state of the add-on, one of the constants. getpluginblockliststate() determine the blocklist state of a plugin. unsigned long getpluginblockliststate( in nsiplugintag plugin, in astring appversion, optional in astring toolkitversion optional ); parameters plugin the plugin to get the state for. appversion optional the version of the application we are checking in the blocklist. if this parameter is null, the version of the running application is use...
...he version of the application we are checking in the blocklist. if this parameter is null, the version of the running application is used. toolkitversion optional the version of the toolkit we are checking in the blocklist. if this parameter is null, the version of the running toolkit is used. return value the blocklist state of the plugin, one of the constants. isaddonblocklisted() determine if an item is blocklisted. boolean isaddonblocklisted( in jsval addon, in astring appversion, optional from gecko 1.9.1 in astring toolkitversion optional from gecko 1.9.1 ); parameters addon the addon object to be checked. appversion optional from gecko 1.9.1 the version of the application we are checking in the blocklist. if this parameter is null, the version of the ru...
nsICache
mething new i want to write into the cache, make me a new entry and doom the old one, if any. access granted - you must write to this descriptor because the cache entry was just created for you. access_read_write 3 access requested - i want to read, but i'm willing to update an existing entry if necessary, or create a new one if none exists. access granted - you can read the descriptor to determine if it's valid, you may write if it needs updating. store_anywhere 0 the storage policy of a cache entry determines the device(s) to which it belongs. see nsicachesession and nsicacheentrydescriptor for more details. allows the cache entry to be stored in any device. the cache service decides which cache device to use based on "some resource management calculation." store_in_memory 1 the st...
...t needs updating. store_anywhere 0 the storage policy of a cache entry determines the device(s) to which it belongs. see nsicachesession and nsicacheentrydescriptor for more details. allows the cache entry to be stored in any device. the cache service decides which cache device to use based on "some resource management calculation." store_in_memory 1 the storage policy of a cache entry determines the device(s) to which it belongs. see nsicachesession and nsicacheentrydescriptor for more details. requires the cache entry to reside in non-persistent storage. that is typically in system ram. store_on_disk 2 the storage policy of a cache entry determines the device(s) to which it belongs. see nsicachesession and nsicacheentrydescriptor for more details. requires the cache entry to reside...
...ide in non-persistent storage. that is typically in system ram. store_on_disk 2 the storage policy of a cache entry determines the device(s) to which it belongs. see nsicachesession and nsicacheentrydescriptor for more details. requires the cache entry to reside in persistent storage. that is typically on a system's hard disk. store_on_disk_as_file 3 the storage policy of a cache entry determines the device(s) to which it belongs. see nsicachesession and nsicacheentrydescriptor for more details. requires the cache entry to reside in persistent storage, and in a separate file. store_offline 4 the storage policy of a cache entry determines the device(s) to which it belongs. see nsicachesession and nsicacheentrydescriptor for more details. requires the cache entry to reside in persisten...
... then a descriptor will be created for a new cache entry for the key. note: if you think that you might need to modify cached data or meta data, then you must open a cache entry requesting write access. only one cache entry descriptor, per cache entry, will be granted write access. usually, you will request read_write access in order to first test the meta data and informational fields to determine if a write, that is going to the net, may actually be necessary. 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. a descriptor granted write access has exclusive access to the cache entry up to the point at which it marks it as valid. once the cache entry has been "validated", other descriptors with read...
nsIClassInfo
read only. classid nscidptr a classid through which an instance of this class can be created, or null. 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(). read only. classidnoalloc nscid a classid thr...
...be accessed as a service using nsiservicemanager.getservicebycontractid(). read only. flags pruint32 specifies various binary properties of this class. possible values for this attribute include a bit-wise combination of the constants read only. implementationlanguage obsolete since gecko 40 pruint32 the language type in which this class is implemented. see nsiprogramminglanguage.constants for a list of possible values. read only. constants bitflags for 'flags' attribute. constant value description singleton 1 << 0 the class is a singleton that must be accessed via nsiservicemanager. threadsafe 1 << 1 the class may be accessed by any thread. main_thread_only 1 << 2 the class may only be accessed...
...se with nsgenericfactory and can be set in nsmodulecomponentinfo::mflags. it has no meaning when returned from the flags attribute of a nsiclassinfo implementation. obsolete since gecko 2.0 methods gethelperforlanguage() get a language mapping specific helper object that may assist in using objects of this class in a specific lanaguage. for example, if asked for the helper for nsiprogramminglanguage::javascript this might return an object that can be nsisupports.queryinterface()'d into the nsixpcscriptable interface to assist xpconnect in supplying javascript specific behavior to callers of the instance object. nsisupports gethelperforlanguage( in pruint32 language ); parameters language this parameter selects the language mapping specific helper object to be returned. nsip...
...age::javascript this might return an object that can be nsisupports.queryinterface()'d into the nsixpcscriptable interface to assist xpconnect in supplying javascript specific behavior to callers of the instance object. nsisupports gethelperforlanguage( in pruint32 language ); parameters language this parameter selects the language mapping specific helper object to be returned. nsiprogramminglanguage defines language identifiers that may be passed for this parameter. return value should return null if no helper available for given language. getinterfaces() this method returns an ordered list of interfaces iids that instances of the class promise to implement. note that nsisupports is an implicit member of the implemented set of interfaces and need not be included. if this meth...
nsIHttpHeaderVisitor
headervisitor.idlscriptable this interface is used to view http request and response headers. inherits from: nsisupports last changed in gecko 1.7 method overview void visitheader(in acstring aheader, in acstring avalue); methods visitheader() called by the nsihttpchannel implementation when visiting request and response headers. this method can throw an exception to terminate enumeration of the channel's headers. void visitheader( in acstring aheader, in acstring avalue ); parameters aheader a string containing the key for a header such as "content-type" avalue the header's value field such as "text/html". multiple values are separated by a comma. example this example shows how to detect flash content. it implements the nsihttpheadervisitor interfac...
... aheader a string containing the key for a header such as "content-type" avalue the header's value field such as "text/html". multiple values are separated by a comma. example this example shows how to detect flash content. it implements the nsihttpheadervisitor interface in javascript and uses it to evaluate the mime type of a http response. this is done by subscribing to the http-on-examine-response and http-on-examine-cached-response observers. when the observer fires, the visitor interface is used to walk through the response headers and evaluate the mime type. mynsihttpheadervisitor = function ( ) { this._isflash = false; }; mynsihttpheadervisitor.prototype.visitheader = function ( aheader, avalue ) { if ( aheader.indexof( "content-type" ) !== -1 ) { ...
...; subject.cancel( this.aborted ); alert( "found flash!" ); //handle flash file here } } }; myhttprequestobserver.prototype.register = function ( ) { var observerservice = components.classes[ "@mozilla.org/observer-service;1" ].getservice( components.interfaces.nsiobserverservice ); observerservice.addobserver(this, "http-on-examine-response", false); observerservice.addobserver(this, "http-on-examine-cached-response", false); }; myhttprequestobserver.prototype.unregister = function ( ) { var observerservice = components.classes[ "@mozilla.org/observer-service;1" ].getservice( components.interfaces.nsiobserverservice ); observerservice.removeobserver( this, "http-on-examine-response" ); obse...
...addobserver(this, "http-on-examine-cached-response", false); }; myhttprequestobserver.prototype.unregister = function ( ) { var observerservice = components.classes[ "@mozilla.org/observer-service;1" ].getservice( components.interfaces.nsiobserverservice ); observerservice.removeobserver( this, "http-on-examine-response" ); observerservice.removeobserver(this, "http-on-examine-cached-response"); }; see also nsihttpchannel ...
nsIInputStream
in addition to the number of bytes available in the stream, this method also informs the caller of the current status of the stream. a stream that is closed will throw an exception when this method is called. that enables the caller to know the condition of the stream before attempting to read from it. if a stream is at end-of-file, but not closed, then ...
...osed will throw an exception when this method is called. that enables the caller to know the condition of the stream before attempting to read from it. if a stream is at end-of-file, but not closed, then this method returns 0 bytes available. note: some nsiinputstream implementations automatically close() when end-of-file is reached; others do not. note: this method should not be used to determine the total size of a stream, even if the stream corresponds to a local file. moreover, since a stream may make available more than 2^32 bytes of data, this method is incapable of expressing the entire size of the underlying data source. unsigned long available(); parameters none. return value number of bytes currently available in the stream, or pr_uint32_max if the size of the stream excee...
.... acount the size of the buffer, or the maximum number of bytes to copy from the stream. return value this method returns the number of bytes copied from the stream (may be less than acount). it returns 0 to indicate end-of-file. exceptions thrown <other-error> on failure. ns_base_stream_would_block indicates that reading from the input stream would block the calling thread for indeterminate amount of time. this exception may only be thrown if isnonblocking() returns true. native code only!readsegments this method provides direct access to the stream's internal buffer. note: a nsiinputstream is not required to implement this method. in some contexts, readsegments may be guaranteed to be implemented, but in general it is not. this method serves as an optimization. unsigned lon...
...turn value the number of bytes read from the stream (may be less than acount). it returns 0 to indicate end-of-file. exceptions thrown <other-error> on failure. ns_error_not_implemented indicates that the stream does not have an internal buffer that can be accessed directly. ns_base_stream_would_block indicates that reading from the input stream would block the calling thread for indeterminate amount of time. this exception may only be thrown if isnonblocking() returns true. example consume all data from an input stream using read(). nsresult consumestream(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...
nsIMsgFolder
nsigned long readonly deletable boolean readonly: can this folder be deleted. for example, special folders cannot be deleted. displayrecipients boolean readonly: should we be displaying recipients instead of the sender. for example, in the sent folder, recipients are more relevant than the sender. manyheaderstodownload boolean readonly: used to determine if it will take a long time to download all the headers in this folder - so that we can do folder notifications synchronously instead of asynchronously. requirescleanup boolean readonly hasnewmessages boolean does this folder have new messages. firstnewmessage nsimsgdbhdr readonly: the first new message in the folder. prettiestname astring...
... requirescleanup boolean readonly hasnewmessages boolean does this folder have new messages. firstnewmessage nsimsgdbhdr readonly: the first new message in the folder. prettiestname astring readonly folderurl acstring readonly: url for this folder. showdeletedmessages boolean readonly server nsimsgincomingserver readonly: this folder's parent server. isserver boolean readonly: is this folder the "phantom" server folder? cansubscribe boolean readonly canfilemessages boolean readonly noselect boolean readonly: this is an imap no select folder imapshared boolean readonly: this is an imap shared folder candeletemess...
...flag of all of the new messages. void clearnewmessages(); clearrequirescleanup() void clearrequirescleanup(); setflag() sets a flag on the folder. the known flags are defined in nsmsgfolderflags.h. void setflag(in unsigned long flag); clearflag() clears a flag on the folder. the known flags are defined in nsmsgfolderflags.h. void clearflag(in unsigned long flag); getflag() determines if a flag is set on the folder or not. the known flags are defined in nsmsgfolderflags.h. boolean getflag(in unsigned long flag); toggleflag() toggles a flag on the folder. the known flags are defined in nsmsgfolderflags.h. void toggleflag(in unsigned long flag); onflagchange() called to notify the database and/or listeners of a change of flag. void onflagchange(in unsigned long fla...
... boolean isancestorof(in nsimsgfolder folder); containschildnamed() looks in immediate children of this folder for the given name. boolean containschildnamed(in astring name); getchildnamed() return the child folder which the specified name. nsimsgfolder getchildnamed(in astring aname); findsubfolder() finds the sub folder with...
nsIOutputStream
re, in unsigned long acount); native code only! methods close() close the stream. forces the output stream to flush() any buffered data. note: this method may be called more than once, but subsequent calls are ignored. void close(); parameters none. exceptions thrown ns_base_stream_would_block indicates that closing the output stream would block the calling thread for an indeterminate amount of time. this exception may only be thrown if isnonblocking() returns true. flush() this method may be called to instruct the output stream to write out the contents of any internal buffers to a low-level data sink, such as a file on disk. however, the flush method may simply do nothing depending on the implementation of the output stream. void flush(); parameters none. exceptio...
...nstruct the output stream to write out the contents of any internal buffers to a low-level data sink, such as a file on disk. however, the flush method may simply do nothing depending on the implementation of the output stream. void flush(); parameters none. exceptions thrown ns_base_stream_would_block indicates that flushing the output stream would block the calling thread for an indeterminate amount of time. this exception may only be thrown if isnonblocking() returns true. isnonblocking() note: writing to a blocking output stream will block the calling thread until all given data can be consumed by the stream. note: a non-blocking output stream may implement nsiasyncoutputstream to provide consumers with a way to wait for the stream to accept more data once its write() method ...
...ng acount ); parameters afromstream an nsiinputstream containing the data to be written. acount the maximum number of bytes to write to the stream. return value this method returns the number of bytes written to the stream (may be less than acount). exceptions thrown ns_base_stream_would_block indicates that writing to the output stream would block the calling thread for an indeterminate amount of time. this exception may only be thrown if isnonblocking() returns true. ns_error_not_implemented indicates that the stream does not implement this method. typically, output streams that do not have an internal buffer will not implement this method since such an implementation would require an intermediate buffer unless afromstream supported nsiinputstream.readsegments(), but that ...
...ils on this function. aclosure a parameter that is passed to areader each time it is called. acount the maximum number of bytes to write to the stream. return value this method returns the number of bytes written to the stream (may be less than acount). exceptions thrown ns_base_stream_would_block indicates that writing to the output stream would block the calling thread for an indeterminate amount of time. this exception may only be thrown if isnonblocking() returns true. ns_error_not_implemented indicates that the stream does not have an internal buffer that can be written to directly. example writesegments() example // copy data from a string to a stream static ns_method copysegment(nsiinputstream* astream, void* aclosure, ...
nsIProcess
cko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) initializes the nsiprocess to represent an existing process, given that process's id. gecko 1.9.1 note this method is no longer implemented as of gecko 1.9.1, and is removed entirely in gecko 1.9.2. void initwithpid( in unsigned long pid ); parameters pid the process id to begin to represent. kill() immediately terminates the process represented by the nsiprocess object. this only works if the process was run without blocking enabled. gecko 1.9.1 note prior to gecko 1.9.1 (firefox 3.5), this method did not work on windows or mac os x. now it does. void kill(); parameters none. run() starts executing the process. gecko 1.9.1 note prior to gecko 1.9.1 (firefox 3.5), this method returned the pr...
... parameters none. run() starts executing the process. gecko 1.9.1 note prior to gecko 1.9.1 (firefox 3.5), this method returned the process id of the newly executing process. it no longer returns a value. void run( in boolean blocking, [array, size_is(count)] in string args, in unsigned long count ); parameters blocking if true, this method will block until the process terminates; if false, the method returns immediately. args an array of count arguments, using the native character set, to be passed to the executable on its command line. count the number of arguments in the args array. runasync() asynchronously runs the process with which the object was initialized, optionally calling an observer when the process finishes running. void runasync( [array, size...
...s-failed" as the topic. the observer will be notified on the main thread. holdweak optional if true, a weak reference is used to hold the observer. runw() executes the file this object was initialized with. void runw( in boolean blocking, [array, size_is(count)] in wstring args, in unsigned long count ); parameters blocking if true, this method will block until the process terminates; if false, the method returns immediately. args an array of count arguments, using utf-16, to be passed to the executable on its command line. count the number of arguments in the args array. runwasync() asynchronously runs the process with which the object was initialized, optionally calling an observer when the process finishes running. void runwasync( [array, size_is(count)] in w...
...// second and third params are used to pass command-line arguments // to the process. var args = ["argument1", "argument2"]; process.run(false, args, args.length); see also nsifile nsiprocess2 obsolete since gecko 1.9.2 ...
nsIScriptableInputStream
4 / thunderbird 3.3 / seamonkey 2.1) method overview unsigned long available(); void close(); void init(in nsiinputstream ainputstream); string read(in unsigned long acount); acstring readbytes(in unsigned long acount); methods available() return the number of bytes currently available in the stream. note: this method should not be used to determine the total size of a stream, even if the stream corresponds to a local file. moreover, since a stream may make available more than 2^32 bytes of data, this method is incapable of expressing the entire size of the underlying data source. unsigned long available(); parameters none. return value the number of bytes. exceptions thrown ns_base_stream_closed if called after the stream has bee...
...stream ); parameters ainputstream the nsiinputstream to be wrapped. read() read data from the stream. warning: if the data contains a null byte, then this method will return a truncated string. note: it is also important to consider how a language bindings may interpret the string data type. in particular, some bindings may convert the byte values into unicode code points, by assuming the byte values are encoded as iso-latin-1. this is the case for the javascript bindings. string read( in unsigned long acount ); parameters acount the maximum number of bytes to read from the stream. return value the data read as a string, which will be an empty string if the stream is at eof. exceptions thrown ns_error_not_initialized if init() was not called. ns_base...
...s to read from the stream. return value the data read as a string, which will be an empty string if the stream is at eof. exceptions thrown ns_error_not_initialized if init() was not called. ns_base_stream_closed if called after the stream has been closed. ns_base_stream_would_block indicates that reading from the input stream would block the calling thread for an indeterminate amount of time. this exception may only be thrown if nsiinputstream.isnonblocking() returns true. readbytes() read data from the stream, including null bytes. acstring readbytes( in unsigned long acount ); parameters acount the maximum number of bytes to read. return value the data from the stream, which will be an empty string if eof has been reached. exceptions thrown ns_e...
...to scratchpad. var {classes: cc, interfaces: ci, results: cr, constructor: cc, utils: cu } = components; var scriptableinputstream = cc("@mozilla.org/scriptableinputstream;1", "nsiscriptableinputstream", "init"); let entry = this.getentry(name); let stream = new scriptableinputstream(this.getinputstream(name)); try { // use readbytes to get binary data, read to read a (null-terminated) string let contents = stream.readbytes(entry.realsize); } finally { stream.close(); } example usage in ondataavailable remember: the nsiscriptableinputstream has a contract where `init` should only be called once, and should always be closed. var scriptableinputstream = cc("@mozilla.org/scriptableinputstream;1", "nsiscriptableinputstream", "init"); var blah = { d...
nsIXULTemplateBuilder
itions that cause a rule to be either accepted or rejected. the condition syntax allows for common conditional handling; additional filtering may be applied by adding a custom filter to a rule with the builder's addrulefilter() method. if a result passes a rule's conditions, this is considered a match, and the content within the rule's <action> body is inserted as a sibling of the <template>, assuming the template builder creates real dom content. only one rule will match a result. for a tree builder, for example, the content within the action body is used to create the tree rows instead. a matching result must have its rulematched() method called. when a result no longer matches, the result's hasbeenremoved() method must be called. optionally, the rule may have a <bindings> section which may...
...o the query processor via its addbinding() method. the bindings are evaluated after a rule has matched. templates may generate content recursively, using the previous iteration's results as reference point to invoke the same queries. since the reference point is different, different output will typically be generated. the reference point nsixultemplateresult object for the first iteration is determined by calling the query processor's translateref() method using the value of the root node's ref attribute. this object may be retrieved later via the builder's rootresult property. for convenience, each reference point as well as all results implement the nsixultemplateresult interface, allowing the result objects from each iteration to be used directly as the reference points for the next iterat...
...atasource readonly: the composite datasource that the template builder observes and uses to create content. this is used only for rdf queries and is maintained for backwards compatibility. it will be the same object as the datasource property. for non-rdf queries, it will always be null. rootresult nsixultemplateresult readonly: the virtual result representing the starting reference point, determined by calling the query processor's translateref method with the root node's ref attribute as an argument. queryprocessor nsixultemplatequeryprocessor [noscript] readonly: the query processor used to generate results. methods rebuild() force the template builder to rebuild its content. all existing content will be removed first. the query processor's done() method will be invoked during clean...
...eters aid the id to return the result for return value the result for the given id. getresultforcontent() retrieves the result corresponding to a generated element, or null is there isn't one. nsixultemplateresult getresultforcontent( in nsidomelement aelement ); parameters acontent element to result the result of return value the result for the specified element. hasgeneratedcontent() determines whether or not the node has content generated for it. this method is intended to be called only by the rdf query processor. if atag is set, the content must have a tag name that matches atag. atag may be ignored for builders that don't generate real dom content. boolean hasgeneratedcontent( in nsirdfresource anode, in nsiatom atag ); parameters anode node to check. atag tag that must match...
nsIXULWindow
olean indicates if this window is instrinsically sized. primarycontentshell nsidocshelltreeitem the primary content shell. note: that this is a docshell tree item and therefore can not be assured of what object it is. it could be an editor, a docshell, or a browser object. or down the road any other object that supports being a docshelltreeitem query accordingly to determine the capabilities. read only. xulbrowserwindow nsixulbrowserwindow provides access to the xulbrowserwindow object offering a way for the browser to update the user interface of the enclosing xul window. zlevel unsigned long one of the z level constants below. on some platforms, windows with a higher zlevel will be kept above windows with a lower zlevel. const...
...he child window being added. native code only!applychromeflags back-door method to force application of chrome flags at a particular time. do not call this unless you know what you are doing! in particular, calling this when this xul window does not yet have a document in its docshell could cause problems. void applychromeflags(); parameters none. assumechromeflagsarefrozen() begin assuming chromeflags do not change hereafter, and assert if they do change. the state change is one-way and idempotent. void assumechromeflagsarefrozen(); parameters none. center() move the window to a centered position. void center( in nsixulwindow arelative, in boolean ascreen, in boolean aalert ); parameters arelative if not null, the window relative to which the window is moved. se...
...ue to move the window to an alert position, generally centered horizontally and 1/3 down from the top. createnewwindow() create a new window. nsixulwindow createnewwindow( in print32 achromeflags, in nsiappshell aappshell ); parameters achromeflags see nsiwebbrowserchrome. aappshell the app shell passed to nsiappshellservice's createtoplevelwindow method. return value the newly minted window. in the case of a content window, the function creates a browser window and waits for it to load. you can then load a document into the window's primary content shell. getcontentshellbyid() the content shell specified by the supplied id. note: that this is a docshell tree item and therefore can not be assured of what object it is. it could be an editor, a docshell, or a browser objec...
... load. you can then load a document into the window's primary content shell. getcontentshellbyid() the content shell specified by the supplied id. note: that this is a docshell tree item and therefore can not be assured of what object it is. it could be an editor, a docshell, or a browser object. or down the road any other object that supports being a docshelltreeitem query accordingly to determine the capabilities. nsidocshelltreeitem getcontentshellbyid( in wstring id ); parameters id the id of the content shell, which is the same as the "type" attribute on the containing frame element. return value the tree item corresponding to the given id, if any. removechildwindow() tell this window that it has lost a child xul window. note that xul windows do not currently track child...
nsIZipReader
string such as '*~*z*~*y*' is not a valid pattern. (foo|bar) will match either the pattern foo or the pattern bar. neither of the patterns foo or bar may use the 'pat~pat2' syntax described immediately above. \ will escape a special character. escaping is required for all special characters unless otherwise specified. all other characters match case-sensitively. an apattern not conforming to this syntax has undefined behavior. return value the nsiutf8stringenumerator containing the matching entry names. exceptions thrown ns_error_illegal_value on many but not all invalid apattern values. getcertificateprincipal() returns an object describing the entity which signed an entry. parsemanifest must be called first. if aentryname is an entry in the jar, getinputstream() mu...
... parameters zipfile the zip file to open. example demonstrating this function: list contents of xpi and read file contents openinner() opens a zip file inside a zip file for reading. void openinner( in nsizipreader zipreader, in autf8string zipentry ); parameters zipreader the zipreader object. zipentry the zip entry. test() tests the integrity of the archive by performing a crc check on each item expanded into memory. if an entry is specified the integrity of only that item is tested. if null (javascript) or emptycstring() (c++) is passed in the integrity of all items in the archive are tested. void test( in autf8string aentryname ); parameters aentryname the single entity to check or null for checking all entries in the archive. examples list content...
...eds the extension to be xpi. change "portabletester@jetpack.xpi" to the name of a xpi file in your extensions folder. then you can copy and paste this code in scratchpad to run it. ...
... * "entry" xpcwrappednative_nohelper { queryinterface: queryinterface(), compression: getter, size: getter, realsize: getter, crc32: getter, isdirectory: getter, lastmodifiedtime: getter, issynthetic: getter, permissions: getter, compression: 8 } scratchpad/1:19 */ if (!entry.isdirectory) { var inputstream = zr.getinputstream(entrypointer); reusablestreaminstance.init(inputstream); var filecontents = reusablestreaminstance.read(entry.realsize); console.log('contenst of file=', filecontents); } else { console.log('is directory, no stream to read'); } } } catch (ex) { console.warn('exception occured = ', ex); if (ex.name == 'ns_error_file_not_found') { services.ww.active...
Performance
lem is that these requirements make some operations, especially commits, very slow. for each commit, sqlite does two disk syncs among many other file operations (see the "atomic commit" section of http://www.sqlite.org/php2004/slides-all.html for more information on how this works). these disk syncs are very slow and limit the speed of a commit to the rotational speed of the mechanical disk. vacuuming and zero-fill sqlite has a vacuum command to compress unused space from the database. sqlite works like a memory manager or a file system. when data is deleted, the associated bytes are marked as free but are not removed from the file. this means that the file will not shrink, and some data may still be visible in the file. the way to work around this is to run the vacuum command to remove this ...
...ill sqlite has a vacuum command to compress unused space from the database. sqlite works like a memory manager or a file system. when data is deleted, the associated bytes are marked as free but are not removed from the file. this means that the file will not shrink, and some data may still be visible in the file. the way to work around this is to run the vacuum command to remove this space. vacuuming is very slow. the vacuum command is essentially the same as the command line sqlite3 olddb .dump | sqlite3 newdb; mv newdb olddb. on some networked drives, vacuuming a 10mb database has been timed at over one minute. therefore, you should avoid vacuuming whenever possible. some items in databases are privacy sensitive, such as deleted history items. users have the expectation that deleting items...
...zero-filling can have significant performance overhead in some situations. for example, the history service used to delete many database items at shutdown when expiring old history items. this operation is not necessarily slow, but writing 0s to disk in an "aci" database is still slow. ...
...tory service used to delete many database items at shutdown when expiring old history items. this operation is not necessarily slow, but writing 0s to disk in an "aci" database is still slow. this made shutdown very slow because the asyncio thread would block shutdown (bug 328598). shutdown times of more than 30 seconds were seen. as a result, this bug introduced incremental history expiration eliminating the need to write many 0s to disk on shutdown. unfortunately, this operation cannot be controlled on a per-transaction or per-connection basis. some operations will benefit, while others will be hurt. ...
MailNews fakeserver
be used in manual qa tests. basic structure fakeserver is situated entirely under mailnews/test/fakeserver/. it is comprised of three major components: a daemon, a handler, and the server itself. the server itself is found in mailnews/test/fakeserver/maild.js and was largely based off of the httpd fakeserver from network code. it utilizes utf-8 as its transport mechanism and is capable of performing proper pipelining of commands. the other two components are specific to the protocol type and found under similar files in the same directory (e.g., smtpd.js). a daemon is information about the server that can be manipulated. an example of such a manipulation is adding a folder or adding messages. daemons should usually persist for the entirety of the test. the handler is the glue between the se...
...handlers = [ /* some set of handlers */ ]; for (var handler in handlers) { // this sets up the fake server var server = new nsmailserver(new handler(daemon)); // port to use. i tend to like using 1024 + default port number myself. // probably best to include as a constant somewhere. also, use something // larger than 1024 for best results. ...
...) is generally a good way to do so server.resettest(); // set up second test server.performtest(); transaction = server.playtransaction(); // finished with tests server.stop(); } currently, fakeserver provides no means to keep a persistent connection past a test, requiring connections to be closed, possibly forcibly. alternatively, one can wait for the timeout, which occurs after 3 minutes, so not closing connections would make the tests take unbearably long. the server provides the following api to xpcshell tests: <caption> nsmailserver xpcshell api </caption> name arguments returns description performtest none nothing runs until the test is forcibly aborted or stopped normally isstopped none if the server is stopped helper for performtest istestfinished none if the t...
... getarticle message id newsarticle object pretty self-explanatory newsarticle api name arguments returns notes [constructor] text (as a string) n/a initializes all fields headers (property) map of header (lower-case) -> value body (property) text of body messageid (property) message id fulltext...
Mail event system
ng 4 messages. because the number of messages in the folder have increased, this change in total message count needs to be broadcast to the world. the folder calls notifyintpropertychanged on itself with the atom that represents "totalmessages": this->notifyintpropertychanged(ktotalmessagesatom, 4, 5);. notifypropertychanged broadcasts this event to each its nsifolderlisteners by calling onitemintpropertychanged on each listener: listener->onintpropertychanged(this, ktotalmessagesatom, 4, 5); the dialog is one of these folder-specific listeners. in its implementation of onintpropertychanged, it uses this information to update the message count in the dialog. notifypropertychanged then broadcasts this event to the mail session: mailsession->onintpropertychanged(this, ktotal...
... message count has changed. rdf handles the notification by updating the message counts in the folder pane. ...
...rdf handles the notification by updating the message counts in the folder pane. ...
...nteger test property fired on folder " + folder.prettyname + " with values " + oldvalue + " and " + newvalue + "\n"); } // set up the folder listener to point to the above function var folderlistener = { onitemadded: function(parent, item, viewstring) {}, onitemremoved: function(parent, item, viewstring) {}, onitempropertychanged: function(parent, item, viewstring) {}, onitemintpropertychanged: myonintpropertychanged, onitemboolpropertychanged: function(item, property, oldvalue, newvalue) {}, onitemunicharpropertychanged: function(item, property, oldvalue, newvalue) {}, onitempropertyflagchanged: function(item, property, oldflag, newflag) {}, onitemevent: function(item, event) = {}, onfolderloaded: function(afolder) = {} ondeleteormovemessagescompleted: func...
Building a Thunderbird extension 3: install manifest
the first portion is the short name of the extension and must be in lowercase; the last portion is a...
...the first portion is the short name of the extension and must be in lowercase; the last portion is a two-part period-de...
...ever, be a unique value so that it does not conflict with other extensions. <em:name>my first extension</em:name>: the extension name is displayed in the thunderbird add-on manager. <em:version>1.0</em:version>: this is the version number of your extension. it must be updated each time you release a new version of your extension. it is not the thunderbird version number (which is stored in the minversion and maxversion fields). <em:creator>jenzed</em:creator>: this optional value is used to store the extension author's name. <em:id>{3550f703-e582-4d05-9a08-453d09bdfdc6}</em:id>: this element contains the version id of the application that this add on is developed for. it is defined by mozilla. a list of valid application ids can be found here. normally the id does not change and is alway...
...tor>: this optional value is used to store the extension author's name. <em:id>{3550f703-e582-4d05-9a08-453d09bdfdc6}</em:id>: this element contains the version id of the application that this add on is developed for. it is defined by mozilla. a list of valid application ids can be found here. normally the id does not change and is always the same even for different versions of thunderbird. <em:minversion>1.5</em:minversion>: this element indicates the earliest version of thunderbird for which the extension is intended to work. do not use a wildcard (such as "*"). see valid application versions for a list of the supported version numbers and formats. <em:maxversion>5.0.*</em:maxversion>: this element indicates the most recent version of thunderbird for which the extension is intended to wo...
Demo Addon
ted in demo1.html in the content folder. it lists all your email accounts with their account type - either pop3 or imap - and the associated email addresses. let data = []; for each (let account in fixiterator(mailservices.accounts.accounts, ci.nsimsgaccount)) { let info = { server: null, type: null, emails: [], name: null, }; let server = account.incomingserver; if (server) { info.server = server.prettyname; info.type = server.type; } for each (let id in fixiterator(account.identities, ci.nsimsgidentity)) { // we're only interested in identities that have a real email. if (id.email) info.emails.push(id.email); } data.push(info); } first, we use fixiterator() here to get all account...
...; } for each (let id in fixiterator(account.identities, ci.nsimsgidentity)) { // we're only interested in identities that have a real email. if (id.email) info.emails.push(id.email); } data.push(info); } first, we use fixiterator() here to get all accounts in your profile. each account is a nsimsgaccount. to get the the server name, we access the incomingserver property of our account, which is a nsimsgincomingserver object. from this, we get its name and type. because an account can have multiple identities of type nsimsgidentity and therefore multiple associated email addresses, with use fixiterator() again to go over all identities and get every email address. demo 2 - find the inbox this demo shows various information: it lists all folders...
...ator() again to go over all identities and get every email address. demo 2 - find the inbox this demo shows various information: it lists all folders of an account (in this case the first one) and marks the inbox folder with a *. furthermore, it shows some messages in the inbox and lists a random attachment. we start with listing all folders and marking the inbox: let server = accounts[0].incomingserver; let folder = server.rootfolder; // ... let inbox; let print = function (indent, folder) { let isinbox = folder.getflag(ci.nsmsgfolderflags.inbox); if (isinbox) inbox = folder; str += indent + folder.prettiestname + (isinbox ? " *" : "") + "\n"; if (folder.hassubfolders) for each (let folder in fixiterator(folder.subfolders, ci.nsimsgfolder)) pri...
...beginning with the rootfolder, with folder.getflag(ci.nsmsgfolderflags.inbox) we check whether the folder is the inbox. then we store the folder name in a string to display it later on the screen and mark it with an * if it is the inbox. afterwards, we check every folder for subfolders. we then go into each subfolder and start over. to list some messages of th...
Zombie compartments
when are compartments created? any compartments with the following forms are created by firefox for its own internal use, and can usually be ignored when looking for zombie compartments. js-compartment([system principal], 0x7f10f1250000) compartment(ato...
...a compartment whose name doesn't match the only page open from that origin. this can be confusing at first, so be ready for it. when are compartments destroyed? compartments are destroyed when they are garbage collected. this happens some time after the last reference to them disappears. this means there can be a delay between a page being closed and its compartments disappearing. explicitly minimizing the memory (a couple of times), i.e. running the garbage collector, with the corresponding about:memory button will help. zombie compartments sometimes, due to bugs in firefox, the add-on sdk and/or add-ons, compartments are created that are never destroyed. these are a particular kind of memory leak, and they cause firefox's memory usage to increase gradually over time, slowing it down...
... a compartment for www.foo.com, but you closed your last www.foo.com tab a while ago, there's a good chance you're seeing a zombie compartment. follow these steps to make a more conclusive diagnosis. restart the browser. open the page that you think might cause a zombie compartment. open about:memory in another tab to confirm that the relevant compartment is present. close the first page. minimize memory usage and remeasure in about:memory. it might be worth refreshing multiple times just to be sure. if the compartment is still present in about:memory, that's very suspicious. you could try waiting 20 minutes or so, then reload about:memory again. some zombie compartments stick around for a limited time before disappearing, others are immortal, and it's useful to know which is whic...
...hat remembers passwords, visit a site that requires a password; for an add-on that performs an operation involving a specific page element such as an image or a chunk of text, perform that operation. the more you exercise the add-on, the more thorough the testing will be, but in practice a lot of problems show up quickly. open about:memory and close all other pages. return to about:memory and minimize memory and remeasure, multiple times if necessary. if only system compartments are present, and there are no ghost windows, congratulations! that's a good sign that the add-on doesn't cause zombie compartments. 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 7005...
Using Objective-C from js-ctypes
ctypes.void_t, id, sel, "..."); the first two cases are both integers (including pointer), so we can cast them after receiving the value in pointer type. the third case is void, but we're going to use the same function internally, the only difference is if we need to ignore the returned value or not. in fact, here we can use the same definition in all cases, as a minimal case. let objc_msgsend = lib.declare("objc_msgsend", ctypes.default_abi, id, id, sel, "..."); declaring a dedicated function for bool might be more efficient, directly getting the primitive value. let objc_msgsend = lib.declare("objc_msgsend", ctypes.default_abi, id, id, sel, "..."); let objc_msgsend_bool = lib.declare("objc_ms...
...we should always pass it a cdata instance, other than this first and second argument, to declare each argument type. ...
... wait until start speaking. while (!objc_msgsend_bool(synth, isspeaking)) {} // wait while speaking. while (objc_msgsend_bool(synth, isspeaking)) {} let release = sel_registername("release"); objc_msgsend(synth, release); objc_msgsend(text, release); lib.close(); creating objective-c blocks objective-c api calls sometimes require you to pass in a block. reading the apple developer :: programming with objective-c - working with blocks you can learn more about blocks. to create a block with js-ctypes, use the function: function createblock(afunctypeptr) { /** * creates a c block instance from a js function. * 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. */ // apple docs :: wor...
...js-ctypes, use the function: function createblock(afunctypeptr) { /** * creates a c block instance from a js function. * 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. */ // apple docs :: working with blocks - https://developer.apple.com/library/ios/documentation/cocoa/conceptual/programmingwithobjectivec/workingwithblocks/workingwithblocks.html var _nsconcreteglobalblock = ctypes.open(ctypes.libraryname('objc')).declare('_nsconcreteglobalblock', ctypes.voidptr_t); // //github.com/realityripple/uxp/blob/master/js/src/ctypes/library.cpp?offset=0#271 /** * the "block descriptor" is a static singleton struct. probably used in more * complex block scenarios involving actual clo...
Declaring types
presented as a string and a ctype object, respectively. the format, then, looks like this: [ { field1: type1 }, { field2: type2 }, ... ...
...find other types see here: predefined types - primitive types. you can then declare and use a function that uses this structure, like this: // declare the libc asctime() function, which returns a char * and accepts a pointer to a tm structure. const asctime = lib.declare("asctime", ctypes.default_abi, ctypes.char.ptr, struct_tm.ptr); var thetime = new struct_tm; thetime.tm_hour = 3; thetime.tm_min = 15; ... var timestr = asctime(thetime.address()); // pass a pointer to the tm struct var jsstring = timestr.readstring(); // convert the c string to javascript the last line converts the c string returned by the libc asctime() function into a javascript string by calling the cdata readstring() method. for another example see here: getcursorpos opaque structures an opaque struc...
...ne technique: var struct = ctypes.structtype('struct'); struct.define([{ next: struct.ptr }]); arrays to declare a new array type, you use the ctypes.arraytype() method.when declaring a new array type, you provide a ctype indicating the type of each element in the array as well as an optional array length. you may declare your array either with a specific number of elements, or with no predetermined size. this is permitted since c allows it, for the widest possible compatibility. declaring an array type with unspecified length to declare a new array type without specifying a length, you simply pass in the ctype specifying the element type when calling ctypes.arraytype(). for example, to create a type for an array of c standard i/o file pointers (perhaps for tracking a number of active fi...
...ructtype("userrecord", [{"name": ctypes.char.ptr}, {"id": ctypes.int32}]); const userrecordptr = new ctypes.pointertype(userrecord); in this example, a new userrecord type is defined, along with a new pointer type that can be used to reference it. the equivalent c code looks like this: typedef struct userrecord { char *name; int id; // assuming int is 32-bit here } userrecord; typedef userrecordptr *userrecord; ...
CData
javascript expression should return a copy of the original cdata object: eval(dataobject.tosource()); tostring() returns a string identifying the data. string tostring(); parameters none. return value a string identifying the data. methods available on string objects these methods must be called on objects that are arrays or pointers to 8-bit or 16-bit character or integer types, terminated by a null character. readstring() converts a character array to a javascript string. 8-bit strings are assumed to be encoded as utf-8. if the 8-bit string contains invalid encoded character, a typeerror exception is thrown. string readstring(); parameters none. return value a new string object that is a copy of the original string contents. readstringreplacemalformed() converts a ...
... readjscharstring = function() { var assumption_max_len = known_len ? ...
... code of 0 // can test this by reading a string like this: "_scratchpad/entehandle.js at master · noitidart/_scratchpad mdnfirefox" at js array position 36 (so 37 if count from 1), we see 183, and at 77 we see char code of 0 if casted to unsigned_char, if casted to char we see -73 at pos 36 but pos 77 still 0, if casted to jschar we see chineese characters in all spots expect spaces even null terminator is a chineese character console.info('ptrasarr.length:', ptrasarr.length); //console.log('debug-msg :: datacasted:', datacasted, uneval(datacasted), datacasted.tostring()); var charcode = []; var fromcharcode = [] for (var i=0; i<ptrasarr.length; i++) { //if known_len is correct, then will not hit null terminator so like in example of "_scratchpad/enteh...
...hit null terminator so like in example of "_scratchpad/entehandle.js at master · noitidart/_scratchpad mdnfirefox" if you pass length of 77, then null term will not get hit by this loop as null term is at pos 77 and we go till `< known_len` var thisunsignedcharcode = ptrasarr.addressofelement(i).contents; if (thisunsignedcharcode == 0) { // reached null terminator, break console.log('reached null terminator, at pos: ', i); break; } charcode.push(thisunsignedcharcode); fromcharcode.push(string.fromcharcode(thisunsignedcharcode)); } console.info('charcode:', charcode); console.info('fromcharcode:', fromcharcode); var char16_val = fromcharcode.join(''); ...
Mozilla
vide important guides and references to ensuring the code you write is secure, including both design recommendations and testing guidelines. bugzilla bugzilla.mozilla.org (often abbreviated b.m.o) is mozilla.org's bug-tracking system, a database for recording bugs and enhancement requests for firefox, thunderbird, seamonkey, camino, and other mozilla.org projects. building mozilla in this article, we list documents that will guide you in building firefox or other projects based upon mozilla code. building spidermonkey with ubsan 1. compile a recent version of llvm & clang. c++ portability guide this document has migrated to using c++ in mozilla c...
...kref.html hacking with bonsai bonsai was originally created to solve the problem of tree instability. the original navigator code base had large sections that were shared across multiple platforms. many times, code checked in would compile or run on a handful of platforms. also, with as many as 100 engineers, it was very difficult to determine what happened in the tree that caused the instability. bonsai was created to solve these problems. how mozilla determines mime types all data handling in mozilla is based on the mime type of the content. this means that every time an uri is loaded, mozilla must find out its mime type. the several ways how this happens are described in this document.
...efox itself, such as a deadlock or infinite loop, or it may be caused by 3rd-party software such as a firefox extension, antivirus software, or even malware or a virus on your computer. http cache httpd.js ime handling guide this document explains how gecko handles ime. implementing download resuming this document describes how an embedder or other gecko/necko-using application can implement download resuming. implementing queryinterface this document describes the right way to write queryinterface(). infallible memory allocation there's ongoing work to implement infallible memory allocators. these are memory allocation rout...
...inue to excel at) testing mozilla code. the mozilla platform the mozilla project encompasses several technologies that, together, comprise the mozilla platform. these links will direct you to documentation about each of these, as well as how to use the mozilla platform to build your own projects. the rust programming language rust is a new open-source systems programming language created by mozilla and a community of volunteers, designed to help developers create fast, secure applications which take full advantage of the powerful features of modern multi-core processors. it prevents segmentation faults and guarantees thread safety, all with an easy-to-learn syntax. ...
Debugger.Memory - Firefox Developer Tools
otherwise, null is returned. known values include the following: “gc mode” “malloc bytes trigger” “allocation trigger” “requested” gccyclenumber the gc cycle’s “number”. does not cor...
...otherwise, null is returned. ...
...rings, called atoms, are not included in censuses’ string counts. scripts spidermonkey has a complex, hybrid representation of javascript code. there are four representations kept in memory: source code. spidermonkey retains a copy of most javascript source code. compressed source code. spidermonkey compresses javascript source code, and de-compresses it on demand. heuristics determine how long to retain the uncompressed code. bytecode. this is spidermonkey’s parsed representation of javascript. bytecode can be interpreted directly, or used as input to a just-in-time compiler. source is parsed into bytecode on demand; functions that are never called are never parsed. machine code. spidermonkey includes several just-in-time compilers, each of which translates java...
... this is spidermonkey’s parsed representation of javascript. bytecode can be interpreted directly, or used as input to a just-in-time compiler. source is parsed into bytecode on demand; functions that are never called are never parsed. machine code. spidermonkey includes several just-in-time compilers, each of which translates javascript source or bytecode to machine code. heuristics determine which code to compile, and which compiler to use. machine code may be dropped in response to memory pressure, and regenerated as needed. furthermore, spidermonkey tracks which types of values have appeared in variables and object properties. this type information can be large. in a census, all the various forms of javascript code are placed in the "script" category. type information is acco...
Deprecated tools - Firefox Developer Tools
emoved. we have created this list of deprecated or removed panels. this page documents the deprecated panels and the bugs that track their removal. although these panels have been removed, you still have access to the old code, and there are alternative webextensions that you can try to get similar functionality. when we deprecate a panel, we begin by getting feedback from the community to determine the impact of removing that panel. once we have decided to remove the panel, we will provide a warning message, and finally, we will remove the panel from the codebase. you may see a warning message, as in the following image, when trying to activate a deprecated panel: in addition, if you open the panel for one of these tools, you will also see a warning message about its removal. scratc...
...hen trying to activate a deprecated panel: in addition, if you open the panel for one of these tools, you will also see a warning message about its removal. scratchpad scratchpad is deprecated as of firefox 70 (bug 1565380), and will be removed as of firefox 72 (bug 1519103). description scratchpad provided an environment for experimenting with javascript code. you can write, run, and examine the result of code that interacts with the web page. alternatives in firefox 71+, you can write multi-line javascript code in the web console editor mode, making it similar to the scratchpad. 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...
...pect the canvas element and see how frequently a given function is called. it was deprecated due to lack of use. we do not have dedicated documentation for the canvas debugger. alternatives spector.js is a webextension that can provide these features with 3d contexts. web audio editor bugzilla issue: bug 1403944 removed as of firefox 67 description the web audio editor allowed you to examine an audio context constructed in the page and provided a visualization of its graph. this gave a high-level view of its operation, and enabled you to ensure that all the nodes are connected in the way you expect. it was possible to edit the audioparam properties for each node in the graph. some non-audioparam properties, like an oscillatornode's type property, were displayed and editable as well.
...m properties, like an oscillatornode's type property, were displayed and editable as well. it was deprecated due to lack of use. more details about the web audio editor alternatives alternatives include audion and https://github.com/spite/webaudioextension web extensions. shader editor bugzilla issue: bug 1342237 removed as of firefox 67 description the shader editor allowed users to examine and edit the source of the webgl vertex and fragment shaders. it was deprecated due to low usage and maintenance costs. more details about the shader editor alternatives an alternative to this panel is this extension: https://github.com/spite/shadereditorextension, or spector.js also supports a shader editor that requires a library to use a shader reloader hook. currently only the babylon l...
Paint Flashing Tool - Firefox Developer Tools
the paint flashing tool, when activated, highlights the part of a page that the browser needs to repaint in response to some input: for example, the user moving the mouse or scrolling. with the help of this tool you can figure out whether your website is causing the browser to repaint more than it needs to. because repaints can be performance-intensive operations, eliminating unnecessary repaints can improve your website's responsiveness. repaints and responsiveness when the browser renders a web page it parses the html and css, determines how to lay it out, and then paints it to actually display the content on the screen. whenever an event happens that might change a visible part of the web page then the browser must repaint some portion of the page. for example, a repaint will be needed ...
...lay the content on the screen. whenever an event happens that might change a visible part of the web page then the browser must repaint some portion of the page. for example, a repaint will be needed if the user scrolls the page or moves the mouse pointer over an element with a :hover pseudo-class that changes the element's style. repainting can be an expensive operation, so the browser tries to minimise the amount of repainting that it needs to do. it tries to work out which parts of the screen are "damaged" and repaint only those. the browser also splits its model of the page into layers that it expects will be updated independently of each other. layers are painted independently and then composited, so a change in the appearance of one layer does not trigger a repaint in any other layers,...
... icon labeled "highlight painted area": then try using the page. after moving the mouse around and scrolling a bit, the above page looks like this: in this example, there are two main sources of repaints: moving the mouse over links makes the browser repaint them, because they have a style applied using the :hover pseudo-class scrolling makes the browser repaint the new part of the page coming into view at the bottom of the screen, and also the scrollbar at the top-right to deactivate paint flashing, click the "highlight painted area" icon in the toolbox again. example: css transitions one area where implementation choices can affect repaint efficiency is in css transitions. the example below shows two different ways to move an element using a css transition. the first way applies...
...the element. so when the element is moved, all that's changed is the relation of the two layers to each other, which is handled in composition: neither layer needs a repaint. in this case, with a simple style, the extra repaints don't make much of a difference. but if the style were computationally expensive to paint, they might. it's difficult to know what optimizations the browser will make to minimize repaints, and they are subject to change from one version to the next. so testing your website with the paint flashing tool helps ensure that it's still performing optimally. ...
Web Audio Editor - Firefox Developer Tools
notice: this tool has been deprecated and will soon be removed from firefox. for details, see deprecated tools. with the web audio api, developers create an audio context. within that context they then construct a number of audio nodes, including: nodes providing the audio source, such as an oscillator or a data buffer source nodes performing transformations such as delay and gain nodes representing the destination of the audio stream, such as the speakers each node has zero or more audioparam properties that configure its operation. for example, the gainnode has a single gain property, while the oscillatornode has frequency and detune properties. the developer connects the nodes in a graph, and the complete graph defines the behavior of the audio stream. the web audio editor ...
...esenting the destination of the audio stream, such as the speakers each node has zero or more audioparam properties that configure its operation. for example, the gainnode has a single gain property, while the oscillatornode has frequency and detune properties. the developer connects the nodes in a graph, and the complete graph defines the behavior of the audio stream. the web audio editor examines an audio context constructed in the page and provides a visualization of its graph. this gives you a high-level view of its operation, and enables you to ensure that all the nodes are connected in the way you expect. you can then examine and edit the audioparam properties for each node in the graph. some non-audioparam properties, like an oscillatornode's type property, are displayed, and you c...
...lt in firefox 32. to enable it, open the developer tool settings and check "web audio". now there should be an extra tab in the toolbox toolbar labeled "web audio". click the tab and load a page that constructs an audio context. two good demos are: the voice-change-o-matic, which can apply various effects to the microphone input and also provides a visualisation of the result the violent theremin, which changes the pitch and volume of a sine wave as you move the mouse pointer visualizing the graph the web audio editor will now display the graph for the loaded audio context. here's the graph for the violent theremin demo: you can see that it uses three nodes: an oscillatornode as the source, a gainnode to control the volume, and an gainnode as the destination. connections to audiopara...
...in another node, then the connection is shown as a dashed line between the nodes, and is labeled with the name of the audioparam: inspecting and modifying audionodes if you click on a node, it's highlighted and you get a node inspector on the right hand side. this list the values of that node's audioparam properties. for example, here's what the oscillatornode looks like: with the violent theremin demo, the frequency parameter is modified as the user moves the mouse left and right, and you can see this reflected in the node inspector. however, the value isn't updated in real time: you have to click the node again to see the updated value. if you click on a value in the node inspector you can modify it: press enter or tab and the new value takes effect immediately. bypassing nodes new i...
Web Console remoting - Firefox Developer Tools
datasize": 1024, "discardrequestbody": false }, { "from": "conn0.netevent14", "type": "networkeventupdate", "updatetype": "responsestart", "response": { "httpversion": "http/1.1", "status": "304", "statustext": "not modified", "headerssize": 194, "discardresponsebody": true } }, { "from": "conn0.netevent14", "type": "networkeventupdate", "updatetype": "eventtimings", "totaltime": 1 }, { "from": "conn0.netevent14", "type": "networkeventupdate", "updatetype": "responseheaders", "headers": 6, "headerssize": 194 }, { "from": "conn0.netevent14", "type": "networkeventupdate", "updatetype": "responsecookies", "cookies": 0 }, { "from": "conn0.netevent14", "type": "networkeventupdate", "updatetype": "responsecontent", "mimetype": "text/...
... false } the request and response content text value is most commonly sent using a longstringactor grip. for very short request/response bodies we send the raw text. starting with firefox 19: for non-text response types we send the content in base64 encoding (again, most likely a longstringactor grip). to tell the difference just check if response.content.encoding == "base64". ...
...monly sent using a longstringactor grip. for very short request/response bodies we send the raw text. starting with firefox 19: for non-text response types we send the content in base64 encoding (again, most likely a longstringactor grip). to tell the difference just check if response.content.encoding == "base64". ...
...ery short request/response bodies we send the raw text. starting with firefox 19: for non-text response types we send the content in base64 encoding (again, most likely a longstringactor grip). to tell the difference just check if response.content.encoding == "base64". ...
AudioWorkletProcessor.process - Web APIs
hey contain 128 32-bit floating-point samples for each of the inputs' channels. however, plans are already in place to revise the specification to allow the size of the audio blocks to be changed depending on circumstances (for example, if the audio hardware or cpu utilization is more efficient with larger block sizes). therefore, you must always check the size of the sample array rather than assuming a particular size. this size may even be allowed to change over time, so you mustn't look at just the first block and assume the sample buffers will always be the same size. syntax var isactivelyprocessing = audioworkletprocessor.process(inputs, outputs, parameters); parameters inputs an array of inputs connected to the node, each item of which is, in turn, an array of channels. each...
...de. the returned value lets your processor have influence over the lifetime policy of the audioworkletprocessor and the node that owns it. if the combination of the return value and the state of the node causes the browser to decide to stop the node, process() will not be called again. returning true forces the web audio api to keep the node alive, while returning false allows the browser to terminate the node if it is neither generating new audio data nor receiving data through its inputs that it is processing. the 3 most common types of audio node are: a source of output. an audioworkletprocessor implementing such a node should return true from the process method as long as it produces an output. the method should return false as soon as it's known that it will no longer produce an ou...
...e should return true from the process method while the buffer is playing, and start returning false when the buffer playing has ended (there's no way to call play on the same audiobuffersourcenode again). a node that transforms its input. a processor implementing such a node should return false from the process method to allow the presence of active input nodes and references to the node to determine whether it can be garbage-collected. an example of a node with this behaviour is the gainnode. as soon as there are no inputs connected and references retained, gain can no longer be applied to anything, so it can be safely garbage-collected. a node that transforms its input, but has a so-called tail-time — this means that it will produce an output for some time even after its inputs are disc...
... working draft ...
BaseAudioContext - Web APIs
erfaces. a baseaudiocontext can be a target of events, therefore it implements the eventtarget interface. ...
...ces. a baseaudiocontext can be a target of events, therefore it implements the eventtarget interface. ...
...atechannelsplitter() creates a channelsplitternode, which is used to access the individual channels of an audio stream and process them separately. baseaudiocontext.createconvolver() creates a convolvernode, which can be used to apply convolution effects to your audio graph, for example a reverberation effect. baseaudiocontext.createdelay() creates a delaynode, which is used to delay the incoming audio signal by a certain amount. this node is also useful to create feedback loops in a web audio api graph. baseaudiocontext.createdynamicscompressor() creates a dynamicscompressornode, which can be used to apply acoustic compression to an audio signal. baseaudiocontext.creategain() creates a gainnode, which can be used to control the overall volume of the audio graph. baseaudiocontext.cr...
...audio graph. baseaudiocontext.createiirfilter() creates an iirfilternode, which represents a second order filter configurable as several different common filter types. baseaudiocontext.createoscillator() creates an oscillatornode, a source representing a periodic waveform. it basically generates a tone. baseaudiocontext.createpanner() creates a pannernode, which is used to spatialise an incoming audio stream in 3d space. baseaudiocontext.createperiodicwave() creates a periodicwave, used to define a periodic waveform that can be used to determine the output of an oscillatornode. baseaudiocontext.createscriptprocessor() creates a scriptprocessornode, which can be used for direct audio processing via javascript. baseaudiocontext.createstereopanner() creates a stereopannernode, whic...
Pixel manipulation with canvas - Web APIs
we get the position of the mouse and crop an image of 5 pixels left and above to 5 pixels right and below. then we copy that one over to another canvas and resize the image to the size we want it to. in the zoom canvas we r...
...erty, we are able to zoom into our picture and see the details. we get the position of the mouse and crop an image of 5 pixels left and above to 5 pixels right and below. then we copy that one over to another canvas and resize the image to the size we want it to. in the zoom canvas we resize a 10×10 pixel crop of the original canvas to 200×200. zoomctx.drawimage(canvas, math.min(math.max(0, x - 5), img.width - 10), math.min(math.max(0, y - 5), img.height - 10), 10, 10, 0, 0, 200, 200); because anti-aliasing is enabled by default, we might want to disable the smoothing to see clear pixels. you can toggle the checkbox to see the effect of the imagesmoothingenabled property (which needs prefixes for different browsers). zoom example <...
...it returns a data uri containing a repres...
...it returns a data uri containing a representation of the image in the format specified by the type parameter ...
DeviceProximityEvent - Web APIs
the deviceproximityevent interface provides information about the distance of a nearby physical object using the proximity sensor of a device. properties deviceproximityevent.max read only the maximum sensing distance the sensor is able to report, in centimeters. ...
... the deviceproximityevent interface provides information about the distance of a nearby physical object using the proximity sensor of a device. properties deviceproximityevent.max read only the maximum sensing distance the sensor is able to report, in centimeters. ...
...tance the sensor is able to report, in centimeters. deviceproximityevent.min read only the minimum sensing distance the sensor is able to report, in centimeters. ususally zero. deviceproximityevent.value read only the current device proximity, in centimeters. ...
...r is able to report, in centimeters. deviceproximityevent.min read only the minimum sensing distance the sensor is able to report, in centimeters. ususally zero. deviceproximityevent.value read only the current device proximity, in centimeters. ...
Document - Web APIs
Web › API › Document
ality globally to the document, like how to obtain the page's url and create new elements in the document. ...
...y globally to the document, like how to obtain the page's url and create new elements in the document. ...
... this property instead. document.linkcolor gets/sets the color of hyperlinks in the document. document.rootelement like document.documentelement, but only for <svg> root elements. use this property instead. document.vlinkcolor gets/sets the color of visited hyperlinks. document.width returns the width of the current document. document.xmlencoding returns the encoding as determined by the xml declaration. document.xmlstandalone obsolete since gecko 10 returns true if the xml declaration specifies the document to be standalone (e.g., an external part of the dtd affects the document's content), else false. document.xmlversion obsolete since gecko 10 returns the version number as specified in the xml declaration or "1.0" if the declaration is absent. methods this inte...
... list of elements with the given name. document.hasfocus() returns true if the focus is currently located anywhere inside the specified document. document.open() opens a document stream for writing. document.querycommandenabled() returns true if the formating command can be executed on the current range. document.querycommandindeterm() returns true if the formating command is in an indeterminate state on the current range. document.querycommandstate() returns true if the formating command has been executed on the current range. document.querycommandsupported() returns true if the formating command is supported on the current range. document.querycommandvalue() returns the current value of the current range for a formating command. document.write() writes text in a document. d...
Element.scrollHeight - Web APIs
the height is measured in the same way as clientheight: it includes the element's padding, but not its border, margin or horizontal scrollbar (if present). it can also include the height of pseudo-elements such as ::before or ::after. ...
...y will round the value to an integer. if you need a fractional value, use element.getboundingclientrect(). syntax elemscrollheight = element.scrollheight; value an integer corresponding to the scrollheight pixel value of the element. example padding-top lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. padding-bottom left top right bottom margin-top margin-bottom border-top border-bottom ...
...tation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ...
... top right bottom margin-top margin-bottom border-top border-bottom problems and solutions determine if an element has been totally scrolled the following equivalence returns true if an element is at the end of its scroll, false if it isn't. element.scrollheight - element.scrolltop === element.clientheight when the container does not scroll, but has overflowing children, these checks determine if the container can scroll: window.getcomputedstyle(element).overflowy === 'visible' window.getcomputedstyle(element).overflowy !== 'hidden' scrollheight demo associated with the onscroll event, this equivalence can be useful to determine whether a user has read a text or not (see also the element.scrolltop and element.clientheight properties). for example: html <form name="registration">...
Introduction to the File and Directory Entries API - Web APIs
rtual file system. the file and directory entries api interacts with other related apis. it was built on the file writer api, which, in turn, was built on file api. each of the apis adds different functionality. these apis are a giant evolutionary leap for web apps, which can now cache and process large amounts of data. about this document this introduction discusses essential concepts and terminology in the file and directory entries api. it gives you the big picture and orients you to key concepts. it also describes restrictions that raise security errors if you ignore them. to learn more about terminology used in this api, see the definitions section. for the reference documentation on the file and directory entries api, see the reference landing page and its subpages. the specifica...
...he reference landing page and its subpages. the specification is still being defined and is subject to change. overview the file and directory entries api includes both asynchronous and synchronous versions of the interfaces. the asynchronous api can be used in cases where you don't want an outstanding operation to block the ui. the synchronous api, on the other hand, allows for simpler programming model, but it must be used with webworkers. usefulness of the api the file and directory entries api is an important api for the following reasons: it lets apps have offline and storage features that involve large binary blobs. it can improve performance by letting an app pre-fetch assets in the background and cache locally. it lets users of your web app directly edit a binary file that'...
...stemurl(). these methods are members of both the window object and the worker global scope. the synchronous api, on the other hand, uses the following methods: requestfilesystemsync() and resolvelocalfilesystemsyncurl(). these synchronous methods are members of the worker's global scope only, not the window object. the synchronous api can be simpler for some tasks. its direct, in-order programming model can make code easier to read. the drawback of synchronous api has to do with its interactions with web workers, which has some limitations. when using the asynchronous api, always use the error callbacks when using the asynchronous api, always use the error callbacks. although the error callbacks for the methods are optional parameters, they are not optional for your sanity. you want to ...
... read. the drawback of synchronous api has to do with its interactions with web workers, which has some limitations. when using the asynchronous api, always use the error callbacks when using the asynchronous api, always use the error callbacks. although the error callbacks for the methods are optional parameters, they are not optional for your sanity. you want to know why your calls failed. at minimum, handle the errors to provide error messages, so you'll have an idea of what's going on. the file and directory entries api interacts with other apis the file and directory entries api is designed to be used with other apis and elements on the web platform. for example, you are likely to use one of the following: xmlhttprequest (such as the send() method for file and blob objects) drag ...
HTMLHtmlElement - Web APIs
n retrieve the htmlhtmlelement object for a given document by reading the value of the document.documentelement property. ...
...trieve the htmlhtmlelement object for a given document by reading the value of the document.documentelement property. ...
...iddle" alignment-baseline="middle">htmlhtmlelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmlhtmlelement.version is a domstring representing the version of the html document type definition (dtd) that governs this document. this property should not be used any more as it is non-conforming. simply omit it. methods no specific method; inherits methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlhtmlelement' in that specification. living standard html 5.1the definition of 'htmlhtmlelement' in that specification. recommendation no change since the last snapshot...
...mment html living standardthe definition of 'htmlhtmlelement' in that specification. living standard html 5.1the definition of 'htmlhtmlelement' in that specification. recommendation no change since the last snapshot html5the definition of 'htmlhtmlelement' in that specification. recommendation the version element has been removed, as it is non-conforming. document object model (dom) level 2 html specificationthe definition of 'htmlhtmlelement' in that specification. obsolete reflecting the element change in html 4.01 specification, the version property is now deprecated. document object model (dom) level 1 specificationthe definition of 'htmlhtmlelement' in that specification. obsolete initial definition ...
HTMLImageElement.loading - Web APIs
lazy; value a domstring providing a hint to the user agent as to how to best schedule the loading of the image to optimize page performance. the possible values are: eager the default behavior, eager tells the browser to load the image as soon as the <img> element is processed. lazy tells the user agent to hold off on loading the image until the browser estimates that it will be needed imminently. for instance, if the user is scrolling through the document, a value of lazy will cause the image to only be loaded shortly before it will appear in the window's visual viewport. usage notes timing of the load event the load event is fired when the document has been fully processed. when images are loaded eagerly (which is the default), every image in the document must be fetched before...
...mages whose loading attribute is set to lazy but are located within the visual viewport immediately upon initial page load are loaded as soon as the layout is known, but their loads do not delay the firing of the load event. in other words, these images aren't loaded immediately when processing the <img> element, but are still loaded as part of the initial page load. ...
... as part of the initial page load. they justt don't affect the timing of the load event. that means that when load fires, it's possible that any lazy-loaded images located in the visual viewport may not yet be visible. preventing element shift during image lazy loads when an image whose loading has been delayed by the loading attribute being set to lazy is finally loaded, the browser will determine the final size of the <img> element based on the style and intrinsic size of the image, then reflow the document as needed to update the positions of elements based on any size change made to the element to fit the image. 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. by establishin...
...eflow from occurring, you should explicitly specify the size of the image's presentation using the image element's width and height attributes. by establishing the intrinsic aspect ratio in this manner, you prevent elements from shifting around while the document loads, which can be disconcerting or offputting at best and can cause users to click the wrong thing at worst, depending on the exact timing of the deferred loads and reflows. 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. function addimagetolist(url) { const list = document.queryselector("div.photo-list"); let newitem = document.createelement("div"); newitem.classname = "photo-item"; l...
HTMLTextAreaElement - Web APIs
nt interface provides special properties and methods for manipulating the layout and presentation of <textarea> elements. ...
...nterface provides special properties and methods for manipulating the layout and presentation of <textarea> elements. ...
...the parent form element. if this element is not contained in a form element, it can be the id attribute of any <form> element in the same document or the value null. inputmode maxlength long: returns / sets the element's maxlength attribute, indicating the maximum number of characters the user can enter. this constraint is evaluated only when the value changes. minlength long: returns / sets the element's minlength attribute, indicating the minimum number of characters the user can enter. this constraint is evaluated only when the value changes. name string: returns / sets the element's name attribute, containing the name of the control. placeholder string: returns / sets the element's placeholder attribute, containing a hint to t...
...h. proin nibh sem, bibendum ut placerat nec, cursus et lacus. phasellus vel augue turpis. nunc eu mauris eu leo blandit mollis interdum eget lorem. </textarea></p> </form> maximum length and number of lines example create a textarea with a maximum number of characters per line and a maximum number of lines: first, create a function that takes the text field and a key event as input and determines if any of the limits have been reached. if the limit has not been reached, it will return the key. function checkrows(ofield, okeyevent) { var nkey = (okeyevent || /* old ie */ window.event || /* check is not supported! */ { keycode: 38 }).keycode, // put here the maximum number of characters per line: ncols = 30, // put here the maximum number of lines: nrows = 5, nsel...
IDBRequest: error event - Web APIs
eded', 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 }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }); dbopenrequest.addeventlistener('success', event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transacti...
...; objectstore.createindex('year', 'year', { unique: false }); }); dbopenrequest.addeventlistener('success', event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); const objectstore = transaction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const objectstorerequest = objectstore.add(newitem); objectstorerequest.addeventlistener('error', () => { console.log(`error adding new item: ${newitem.tasktitle}`); }); }); the same example, using the onerror property instead of addeventlistener(): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbo...
...eded = 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 }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transacti...
... unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); const objectstore = transaction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const objectstorerequest = objectstore.add(newitem); objectstorerequest.onerror = () => { console.log(`error adding new item: ${newitem.tasktitle}`); }; }; ...
IDBTransaction: complete event - Web APIs
eded = 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 }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transacti...
...equest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); // add a listener for `complete` transaction.addeventlistener('complete', event => { console.log('transaction was competed'); }); const objectstore = transaction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2019 }; 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 objectst...
...eded = 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 }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transacti...
...onst db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); // add a listener for `complete` transaction.oncomplete = event => { console.log('transaction was competed'); }; const objectstore = transaction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2019 }; const objectstorerequest = objectstore.add(newitem); }; ...
IDBTransaction: error event - Web APIs
st = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transac...
...{ const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); transaction.addeventlistener('error', () => { console.log(`error adding new item: ${newitem.tasktitle}`); }); const objectstore = transaction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const objectstorerequest = 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 co...
...st = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transac...
...ess = (event) => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); transaction.onerror = () => { console.log(`error adding new item: ${newitem.tasktitle}`); }; const objectstore = transaction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const objectstorerequest = objectstore.add(newitem); }; ...
Basic concepts - Web APIs
availability, these applications can work both online and offline. indexeddb is useful for applications that store a large amount of data (for example, a catalog of dvds in a lending library) and applications that don't need persistent internet connectivity to work (for example, mail clients, to-do lists, and notepads). about this document this introduction discusses essential concepts and terminology in indexeddb. it gives you the big picture and explains key concepts. you'll find the following useful: for an overview of the design and structure of indexeddb, see big concepts. to learn more about indexeddb terms, see the definitions section. for a detailed tutorial on how to use the api, see using indexeddb. for the reference documentation on the indexeddb api, refer back to the m...
...ber 18, 2010. while both indexeddb and websql are solutions for storage, they do not offer the same functionalities. websql database is a relational database access system, whereas indexeddb is an indexed table system. big concepts if you have assumptions from working with other types of databases, you might get thrown off when working with indexeddb. so keep the following important concepts in mind: indexeddb databases store key-value pairs. the values can be complex structured objects, and keys can be properties of those objects. you can create indexes that use any property of the objects for quick searching, as well as sorted enumeration. keys can be binary objects. indexeddb is built on a transactional database model. everything you do in indexeddb always happens in the cont...
...on operations on a particular database. it is how you interact with the data in a database. in fact, any reading or changing of data in the database must happen in a transaction. a database connection can have several active transactions associated with it at a time, so long as the writing transactions do not have overlapping scopes. the scope of transactions, which is defined at creation, determines which object stores the transaction can interact with and remains constant for the lifetime of the transaction. so, for example, if a database connection already has a writing transaction with a scope that just covers the flyingmonkey object store, you can start a second transaction with a scope of the unicorncentaur and unicornpegasus object stores. as for reading transactions, you can have se...
...ion. so, for example, if a database connection already has a writing transaction with a scope that just covers the flyingmonkey object store, you can start a second transaction with a scope of the unicorncentaur and unicornpegasus object stores. as for reading transactions, you can have several of them — even overlapping ones. transactions are expected to be short-lived, so the browser can terminate a transaction that takes too long, in order to free up storage resources that the long-running transaction has locked. you can abort the transaction, which rolls back the changes made to the database in the transaction. and you don't even have to wait for the transaction to start or be active to abort it. the three modes of transactions are: readwrite, readonly, and versionchange. the only w...
Media Source API - Web APIs
the media source api, formally known as media source extensions (mse), provides functionality enabling plugin-free web-based streaming media. using mse, media streams can be created via javascript, and played using <audio> and <video> elements. media source extensions concepts and usage playing video and audio has been available in web applications without plugins for a few years now, but the basic features offered have really only been useful for playing single whole tracks. we can't, for example, combine/split arraybuffers. streaming media has up until recently been the domain of flash, with technologies like flash media server serving video streams using the rtmp protocol. the mse standard with media source extensions (mse), this is changing. mse allows us to replace the usual singl...
... information like the ready state of the media for being played, and references to multiple sourcebuffer objects that represent the different chunks of media that make up the entire stream. mse gives us finer grained control over how much and how often content is fetched, and some control over memory usage details, such as when buffers are evicted. it lays the groundwork for adaptive bitrate streaming clients (such as those using dash or hls) to be built on its extensible api. creating assets that work with mse in modern browsers is a laborious process, taking significant time, computing power, and energy. the usage of external utilities to massage the content into a suitable format is required. while browser support for the various media containers with mse is spotty, usage of the h.264 vid...
...c, aac audio codec, and mp4 container format is a common baseline. mse also provides an api for runtime detection of container and codec support. if you do not require explicit control of video quality over time, the rate at which content is fetched, or the rate at which memory is evicted, then the <video> and <source> tags may well be a simple and adequate solution. dash dynamic adaptive streaming over http (dash) is a protocol for specifying how adaptive content should be fetched. it is effectively a layer built on top of mse for building adaptive bitrate streaming clients. while there are other protocols available (such as http live streaming (hls)), dash has the most platform support. dash moves lots of logic out of the network protocol and into the client side application logic, usin...
... the two most common use cases for dash involve watching content “on demand” or “live.” on demand allows a developer to take their time transcoding the assets into multiple resolutions of various quality. ...
performance.now() - Web APIs
Web › API › Performance › now
the performance.now() method returns a domhighrestimestamp, measured in milliseconds. note: this feature is available in web workers. the returned value represents the time elapsed since the time origin. bear in mind the following points: in dedicated workers created from a window context, the value in the worker will be lower than performance.now() in the window who spawned that worker. it used to be the same as t0 of the main context, but this was changed. ...
...ted workers created from a window context, the value in the worker will be lower than performance.now() in the window who spawned that worker. it used to be the same as t0 of the main context, but this was changed. in shared or service workers, the value in the worker might be higher than that of the main context because that window can be created after those workers. it's important to keep in mind that to mitigate potential security threats such as spectre, browsers typically round the returned value by some amount in order to be less predictable. this inherently introduces a degree of inaccuracy by limiting the resolution or precision of the timer. for example, firefox rounds the returned time to 1 millisecond increments. the precision of the returned value is subject to change if/when ...
... for example, firefox rounds the returned time to 1 millisecond increments. the precision of the returned value is subject to change if/when the security concerns are alleviated through other means. syntax t = performance.now(); example const t0 = performance.now(); dosomething(); const t1 = performance.now(); console.log(`call to dosomething took ${t1 - t0} milliseconds.`); unlike other timing data available to javascript (for example date.now), the timestamps returned by performance.now() are not limited to one-millisecond resolution. instead, they represent times as floating-point numbers with up to microsecond precision. also unlike date.now(), the values returned by performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manu...
...stamps returned by performance.now() are not limited to one-millisecond resolution. instead, they represent times as floating-point numbers with up to microsecond precision. also unlike date.now(), the values returned by performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like ntp). otherwise, performance.timing.navigationstart + performance.now() will be approximately equal to date.now(). reduced time precision to offer protection against timing attacks and fingerprinting, the precision of performance.now() might get rounded depending on browser settings. in firefox, the privacy.reducetimerprecision preference is enabled by default and defaults to 1ms. // reduced time precision (1ms) in firefox 60 ...
Web Push API Notifications best practices - Web APIs
“if done well, it's nice to have, but if not done well, it's really annoying.” — overheard conversation between two browser developers discussing the ethics of push notifications. 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. ...
...er found a hiccup in the approvals and wants to get your feedback on something before she proceeds. after a few failed attempts to get your attention, they send you an email, and your email app produces a push notification that successfully alerts you, even though your mail web app is not open. in this document, we’ll talk about the ethical use of web push notifications. sometimes they can eliminate frustration and annoyance, and sometimes they can cause them, and it’s up to you as a developer to make wise recommendations (and decisions) about the use of push notifications. what are you hoping to achieve with this push notification? as with everything, with great power comes great responsibility. every push notification should be useful and time-sensitive, and the user should always b...
...tions. what are you hoping to achieve with this push notification? as with everything, with great power comes great responsibility. every push notification should be useful and time-sensitive, and the user should always be asked for permission before sending the first one, and be offered an easy way to opt out of getting more in the future. there are some basic questions you can answer to determine if a push notification is needed: is there someone waiting in real-time for a response? in our above example, the program manager is awaiting your response and so a push notification is appropriate. is up-to-the minute updating necessary? i use a service that aggregates different social media news sources. when a story i’m interested in is trending, i’d like to get a notification! is th...
... a service that aggregates different social media news sources. when a story i’m interested in is trending, i’d like to get a notification! is there breaking news that is timely? this is where it gets a little tricky. sometimes news sites request push notifications so they can essentially say "look at me! look at me!" it all comes down to what the user wants, and you can use behavior to determine intent. for example, if the user views more than one article, or lingers on your page for several minutes, they may be interested in receiving updates. in addition to the question of whether a push notification is required at all, there are many different types of push notifications, ranging from casual-and-disappearing to persistent-and-requiring-interaction. we caution you to use the intera...
RTCIceTransport.state - Web APIs
this differs from the gatheringstate, which only indicates whether or not ice gathering is currently underway. syntax icestate = icetransport.state; value a domstring, whose value is one of those found in the enumerated type rtcicetransportstate, which indicates the stage of ice gathering that's currently underway. ...
...its value will be one of the following: "new" the rtcicetransport is currently gathering local candidates, or is waiting for the remote device to begin to transmit the remote candidates, or both. in this state, checking of candidates to look for those which might be acceptable has not yet begun. "checking" at least one remote candidate has been received, and the rtcicetransport has begun examining pairings of remote and local candidates in order to attempt to identify viable pairs that could be used to establish a connection. keep in mind that gathering of local candidates may still be underway, and, similarly, the remote device also may still be gathering candidates of its own. "connected" a viable candidate pair has been found and selected, and the rtcicetransport has connected th...
...es. "completed" the transport has finished gathering local candidates and has received a notification from the remote peer that no more candidates will be sent. in addition, all candidate pairs have been considered and a pair has been selected for use. if consent checks fail on all successful candidate pairs, the transport state will change to "failed". "disconnected" the ice agent has determined that connectivity has been lost for this rtcicetransport. this is not a failure state (that's "failed"). a value of "disconnected" means that a transient issue has occurred that has broken the connection, but that should resolve itself automatically without your code having to take any action. see the disconnected state for additional details. "failed" the rtcicetransport has finished the gat...
...matically without your code having to take any action. see the disconnected state for additional details. "failed" the rtcicetransport has finished the gathering process, has received the "no more candidates" notification from the remote peer, and has finished checking pairs of candidates, without successfully finding a pair that is both valid and for which consent can be obtained. this is a terminal state, indicating that the connection cannot be achieved or maintained. "closed" the transport has shut down and is no longer responding to stun requests. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicetransportstate' in that specification. candidate recommendation initial definition. ...
SVGGeometryElement - Web APIs
y with an equivalent path, and which can be filled and stroked. this includes paths and the basic shapes. ...
...th an equivalent path, and which can be filled and stroked. this includes paths and the basic shapes. ...
...lly part of the svgpathelement interface. in svg 2 they were moved to this interface. properties this interface also inherits properties from its parent, svggraphicselement. svggeometryelement.pathlength read only this property reflects the pathlength attribute. methods this interface also inherits methods from its parent, svggraphicselement. svggeometryelement.ispointinfill() determines whether a given point is within the fill shape of an element. normal hit testing rules apply; the value of the pointer-events property on the element determines whether a point is considered to be within the fill. svggeometryelement.ispointinstroke() determines whether a given point is within the stroke shape of an element. normal hit testing rules apply; the value of the pointer-events prope...
... svggeometryelement.gettotallength() returns the user agent's computed value for the total length of the path in user units. ...
Using the Screen Capture API - Web APIs
note: it may be useful to note that recent versions of the webrtc adapter.js shim include implementations of getdisplaymedia() to enable screen sharing on browsers that support it but do not implement the current standard api. this works with at least chrome, edge, and firefox. capturing screen contents capturing screen contents as a live mediastream is initiated by calling navigator.mediadevices.getdisplaymedia(), which returns a promise that resolves to a stream containing the live screen contents. ...
... shared stream. this effect can be amplified when capturing logical display surfaces, which may contain content that the user doesn't know about at all, let alone see. user agents which take privacy seriously should obfuscate content that is not actually visible onscreen, unless authorization has been given to share that content specifically. authorizing capture of display contents before streaming of captured screen contents can begin, the user agent will ask the user to confirm the sharing request, and to select the content to share. examples simple screen capture in this example, the contents of the captured screen area are simply streamed into a <video> element on the same page. javascript there isn't all that much code needed in order to make this work, and if you're familiar w...
...on id="stop">stop capture</button></p> <video id="video" autoplay></video> <br> <strong>log:</strong> <br> <pre id="log"></pre> the key parts of the html are: a <button> labeled "start capture" which, when clicked, calls the startcapture() function to request access to, and begin capturing, screen contents. a second button, "stop capture", which upon being clicked calls stopcapture() to terminate capture of screen contents. a <video> into which the captured screen contents are streamed. a <pre> block into which logged text is placed by the intercepted consolemethod. css the css is entirely cosmetic in this example. the video is given a border, and its width is set to occupy nearly the entire available horizontal space (width: 98%). max-width is set to 860px to set an absolute uppe...
...lay-capture permission. this can be done using the feature-policy http header or—if you're using the screen capture api in an <iframe>, the <iframe> element's allow attribute. ...
Screen Wake Lock API - Web APIs
it allows for a simple platform based solution which up until now could only be achieved via workarounds which were potentially power hungry. only visible (active) documents can acquire the screen wake lock. ...
...en an application needs to keep running. concepts and usage most devices by default turn off their screen after a specified amount of time to prolong the life of the hardware. modern devices do this to save on battery power. whilst this is a useful feature, some applications need the screen to stay awake to be their most useful. the screen wake lock api prevents the screen from turning off, dimming or locking. it allows for a simple platform based solution which up until now could only be achieved via workarounds which were potentially power hungry. only visible (active) documents can acquire the screen wake lock. there are plenty of use cases for keeping a screen on, including reading an ebook, map navigation, following a recipe, presenting to an audience, scanning a qr/barcode or applic...
... object to control release later and also to reacquire the lock if need be. the screen wake lock api should be used to keep the screen on to benefit usability. it's a good idea to show some feedback on the interface to show if wake lock is active and a way for the user to disable it if they wish. screen wake lock api interfaces wakelock the wakelock interface prevents device screens from dimming or locking when an application needs to keep running. wakelocksentinel provides a handle to the underlying platform wake lock and if referenced can be manually released and reacquired. get an instance of the object by calling wakelock.request. navigator.wakelock returns a wakelock object instance, from which all other functionality can be accessed. examples feature detection this code ch...
...en user ends activity that required always-on screen. for example, a ticketing app which uses qr codes to transmit ticket information, might acquire screen wake lock when the qr code is displayed (so that code is successfully scanned) but release afterwards. a presentation app might hold the lock only while a presentation is active, but not when presentation is being edited. 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. only active documents can acquire screen wake locks and previously acquired locks are automatically released when document becomes inactive. therefore make sure to re-acquire screen wake lock if necessary when document becomes active (listen for visibi...
WebGLRenderingContext.depthFunc() - Web APIs
the webglrenderingcontext.depthfunc() method of the webgl api specifies a function that compares incoming pixel depth to the current depth buffer value. syntax void gl.depthfunc(func); parameters func a glenum specifying the depth comparison function, which sets the conditions under which the pixel will be drawn. the default value is gl.less. ...
...epthfunc() method of the webgl api specifies a function that compares incoming pixel depth to the current depth buffer value. syntax void gl.depthfunc(func); parameters func a glenum specifying the depth comparison function, which sets the conditions under which the pixel will be drawn. the default value is gl.less. ...
...ng pixel depth to the current depth buffer value. syntax void gl.depthfunc(func); parameters func a glenum specifying the depth comparison function, which sets the conditions under which the pixel will be drawn. the default value is gl.less. ...
...c(func); parameters func a glenum specifying the depth comparison function, which sets the conditions under which the pixel will be drawn. the default value is gl.less. possible values are: gl.never (never pass) gl.less (pass if the incoming value is less than the depth buffer value) gl.equal (pass if the incoming value equals the the depth buffer value) gl.lequal (pass if the incoming value is less than or equal to the depth buffer value) gl.greater (pass if the incoming value is greater than the depth buffer value) gl.notequal (pass if the incoming value is not equal to the depth buffer value) gl.gequal (pass if the incoming value is greater than or equal to the depth buffer value) gl.always (always pass) return value none. examples the depth testing is disa...
WebGLRenderingContext.texParameter[fi]() - Web APIs
l array texture. the pname parameter is a glenum specifying the texture parameter to set. the param parameter is a glfloat or glint specifying the value for the specified parameter pname. pname description param available in webgl 1 gl.texture_mag_filter texture magnification filter gl.linear (default value), gl.nearest. gl.texture_min_filter texture minification filter gl.linear, gl.nearest, gl.nearest_mipmap_nearest, gl.linear_mipmap_nearest, gl.nearest_mipmap_linear (default value), gl.linear_mipmap_linear. gl.texture_wrap_s wrapping function for texture coordinate s gl.repeat (default value),gl.clamp_to_edge, gl.mirrored_repeat. gl.texture_wrap_t wrapping function for texture coordinate t ...
...ult value), gl.gequal, gl.less, gl.greater, gl.equal, gl.notequal, gl.always, gl.never. gl.texture_compare_mode texture comparison mode gl.none (default value), gl.compare_ref_to_texture. gl.texture_max_level maximum texture mipmap array level any int values. gl.texture_max_lod texture maximum level-of-detail value any float values. ...
...al, gl.less, gl.greater, gl.equal, gl.notequal, gl.always, gl.never. gl.texture_compare_mode texture comparison mode gl.none (default value), gl.compare_ref_to_texture. gl.texture_max_level maximum texture mipmap array level any int values. gl.texture_max_lod texture maximum level-of-detail value any float values. ...
... recommendation initial definition for webgl. opengl es 2.0the definition of 'gltexparameter' in that specification. ...
WebGL: 2D and 3D graphics for the web - Web APIs
Web › API › WebGL API
es. ...
...ou improve the quality, performance, and reliability of your webgl content. using extensions a guide to using webgl extensions. tutorials webgl tutorial a beginner's guide to webgl core concepts. a good place to start if you don't have previous webgl experience. examples a basic 2d webgl animation example this example demonstrates the simple animation of a one-color shape. ...
... advanced tutorials webgl model view projection a detailed explanation of the three core matrices that are typically used to represent a 3d object view: the model, view and projection matrices. ...
... view: the model, view and projection matrices. matrix math for the web a useful guide to how 3d transform matrices work, and can be used on the web — both for webgl calculations and in css3 transforms. resources raw webgl: an introduction to webgl a talk by nick desaulniers that introduces the basics of webgl. this is a great place to start if you've never done low-level graphics programming. khronos webgl site the main web site for webgl at the khronos group. webgl fundamentals a basic tutorial with fundamentals of webgl. webgl playground an online tool for creating and sharing webgl projects. good for quick prototyping and experimenting. webgl academy an html/javascript editor with tutorials to learn basics of webgl programming. webgl stats a site with statistics about webgl ...
WebRTC connectivity - Web APIs
making their way down the line toward their worse candidates. ideally, candidates are udp (since it's faster, and media streams are able to recover from interruptions relatively easily), but the ice standard does allow tcp candidates as well. generally, ice candidates using tcp are only going to be used when udp is not available or is restricted in ways that make it not suitable for media streaming. not all browsers support ice over tcp, however. ice allows candidates to represent connections over either tcp or udp, with udp generally being preferred (and being more widely supported). each protocol supports a few types of candidate, with the candidate types defining how the data makes its way from peer to peer. udp candidate types udp candidates (candidates with their protocol set to u...
...initiator's request with a candidate whose ip address is unrelated to the remote peer. relay a relay candidate is generated just like a server reflexive candidate ("srflx"), but using turn instead of stun. tcp candidate types tcp candidates (that is, candidates whose protocol is tcp) can be of these types: active the transport will try to open an outbound connection but won't receive incoming connection requests. this is the most common type, and the only one that most user agents will gather. passive the transport will receive incoming connection attempts but won't attempt a connection itself. so the transport will try to simultaneously open a connection with its peer. choosing a candidate pair the ice layer selects one of the two peers to serve as the controlling agent. this...
...e transport will try to simultaneously open a connection with its peer. choosing a candidate pair the ice layer selects one of the two peers to serve as the controlling agent. this is the ice agent which will make the final decision as to which candidate pair to use for the connection. the other peer is called the controlled agent. you can identify which one your end of the connection is by examining the value of rtcicecandidate.transport.role, although in general it doesn't matter which is which. the controlling agent not only takes responsibility for making the final decision as to which candidate pair to use, but also for signaling that selection to the controlled agent by using stun and an updated offer, if necessary. the controlled agent just waits to be told which candidate pair to ...
....transport.role, although in general it doesn't matter which is which. the controlling agent not only takes responsibility for making the final decision as to which candidate pair to use, but also for signaling that selection to the controlled agent by using stun and an updated offer, if necessary. the controlled agent just waits to be told which candidate pair to use. it's important to keep in mind that a single ice session may result in the controlling agent choosing more than one candidate pair. each time it does so and shares that information with the controlled agent, the two peers reconfigure their connection to use the new configuration described by the new candidate pair. once the ice session is complete, the configuration that's currently in effect is the final one, unless an ice ...
Writing WebSocket servers - Web APIs
a websocket server is nothing more than an application listening on any port of a tcp server that follows a specific protocol. the task of creating a custom server tends to scare people; however, it can be straightforward to implement a simple websocket server on your platform of choice. a websocket server can be written in any server-side programming language that is capable of berkeley sockets, such as c(++), python, php, or server-side javascript. this is not a tutorial in any specific language, but serves as a guide to facilitate writing your own server. this article assumes you're already familiar with how http works, and that you have a moderate level of programming experience. depending on language support, knowledge of tcp sockets may be required. the scope of this guide is to pres...
... note: read the latest official websockets specification, rfc 6455. ...
...ers (for load-balancing or other practical reasons), so you will often use a reverse proxy (such as a regular http server) to detect websocket handshakes, pre-process them, and send those clients to a real websocket server. this means that you don't have to bloat your server code with cookie and authentication handlers (for example). the websocket handshake first, the server must listen for incoming socket connections using a standard tcp socket. depending on your platform, this may be handled for you automatically. for example, let's assume that your server is listening on example.com, port 8000, and your socket server responds to get requests at example.com/chat. warning: the server may listen on any port it chooses, but if it chooses any port other than 80 or 443, it may have problems ...
... miscellaneous for details. the sec-websocket-accept header is important in that the server must derive it from the sec-websocket-key that the client sent to it. to get it, concatenate the client's sec-websocket-key and the string "258eafa5-e914-47da-95ca-c5ab0dc85b11" together (it's a "magic string"), take the sha-1 hash of the result, and return the base64 encoding of that hash. note: this seemingly overcomplicated process exists so that it's obvious to the client whether the server supports websockets. this is important because security issues might arise if the server accepts a websockets connection but interprets the data as a http request. so if the key was "dghlihnhbxbszsbub25jzq==", the sec-websocket-accept header's value is "s3pplmbitxaq9kygzzhzrbk+xoo=". once the server sends th...
Web Audio API best practices - Web APIs
es, you are looking at either the grabbing the file from an htmlmediaelement (i.e. an <audio> or <video> element), or you're looking to fetch the file and decode it into a buffer. both are legitimate ways of working, however, it's more common to use the former when you are working with full-length tracks, and the latter when working with shorter, more sample-like tracks. media elements have streaming support out of the box. the audio will start playing when the browser determines it can load the rest of the file before playing finishes. you can see an example of how to use this with the web audio api in the using the web audio api tutorial. you will, however, have more control if you use a buffer node. you have to request the file and wait for it to load (this section of our advanced articl...
...b audio api comes with, you can do most of what you'd want to do. if you are looking for sound creation or a more instrument-based option, tone.js is a great library. it provides advanced scheduling capabilities, synths, and effects, and intuitive musical abstractions built on top of the web audio api. r-audio, from the bbc's research & development department, is a library of react components aiming to provide a "more intuitive, declarative interface to web audio". if you're used to writing jsx it might be worth looking at. autoplay policy browsers have started to implement an autoplay policy, which in general can be summed up as: "create or resume context from inside a user gesture". but what does that mean in practice? a user gesture has been interpreted to mean a user-initiated eve...
...on them is a good option for signalling to assistive technology what the button's exact purpose is, and therefore making the app more accessible. there's a demo of how to use it here. as you work with a lot of changing values within the web audio api and will want to provide users with control over these, the range input is often a good choice of control to use. it's a good option as you can set minimum and maximum values, as well as increments with the step attribute. setting audioparam values there are two ways to manipulate audionode values, which are themselves objects of type audioparam interface. the first is to set the value directly via the property. so for instance if we want to change the gain value of a gainnode we would do so thus: gainnode.gain.value = 0.5; this will set ou...
...re using any of the audioparam's defined methods to set these values, they will take precedence over the above property setting. if for example, you want the gain value to be raised to 1 in 2 seconds time, you can do this: gainnode.gain.setvalueattime(1, audioctx.currenttime + 2); it will override the previous example (as it should), even if it were to come later in your code. bearing this in mind, if your website or application requires timing and scheduling, it's best to stick with the audioparam methods for setting values. if you're sure it doesn't, setting it with the value property is fine. ...
Web audio spatialization basics - Web APIs
le will cover the basics of how to implement such a system. 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. think sounds flying over you, creeping up behind you, moving across in front of you. that sort of thing. it's really useful for webxr and gaming. in 3d spaces, it's the only way to achieve realistic audio. libraries like three.js and a-frame harness its potential when dealing with sound. it's worth noting that you don't have to move sound within a full 3d space either — you could stick with just a 2d plane, so if you were planning a 2d game, this would still be the node you were looking for. note: there's also a stereopannernode desi...
...ted in our basic using the web audio api guide. see the 3d spatialization demo live (and see the source code also). the boombox sits inside a room (defined by the edges of the browser viewport), and in this demo, we can move and rotate it with the provided controls. when we move the boombox, the sound it produces changes accordingly, panning as it moves to the left or right of the room, or becoming quieter as it is moved away from the user or is rotated so the speakers are facing away from them, etc. this is done by setting the different properties of the pannernode object instance in relation to that movement, to emulate spacialization. note: the experience is much better if you use headphones, or have some kind of surround sound system to plug your computer into. creating an audio li...
... rolloff = 10; now we can start setting our position and orientation of our boombox. this is a lot like how we did it with our listener. these are also the parameters we're going to change when the controls on our interface are used. const positionx = posx; const positiony = posy; const positionz = posz; const orientationx = 0.0; const orientationy = 0.0; const orientationz = -1.0; note the minus value on our z orientation — this sets the boombox to face us. a positive value would set the sound source facing away from us. let's use the relevant constructor for creating our panner node and pass in all those parameters we set above: const panner = new pannernode(audioctx, { panningmodel: pannermodel, distancemodel: distancemodel, positionx: positionx, positiony: positi...
...e: refdistance, maxdistance: maxdistance, rollofffactor: rolloff, coneinnerangle: innercone, coneouterangle: outercone, coneoutergain: outergain }) moving the boombox now we're going to move our boombox around our 'room'. we've got some controls set up to do this. we can move it left and right, up and down, and back and forth; we can also rotate it. the sound direction is coming from the boombox speaker at the front, so when we rotate it, we can alter the sound's direction — i.e. make it project to the back when the boombox is rotated 180 degrees and facing away from us. we need to set up a few things for the interface. first, we'll get references to the elements we want to move, then we'll store references to the values we'll change when we set up css transforms to ...
Window.requestAnimationFrame() - Web APIs
domhighrestimestamp, which indicates the current time (based on the number of milliseconds since time origin). when callbacks queued by requestanimationframe() begin to fire multiple callbacks in a single frame, each receives the same timestamp even though time has passed during the computation of every previous callback's workload. this timestamp is a decimal number, in milliseconds, but with a minimal precision of 1ms (1000 µs). be sure to always use the first argument (or some other method for getting the current time) to calculate how much the animation will progress in a frame, otherwise the animation will run faster on high refresh rate screens. check the example below for a way to do this. syntax window.requestanimationframe(callback); parameters callback the function to c...
...ion of the time elapsed since the start of the animation (in milliseconds) with 0.1 * elapsed. the element's final position is 200px (0.1 * 2000) to the right of its initial position. ...
... is 200px (0.1 * 2000) to the right of its initial position. const element = document.getelementbyid('some-element-you-want-to-animate'); let start; function step(timestamp) { if (start === undefined) start = timestamp; const elapsed = timestamp - start; // `math.min()` is used here to make sure that the element stops at exactly 200px. element.style.transform = 'translatex(' + math.min(0.1 * elapsed, 200) + 'px)'; if (elapsed < 2000) { // stop the animation after 2 seconds window.requestanimationframe(step); } } window.requestanimationframe(step); notes edge versions below 17 and internet explorer do not reliably fire requestanimationframe before the paint cycle. specification specification status comment html living standardthe defini...
... obsolete initial definition ...
Worker.prototype.postMessage() - Web APIs
above, if you want to pass multiple values you can send an array. transfer example this example shows a firefox add-on that transfers an arraybuffer from the main thread to the chromeworker, and then the chromeworker transfers it back to the main thread. ...
...transfers it back to the main thread. ...
...nes below }, [ arrbuf // the array buffer we created 9 lines above ] ); console.info('arrbuf.bytelength post transfer:', arrbuf.bytelength); worker code self.onmessage = function (msg) { switch (msg.data.atopic) { case 'do_sendworkerarrbuff': sendworkerarrbuff(msg.data.abuf) break; default: throw 'no atopic on incoming message to chromeworker'; } } function sendworkerarrbuff(abuf) { console.info('from worker, pre send back abuf.bytelength:', abuf.bytelength); self.postmessage({atopic:'do_sendmainarrbuff', abuf:abuf}, [abuf]); console.info('from worker, post send back abuf.bytelength:', abuf.bytelength); } output logged arrbuf.bytelength pre transfer: 8 boo...
...} bootstrap.js:20 got back buf in main thread, abuf.bytelength: 8 bootstrap.js:12 from worker, post send back abuf.bytelength: 0 myworker.js:7:2 bytelength goes to 0 as it is transferred. to see a full working example of this firefox demo add-on see here: github :: chromeworker - demo-transfer-arraybuffer speci...
Using the aria-valuenow attribute - Accessibility
the aria-valuenow attribute is used to define the current value for a range widget such as a slider, spinbutton or progressbar. if the current value is not known, the author should not set the aria-valuenow attribute. if the aria-valuenow has a known minimum and maximum value, authors should set the aria-valuemin and aria-valuemax attributes. when the rendered value cannot be accurately represented as a number, authors should use the aria-valuetext attribute in conjunction with aria-valuenow to provide a user-friendly representation of the range's current value. for example, a slider may have rendered values of small, medium, and large. in this case, the values of aria-valuenow could range from 1 through 3, which indicate the position of each value in the value space, but the aria-va...
...e of the strings: small, medium, or large. aria-valuenow is a required attribute of role slider, scrollbar and spinbutton. value string representation of a number possible effects on user agents and assistive technology for elements with role progressbar and scrollbar, assistive technologies should render the actual value as a percentage, calculated as a position on the range from aria-valuemin to aria-valuemax if both are defined, otherwise the actual value with a percent indicator. for elements with role slider and spinbutton, assistive technologies should render the actual value to users. note: opinions may differ on how assistive technology should handle this technique. the information provided above is one of those opinions and therefore not normative. examples example 1: the...
...ole slider and spinbutton, assistive technologies should render the actual value to users. note: opinions may differ on how assistive technology should handle this technique. the information provided above is one of those opinions and therefore not normative. examples example 1: the snippet below shows a simple slider with a current value of 4. ...
...refore not normative. examples example 1: the snippet below shows a simple slider with a current value of 4. ...
Using the slider role - Accessibility
mation provided above is one of those opinions and therefore not normative. examples example 1: simple numerical range in the example below, a simple slider is used to select a value between 1 and 100. the current volume is 50. the application will programmatically update the value of aria-valuenow in response to user input. ...
...fore not normative. examples example 1: simple numerical range in the example below, a simple slider is used to select a value between 1 and 100. the current volume is 50. the application will programmatically update the value of aria-valuenow in response to user input. ...
...e that is not, semantically, a number. in these cases, the aria-valuetext attribute is used to provide the appropriate text name for the currently selected value. in the example below, the slider is used to select a day of the week. ...
...names = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]; var updateslider = function (newvalue) { var handle = document.getelementbyid("day-handle"); handle.setattribute("aria-valuenow", newvalue.tostring()); handle.setattribute("aria-valuetext", daynames[newvalue]); }; working examples: slider example notes aria attributes used aria-valuemin aria-valuemax aria-valuenow aria-valuetext aria-orientation related aria techniques compatibility tbd: add support information for common ua and at product combinations additional resources wai-aria specification for the slider role ...
aspect-ratio - CSS: Cascading Style Sheets
the aspect-ratio css media feature can be used to test the aspect ratio of the viewport. syntax the aspect-ratio feature is specified as a <ratio> value representing the width-to-height aspect ratio of the viewport. it is a range feature, meaning you can also use the prefixed min-aspect-ratio and max-aspect-ratio variants to query minimum and maximum values, respectively. examples the example below is contained in an <iframe>, which creates its own viewport. resize the <iframe> to see aspect-ratio in action. ...
...nge feature, meaning you can also use the prefixed min-aspect-ratio and max-aspect-ratio variants to query minimum and maximum values, respectively. examples the example below is contained in an <iframe>, which creates its own viewport. resize the <iframe> to see aspect-ratio in action. html <div id='inner'> watch this element as you resize your viewport's width and height. ...
...o use the prefixed min-aspect-ratio and max-aspect-ratio variants to query minimum and maximum values, respectively. examples the example below is contained in an <iframe>, which creates its own viewport. resize the <iframe> to see aspect-ratio in action. html <div id='inner'> watch this element as you resize your viewport's width and height. ...
...aximum aspect ratio */ @media (max-aspect-ratio: 3/2) { div { background: #9ff; /* cyan */ } } /* exact aspect ratio, put it at the bottom to avoid override*/ @media (aspect-ratio: 1/1) { div { background: #f9a; /* red */ } } _example used iframe and dataurl to enable this iframe could resize html <label id="wf" for="w">width:165</label> <input id="w" name="w" type="range" min="100" max="250" step="5" value="165"> <label id="hf" for="w">height:165</label> <input id="h" name="h" type="range" min="100" max="250" step="5" value="165"> <iframe id="outer" src="data:text/html,<style> @media (min-aspect-ratio: 8/5) { div { background: %239af; } } @media (max-aspect-ratio: 3/2) { div { background: %239ff; } } @media (aspect-ratio: 1/1) { div { background: %23f9a; } }</style><...
color - CSS: Cascading Style Sheets
Web › CSS › @media › color
r css media feature can be used to test the number of bits per color component (red, green, blue) of the output device. syntax the color feature is specified as an <integer> value that represents the number of bits per color component (red, green, blue) of the output device. if the device is not a color device, the value is zero. ...
...e number of bits per color component (red, green, blue) of the output device. syntax the color feature is specified as an <integer> value that represents the number of bits per color component (red, green, blue) of the output device. if the device is not a color device, the value is zero. it is a range feature, meaning that you can also use the prefixed min-color and max-color variants to query minimum and maximum values, respectively. ...
... see applying color to html elements using css to learn more about using css to apply color to html. ...
... css to learn more about using css to apply color to html. examples html <p>this text should be black on non-color devices, red on devices with a low number of colors, and greenish on devices with a high number of colors.</p> css p { color: black; } /* any color device */ @media (color) { p { color: red; } } /* any color device with at least 8 bits per color component */ @media (min-color: 8) { p { color: #24ba13; } } result specifications specification status comment media queries level 4the definition of 'color' in that specification. candidate recommendation the value can now be negative, in which case it computes to false. media queriesthe definition of 'color' in that specification. recommendation initial def...
Mozilla CSS extensions - CSS: Cascading Style Sheets
ccepted] -moz-animation-direction [prefixed version still accepted] -moz-animation-duration [prefixed version still accepted] -moz-animation-fill-mode [prefixed version still accepted] -moz-animation-iteration-count [prefixed version still accepted] -moz-animation-name [prefixed version still accepted] -moz-animation-play-state [prefixed version still accepted] -moz-animation-timing-function [prefixed version still accepted] -moz-appearance b -moz-backface-visibility [prefixed version still accepted] -moz-background-clipobsolete since gecko 2 -moz-background-originobsolete since gecko 2 -moz-background-inline-policyobsolete since gecko 32 [superseded by the standard version box-decoration-break] -moz-background-sizeobsolete since gecko 2 -moz-border-end ...
...xed version still accepted] -moz-transform-origin [prefixed version still accepted] -moz-transform-style [prefixed version still accepted] -moz-transition [prefixed version still accepted] -moz-transition-delay [prefixed version still accepted] -moz-transition-duration [prefixed version still accepted] -moz-transition-property [prefixed version still accepted] -moz-transition-timing-function [prefixed version still accepted] -moz-user-select values global values -moz-initial -moz-appearance button button-arrow-down button-arrow-next button-arrow-previous button-arrow-up button-bevel checkbox checkbox-container checkbox-label checkmenuitem dialog groupbox listbox menuarrow menucheckbox menuimage menuitem menuitemtext menulist menulist-b...
...uitemtext menulist menulist-button menulist-text menulist-textfield menupopup menuradio menuseparator -moz-mac-unified-toolbar -moz-win-borderless-glass -moz-win-browsertabbar-toolbox -moz-win-communications-toolbox -moz-win-glass -moz-win-media-toolbox -moz-window-button-box -moz-window-button-box-maximized -moz-window-button-close -moz-window-button-maximize -moz-window-button-minimize -moz-window-button-restore -moz-window-titlebar -moz-window-titlebar-maximized progressbar progresschunk radio radio-container radio-label radiomenuitem resizer resizerpanel scale-horizontal scalethumb-horizontal scalethumb-vertical scale-vertical scrollbarbutton-down scrollbarbutton-left scrollbarbutton-right scrollbarbutton-up scrollbar-small scrollbarthumb-horizontal ...
...-simp-chinese-informal -moz-tamil -moz-telugu -moz-thai -moz-trad-chinese-formal -moz-trad-chinese-informal -moz-urdu overflow -moz-scrollbars-none -moz-scrollbars-horizontal -moz-scrollbars-vertical -moz-hidden-unscrollable text-align -moz-center -moz-left -moz-right text-decoration -moz-anchor-decoration -moz-user-select -moz-all -moz-none width, min-width, and max-width -moz-min-content -moz-fit-content -moz-max-content -moz-available pseudo-elements and pseudo-classes a – d ::-moz-anonymous-block eg@:- bug 331432 ::-moz-anonymous-positioned-block :-moz-any :-moz-any-link [matches :link and :visited] :-moz-broken ::-moz-canvas ::-moz-color-swatch ::-moz-cell-content :-moz-drag-over f – i :-moz-first...
Scaling of SVG backgrounds - CSS: Cascading Style Sheets
this article describes how scaling of svg images is handled when using these properties. the algorithm, in summary the algorithm can for the most part be summarized by these four rules. there are some edge cases that aren't covered by these rules, but this covers the majority of cases. if background-size specifies a fixed dimension (that is, percentages and relative units are fixed by their context), that dimension wins. ...
... is specified, but no dimensions, rule 4 is applied -- except that rule 2 also applies. the image is therefore rendered just like for the contain case. ...
...atio.svg); background-size: auto auto; the rendered output looks like this: using "auto" and one specific length given rule 1, specified dimensions are always used, so we need to use our rules only to determine the second dimension. source: no dimensions or intrinsic ratio if the image has no dimensions or intrinsic ratio, rule 4 applies, and we use the background area's dimension to determine the value for the auto dimension. background: url(no-dimensions-or-ratio.svg); background-size: auto 150px; here, the width is determined using the background area's width per rule 4, while the height is the 140px specified in the css. source: one specified dimension with no intrinsic ratio if the image has one specified dimension but no intrinsic ratio, that specified dimension is used p...
..., so the 100px width specified in the svg is selected, per rule 3. the height is set at 125px in the css, so that is selected per rule 1. source: one specified dimension with intrinsic ratio when a dimension is specified, rule 1 applies that dimension from the svg to the rendered background unless specifically overridden by the css. when an intrinsic ratio is also specified, that's used to determine the other dimension. background: url(100px-height-3x4-ratio.svg); background-size: 150px auto; in this case, we use the width of the image specified in the css set at 150px, so rule 1 is applied. the intrinsic 3:4 aspect ratio then determines the height for the auto case. source: no specified dimensions with intrinsic ratio if no dimensions are specified in the svg, the specified dimensio...
Viewport concepts - CSS: Cascading Style Sheets
ome returns the length in the default pixel size. when zoomed in you may get: document.documentelement.clientwidth /* 800 */ window.innerwidth /* 800 */ window.outerwidth /* 800 in firefox, 1200 in chrome */ document.documentelement.clientheight /* 533 */ window.innerheight /* 533 */ window.outerheight /* 596 in firefox, 900 in chrome */ the viewport was originally 1200 x 800 pixels. upon zooming in, the viewport became 800 x 533 pixels. this is the layout viewport. sticky headers or footers, with the following styles, will stick to the top and bottom of the layout viewport respectively. 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 header and footer stayed flu...
...e, and 1vw will be 1% of the width of the document. iframe { width: 50vw; } if the iframe is set to 50vw, it will be 50% of the width of the 1200px parent document in our example above, or 600px, with 1vw being 6px. when zoomed in, the iframe shrinks to 400px and 1vw becomes 4px. a width-based media query within the iframe document is relative to the iframe's viewport. @media screen and (min-width: 500px) { p { color: red; } } if the above css is included in the iframe, the paragraphs will become red when the user has zoomed in, but this style does not apply in the non-zoomed-in state. svg in an svg document, the viewport is the visible area of the svg image. you can set any height and width on an svg, but the whole image might not be visible. the area that is vis...
...ing a css pixel. svg also has an internal coordinate system defined via the viewbox attribute, which is not related to this viewport discussion. if you include an svg file in your html, the viewport of the svg is the initial containing block, or the width and height of the svg container. using the @media query in your svg's css is relative to that container, not the browser. @media screen and (min-width: 400px) and (max-width: 500px) { /* css goes here */ } generally, when you write the above media query, the styles are applied if the viewport, generally the browser window, is between 400px and 500px, inclusive. the width media query in the svg is based on the element in which the svg is contained — the <img> if the source is an svg file, the svg itself if the svg is included directly...
...width instead of the default 980px as the width of the screen, developers can include a viewport meta tag, like the following: <meta name="viewport" content="width=device-width"> the width property controls the size of the viewport. it should preferably be set to device-width, which is the width of the screen in css pixels at a scale of 100%. there are other properties, including maximum-scale, minimum-scale, and user-scalable, which control whether users can zoom the page in or out, but the default values are the best for accessibility and user experience, so these can be omitted. 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 ...
flex - CSS: Cascading Style Sheets
Web › CSS › flex
clone https://github.com/mdn/interactive-examples and send us a pull request. constituent properties this property is a shorthand for the following css properties: flex-grow flex-shrink flex-basis syntax /* keyword values */ flex: auto; flex: initial; flex: none; /* one value, unitless number: flex-grow */ flex: 2; /* one value, width/height: flex-basis */ flex: 10em; flex: 30%; flex: min-content; /* two values: flex-grow | flex-basis */ flex: 1 30px; /* two values: flex-grow | flex-shrink */ flex: 2 2; /* three values: flex-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. one-value syntax: the value must be one of: a <number>: in this...
...: then it is interpreted as <flex-shrink>. a valid value for width: then it is interpreted as <flex-basis>. three-value syntax: the values must be in the following order: a <number> for <flex-grow>. a <number> for <flex-shrink>. a valid value for width for <flex-basis>. values initial the item is sized according to its width and height properties. it shrinks to its minimum size to fit the container, but does not grow to absorb any extra free space in the flex container. this is equivalent to setting "flex: 0 1 auto". auto the item is sized according to its width and height properties, but grows to absorb any extra free space in the flex container, and shrinks to its minimum size to fit the container. this is equivalent to setting "flex: 1 1 auto". none the ...
... formal definition in...
...en; display: flex; margin: 1em; } .item { margin: 1em; padding: 0.5em; width: 110px; min-width: 0; background-color: #1b5385; color: white; font-family: monospace; font-size: 13px; } .initial { flex: initial; } .auto { flex: auto; } .none { flex: none; } .four { flex: 4; } .two { flex: 2; } .one { flex: 1; } by default flex items don't shrink below their minimum content size. to change this, set the item's min-width or min-height. formal definition initial valueas each of the properties of the shorthand:flex-grow: 0flex-shrink: 1flex-basis: autoapplies toflex items, including in-flow pseudo-elementsinheritednocomputed valueas each of the properties of the shorthand:flex-grow: as specifiedflex-shrink: as specifiedflex-basis: as specified, but with ...
font-size - CSS: Cascading Style Sheets
Web › CSS › font-size
s a very useful unit in css, since it automatically adapts its length relative to the font that the reader chooses to use. em and ex units on the font-size property are relative to the parent element's font size (unlike all other properties, where they're relative to the font size on the element). this means em units and percentages do the same thing for font-size. ...
...e relative to the font size on the element). this means em units and percentages do the same thing for font-size. one important fact to keep in mind: em values compound. take the following html and css: html { font-size: 62.5%; /* font-size 1em = 10px on default browser settings */ } span { font-size: 1.6em; } <div> <span>outer <span>inner</span> outer</span> </div> the result is: assuming that the browser's default font-size is 16px, the words “outer” would be rendered at 16px, but the word “inner” would be rendered at 25.6px. this is because the inner <span>'s font-size is 1.6em which is relative to its parent's font-size, which is in turn relative to its parent's font-size. this is often called compounding. rems rem values were invented in order to sidestep the compou...
...ve to its parent's font-size, which is in turn relative to its parent's font-size. this is often called compounding. rems rem values were invented in order to sidestep the compounding problem. rem values are relative to the root html element, not the parent element. in other words, it lets you specify a font size in a relative fashion without being affected by the size of the parent, thereby eliminating compounding. the css below is nearly identical to the previous example. the only exception is that the unit has been changed to rem. html { font-size: 62.5%; /* font-size 1em = 10px on default browser settings */ } span { font-size: 1.6rem; } then we apply this css to the same html, which looks like this: <span>outer <span>inner</span> outer</span> in this example, the words “o...
...al to the previous example. the only exception is that the unit has been changed to rem. html { font-size: 62.5%; /* font-size 1em = 10px on default browser settings */ } span { font-size: 1.6rem; } then we apply this css to the same html, which looks like this: <span>outer <span>inner</span> outer</span> in this example, the words “outer inner outer” are all displayed at 16px (assuming that the browser's font-size has been left at the default value of 10px). formal definition initial valuemediumapplies toall elements. it also applies to ::first-letter and ::first-line.inheritedyespercentagesrefer to the parent element's font sizecomputed valueas specified, but with relative lengths converted into absolute lengthsanimation typea length formal syntax <absolute-size> | <relat...
grid-template - CSS: Cascading Style Sheets
[main-top] "b b b" 1fr [main-bottom] / auto 1fr auto; /* global values */ grid-template: inherit; grid-template: initial; grid-template: unset; values none is a keyword that sets all three longhand properties to none, meaning there is no explicit grid. there are no named grid areas. rows and columns will be implicitly generated; their size will be determined by the grid-auto-rows and grid-auto-columns properties. <'grid-template-rows'> / <'grid-template-columns'> sets grid-template-rows and grid-template-columns to the specified values, and sets grid-template-areas to none. [ <line-names>? <string> <track-size>? <line-names>? ]+ [ / <explicit-track-list> ]? sets grid-template-areas to the strings listed, grid-template-rows to the track sizes fo...
...lute lengthsgrid-template-rows: as specified, but with relative lengths converted into absolute lengthsgrid-template-areas: as specifiedanimation typediscrete formal syntax none | [ <'grid-template-rows'> / <'grid-template-columns'> ] | [ <line-names>? <string> <track-size>? <line-names>? ...
...emplate-columns'> ] | [ <line-names>? <string> <track-size>? <line-names>? ]+ [ / <explicit-track-list> ]?where <line-names> = '[' <custom-ident>* ']'<track-size> = <track-breadth> | minmax( <inflexible-breadth> , <track-breadth> ) | fit-content( [ <length> | <percentage> ] )<explicit-track-list> = [ <line-names>? ...
... <explicit-track-list> ]?where <line-names> = '[' <custom-ident>* ']'<track-size> = <track-breadth> | minmax( <inflexible-breadth> , <track-breadth> ) | fit-content( [ <length> | <percentage> ] )<explicit-track-list> = [ <line-names>? ...
height - CSS: Cascading Style Sheets
Web › CSS › height
the height css property specifies the height of an element. by default, the property defines the height of the content area. if box-sizing is set to border-box, however, it instead determines the height of the border area. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. the min-height and max-height properties override height. syntax /* keyword value */ height: auto; /* <length> values */ height: 120px; height: 10em; /* <percentage> value */ height: 75%; /* global values */ height: inherit; height: initial; height: unset; values <length> defines the height as an absolute value. <percentage> defines the...
...; height: 10em; /* <percentage> value */ height: 75%; /* global values */ height: inherit; height: initial; height: unset; values <length> defines the height as an absolute value. <percentage> defines the height as a percentage of the containing block's height. auto the browser will calculate and select a height for the specified element. max-content the intrinsic preferred height. min-content the intrinsic minimum height. fit-content(<length-percentage>) uses the fit-content formula with the available space replaced by the specified argument, i.e. min(max-content, max(min-content, )). accessibility concerns ensure that elements set with a height are not truncated and/or do not obscure other content when the page is zoomed to increase text size. mdn understanding wcag,...
...f the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to auto. 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. </div> </div> css div { width: 250px; margin-bottom: 5px; ...
...ht: 25px; } #parent { height: 100px; } #child { height: 50%; width: 75%; } result specifications specification status comment css box sizing module level 4the definition of 'height' in that specification. editor's draft css box sizing module level 3the definition of 'height' in that specification. working draft added the max-content, min-content, fit-content keywords. css level 2 (revision 1)the definition of 'height' in that specification. recommendation adds support for the <length> values and precises on which element it applies to. css level 1the definition of 'height' in that specification. recommendation initial definition. ...
<length> - CSS: Cascading Style Sheets
Web › CSS › length
engths font-relative lengths define the <length> value in terms of the size of a particular character or font attribute in the font currently in effect in an element or its parent. note: these units, especially em and rem, are often used to create scalable layouts, which maintain the vertical rhythm of the page even when the user changes the font size. cap represents the "cap height" (nominal height of capital letters) of the element’s font. ch represents the width, or more precisely the advance measure, of the glyph "0" (zero, the unicode character u+0030) in the element's font. in the cases where it is impossible or impractical to determine the measure of the “0” glyph, it must be assumed to be 0.5em wide by 1em tall. em represents the calculated font-size of the elem...
...ion blocks. vh equal to 1% of the height of the viewport's initial containing block. vw equal to 1% of the width of the viewport's initial containing block. vi equal to 1% of the size of the initial containing block, in the direction of the root element’s inline axis. vb equal to 1% of the size of the initial containing block, in the direction of the root element’s block axis. vmin equal to the smaller of vw and vh. vmax equal to the larger of vw and vh. absolute length units absolute length units represent a physical measurement when the physical properties of the output medium are known, such as for print layout. this is done by anchoring one of the units to a physical unit, and then defining the others relative to it. the anchor is done differently for low-resoluti...
... that attempts to render at exactly one millimeter regardless of the size or resolution of the display. this is rarely actually what you want, but may be useful in particular for mobile devices. interpolation when animated, values of the <length> data type are interpolated as real, floating-point numbers. the interpolation happens on the calculated value. the speed of the interpolation is determined by the timing function associated with the animation. examples length unit comparison the following demo provides you with an input field in which you can enter a <length> value (e.g. 300px, 50%, 30vw) to set the width of a result bar that will appear below it once you've pressed return. this allows you to compare and contrast the effect of different length units. html <div class="outer">...
...m.focus(); }) result specifications specification status comment css values and units module level 4the definition of '<length>' in that specification. editor's draft adds the vi, vb, ic, lh, and rlh units. css values and units module level 3the definition of '<length>' in that specification. candidate recommendation adds the ch, rem, vw, vh, vmin, vmax, and q units. css level 2 (revision 1)the definition of '<length>' in that specification. recommendation explicit definition of the em, pt, pc, and px units. css level 1the definition of '<length>' in that specification. recommendation initial definition. implicit definition of the em, pt, pc, and px units. ...
mask-mode - CSS: Cascading Style Sheets
Web › CSS › mask-mode
the mask-mode css property sets whether the mask reference defined by mask-image is treated as a luminance or alpha mask. /* keyword values */ mask-mode: alpha; mask-mode: luminance; mask-mode: match-source; /* multiple values */ mask-mode: alpha, match-source; /* global values */ mask-mode: inherit; mask-mode: initial; mask-mode: unset; syntax the mask-mode property is specified as one or more of the keyword values listed below, separated by commas. values alpha this keyword indicates that the transparency (alpha channel) values of the mask layer image should be used as the mask values. luminance this keyword indicates that the luminance values of the mask layer image should be used as the mask values. match-source if the mask-image property is of type <mask-source>, the l...
... if it is of type <image>, the alpha values of the mask layer image should be used as the mask values. ...
...values. if it is of type <image>, the alpha values of the mask layer image should be used as the mask values. ...
... 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 value="match-source">match-source</option> </select> javascript var maskmode = document.getelementbyid("maskmode"); maskmode.addeventlistener("change", function (evt) { document.getelementbyid("masked").style.maskmode = evt.target.value; }); result specifications specification status comment css masking module level 1the de...
mask - CSS: Cascading Style Sheets
Web › CSS › mask
ng css properties: mask-clip mask-composite mask-image mask-mode mask-origin mask-position mask-repeat mask-size syntax /* keyword values */ mask: none; /* image values */ mask: url(mask.png); /* pixel image used as mask */ mask: url(masks.svg#star); /* element within svg graphic used as mask */ /* combined values */ mask: url(masks.svg#star) luminance; /* element within svg graphic used as luminance mask */ mask: url(masks.svg#star) 40px 20px; /* element within svg graphic used as mask positioned 40px from the top and 20px from the left */ mask: url(masks.svg#star) 0 0/50px 50px; /* element within svg graphic used as mask with a width and height of 50px */ mask: url(masks.svg#star) repeat-x; /* element within svg graph...
...rthand:mask-image: nonemask-mode: match-sourcemask-repeat: no-repeatmask-position: centermask-clip: border-boxmask-origin: border-boxmask-size: automask-composite: addapplies toall elements; in svg, it applies to container elements excluding the defs element and all graphics elementsinheritednopercentagesas each of the properties of the shorthand:mask-position: refer to size of mask painting area minus size of mask layer image (see the text for background-position)computed valueas each of the properties of the shorthand:mask-image: as specified, but with <url> values made absolutemask-mode: as specifiedmask-repeat: consists of two keywords, one per dimensionmask-position: consists of two keywords representing the origin and two offsets from that origin, each given as an absolute length (if gi...
...)<image-set()> = image-set( <image-set-option># )<element()> = element( <id-selector> )<paint()> = paint( <ide...
... candidate recommendation extends its usage to html elements. extends its syntax by making it a shorthand for the new mask-* properties defined in ...
overflow-block - CSS: Cascading Style Sheets
ly if one of overflow-x or overflow-y is neither visible nor clipanimation typediscrete formal syntax visible | hidden | clip | scroll | auto examples html <ul> <li><code>overflow-block:hidden</code> — hides the text outside the box <div id="div1"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </div> </li> <li><code>overflow-block:scroll</code> — always adds a scrollbar <div id="div2"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt u...
... laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </div> </li> <li><code>overflow-block:scroll</code> — always adds a scrollbar <div id="div2"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </div> </li> <li><code>overflow-block:visible</code> — displays the text outside the box if needed <div id="div3"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmo...
...uip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </div> </li> <li><code>overflow-block:visible</code> — displays the text outside the box if needed <div id="div3"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </div> </li> <li><code>overflow-block:auto</code> — on most browser, equivalent to <code>scroll</code> <div id="div4"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do ei...
...ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </div> </li> <li><code>overflow-block:auto</code> — on most browser, equivalent to <code>scroll</code> <div id="div4"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </div> </li> </ul> css #div1, #div2, #div3, #div4 { border: 1px solid black; width: 250px; height: 100px; } #div1 { overflow-block: hidden; margin-bottom: 120px;} #div2 { overflow-block...
overflow-y - CSS: Cascading Style Sheets
or overflow-y is neither visible nor clipanimation typediscrete formal syntax visible | hidden | clip | scroll | auto examples setting overflow-y behavior html <ul> <li><code>overflow-y:hidden</code> — hides the text outside the box <div id="div1"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </div> </li> <li><code>overflow-y:scroll</code> — always adds a scrollbar <div id="div2"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut la...
...amco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </div> </li> <li><code>overflow-y:scroll</code> — always adds a scrollbar <div id="div2"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </div> </li> <li><code>overflow-y:visible</code> — displays the text outside the box if needed <div id="div3"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod te...
...aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </div> </li> <li><code>overflow-y:visible</code> — displays the text outside the box if needed <div id="div3"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </div> </li> <li><code>overflow-y:auto</code> — on most browser, equivalent to <code>scroll</code> <div id="div4"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmo...
...uip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </div> </li> <li><code>overflow-y:auto</code> — on most browser, equivalent to <code>scroll</code> <div id="div4"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </div> </li> </ul> css #div1, #div2, #div3, #div4 { border: 1px solid black; width: 250px; height: 100px; } #div1 { overflow-y: hidden; margin-bottom: 12px;} #div2 { overflow-y: scroll;...
place-items - CSS: Cascading Style Sheets
of the properties of the shorthand:align-items: as specifiedjustify-items: as specifiedanimation typediscrete formal syntax <'align-items'> <'justify-items'>? ...
...ustify-items: as specifiedanimation typediscrete formal syntax <'align-items'> <'justify-items'>? ...
...ax <'align-items'> <'justify-items'>? ...
...ms in a flex container div > div { box-sizing: border-box; border: 2px solid #8c8c8c; width: 50px; display: flex; align-items: center; justify-content: center; } #item1 { background-color: #8cffa0; min-height: 30px; } #item2 { background-color: #a0c8ff; min-height: 50px; } #item3 { background-color: #ffa08c; min-height: 40px; } #item4 { background-color: #ffff8c; min-height: 60px; } #item5 { background-color: #ff8cff; min-height: 70px; } #item6 { background-color: #8cffff; min-height: 50px; font-size: 30px; } select { font-size: 16px; } .row { margin-top: 10px; } html <div id="container" class="flex"> <div id="item1">1</div> <div id="item2">2</div> <div id="item3">3</div> <div id="item4">4</div> <div id="item5">5</div> <div id=...
touch-action - CSS: Cascading Style Sheets
/* keyword values */ touch-action: auto; touch-action: none; touch-action: pan-x; touch-action: pan-left; touch-action: pan-right; touch-action: pan-y; touch-action: pan-up; touch-action: pan-down; touch-action: pinch-zoom; touch-action: manipulation; /* global values */ touch-action: inherit; touch-action: initial; touch-action: unset; by default, panning (scrolling) and pinching gestures are handled exclusively by the browser. ...
... touch-action will not have any impact on the behavior of the current gesture. syntax the touch-action property may be specified as either: one of the keywords auto, none, manipulation, or one of the keywords pan-x, pan-left, pan-right, and/or one of the keywords pan-y, pan-up, pan-down, plus optionally the keyword pinch-zoom. values auto enable browser handling of all panning and zooming gestures. none disable browser handling of all panning and zooming gestures. pan-x enable single-finger horizontal panning gestures. may be combined with pan-y, pan-up, pan-down and/or pinch-zoom. pan-y enable single-finger vertical panning gestures. may be combined with pan-x, pan-left, pan-right and/or pinch-zoom. manipulation enable panning and pinch zoom gestures, but disable additio...
... (pan-up) means that the user is dragging their finger downward on the screen surface, and likewise pan-left means the user is dragging their finger to the right. multiple directions may be combined except when there is a simpler representation (for example, "pan-left pan-right" is invalid since "pan-x" is simpler, but "pan-left pan-down" is valid). pinch-zoom enable multi-finger panning and zooming of the page. this may be combined with any of the pan- values. accessibility concerns a declaration of touch-action: none; may inhibit operating a browser's zooming capabilities. this will prevent people experiencing low vision conditions from being able to read and understand page content. mdn understanding wcag, guideline 1.4 explanations understanding success criterion 1.4.4 | understa...
... html <div id="map"></div> css #map { height: 400px; width: 400px; background: blue; touch-action: none; } result specifications specification status comment compatibility standardthe definition of 'touch-action' in that specification. living standard added pinch-zoom property value. pointer e...
Creating a cross-browser video player - Developer guides
this list is inserted after the <video> element, but inside the <figure> element (this is important for the fullscreen functionality, which is explained later on). ...
... the function checks the dir parameter, which indicates whether the volume is to be increased (+) or decreased (-) and acts accordingly. the function is defined to increase or decrease the video's volume attribute in steps of 0.1, ensuring that it doesn't go lower than 0 or higher than 1. progress when the <progress> element was defined above in the html, only two attributes were set, value and min, both being given a value of 0. the function of these attributes is self-explanatory, with min indicating the minimum allowed value of the progress element and value indicating its current value. it also needs to have a maximum value set so that it can display its range correctly, and this can be done via the max attribute, which needs to be set to the maximum playing time of the video. this is o...
...ss element's value attribute is set to the video's currenttime. the <span> element mentioned earlier, for browsers that do not support the <progress> element (e.g. internet explorer 9), is also updated at this time, setting its width to be a percentage of the total time played. this span has a solid css background colour, which helps it provide the same visual feedback as a <progress> element. coming back to the video.duration problem mentioned above, when the timeupdate event is raised, in most mobile browsers the video's duration attribute should now have the correct value. this can be taken advantage of to set the progress element's max attribute if it is currently not set: video.addeventlistener('timeupdate', function() { if (!progress.getattribute('max')) progress.setattribute('max'...
... if the browser is currently in fullscreen mode, then it must be exited and vice versa. support for the different prefixed versions of the relevant action are checked in order to call the correct one. interestingly document must be used for exiting/cancelling fullscreen mode, whereas any html element can request fullscreen mode, here the videocontainer is used as it also cont...
Localizations and character encodings - Developer guides
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 the 1990s, it was common to leave the encoding undeclared and to use a region-specific encoding that wasn't able to represent all of unicode. firefox needs a fallback encoding that it uses for non-conforming legacy content that doesn't declare its encoding. for most locales, the fallback encoding is windows-1252 (often called iso-8859-1), which was the encoding emitted by most windows applications in the 1990s and a superset of the encoding emitted by most unix applications in the 1990s as a deployed in the america has and in western europe. however, there are locales where web publishing was common...
...ion is obsolete, since the preference intl.charset.default no longer exists. the mapping from locales onto fallback encodings is now built into gecko itself. the fallback encoding is specified by the preference intl.charset.default in intl.properties. it should be set to the canonical name of the legacy encoding that users of the localizations are most likely to encounter when browsing non-conforming legacy web content that doesn't declare its encoding. note that the fallback encoding as defined by the previous sentence does not necessarily need to be able to represent the characters needed for the language of the localization! the fallback encoding should be left to windows-1252 for western european locales, north, central and south american locales, african locales, central asian locales ...
...indows-1252 as the fallback encoding. specifying the heuristic detection mode the heuristic detection mode is specified by the preference intl.charset.detector in intl.properties. the setting must be left blank for all locales other than russian, ukrainian and japanese. do not under any circumstances specify the "universal" detector. it is not actually universal despite its name! exception for minority languages if the localization is for minority language and the users are typically literate in the majority language of the region and read web content written in the majority language very often, it is appropriate to specify the fallback encoding and the heuristic detection mode to be the same as for the localization for the majority language of the region. for example, for a localization ...
... setting some encodings to be more easily selectable from the character encoding menu the preference intl.charsetmenu.browser.static in intl.properties makes some character encodings more easily available in the character encoding menu in the browser. ...
<h1>–<h6>: The HTML Section Heading elements - HTML: Hypertext Markup Language
because of this, it is important to not skip one or more heading levels. doing so may create confusion, as the person navigating this way may be left wondering where the missing heading is. don't <h1>heading level 1</h1> <h3>heading level 3</h3> <h4>heading level 4</h4> do <h1>heading level 1</h1> <h2>heading level 2</h2> <h3>heading level 3</h3> nesting headings...
...ding is. don't <h1>heading level 1</h1> <h3>heading level 3</h3> <h4>heading level 4</h4> do <h1>heading level 1</h1> <h2>heading level 2</h2> <h3>heading level 3</h3> nesting headings may be nested as subsections to reflect the organization of the content of the page. ...
... 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. this technique is useful for situations where there is more than one sectioning element on the same page. example <header> <nav aria-labelledby="primary-navigation"> <h2 id="primary-navigation">primary navigati...
...n"> <h2 id="footer-navigation">footer navigation</h2> <!-- navigation items --> </nav> </footer> in this example, screen reading technology would announce that there are two <nav> sections, one called "primary navigation" and one called "footer navigation". if labels were not provided, the person using screen reading software may have to investigate each nav element's contents to determine their purpose. using the aria-labelledby attribute labeling regions • page structure • w3c wai web accessibility tutorials specifications specification status comment html living standardthe definition of '<h1>, <h2>, <h3>, <h4>, <h5>, and <h6>' in that specification. living standard html5the definition of '<h1>, <h2>, <h3>, <h4>, <h5>, and ...
<link>: The External Resource Link element - HTML: Hypertext Markup Language
Web › HTML › Element › link
e disabled attribute is changed to false or removed. setting the disabled property in the dom causes the stylesheet to be removed from the document's document.stylesheets list. href this attribute specifies the url of the linked resource. a url can be absolute or relative. hreflang this attribute indicates the language of the linked resource. it is purely advisory. allowed values are determined by bcp47. use this attribute only if the href attribute is present. importance indicates the relative importance of the resource. priority hints are delegated using the values: auto: indicates no preference. the browser may use its own heuristics to decide the priority of the resource. high: indicates to the browser that the resource is of high priority. low: indicates to the browser...
...icon" href="favicon32.png"> conditionally loading resources with media queries you can provide a media type or query inside a media attribute; this resource will then only be loaded if the media condition is true. ...
...you can provide a media type or query inside a media attribute; this resource will then only be loaded if the media condition is true. ...
...his resource will then only be loaded if the media condition is true. ...
Browser detection using the user agent - HTTP
n feature detection is where you don't try to figure out which browser is rendering your page, but instead, you check to see if the specific feature you need is available. if it's not, you use a fallback. in those rare cases where behavior differs between browsers, instead of checking the user agent string, you should instead implement a test to detect how the browser implements the api and determine how to use it from that. an example of feature detection is as follows. in 2017, chrome unflagged experimental lookbehind support in regular expressions, but no other browser supported it. so, you might have thought to do this: // this code snippet splits a string in a special notation if (navigator.useragent.indexof("chrome") !== -1){ // yes! the user is suspected to support look-behind...
...ntil you can open up the dev tools side panel and resize the screen while the webpage looks smooth, fluid, and dynamically resized. the simplest way to do this is to separate all the code that moves content around based on screen size to a single function that is called when the page is loaded and at each resize event thereafter. if there is a lot calculated by this layout function before it determines the new layout of the page, then consider debouncing the event listener such that it is not called as often. also note that there is a huge difference between the media queries (max-width: 25em), not all and (min-width: 25em), and (max-width: 24.99em): (max-width: 25em) excludes (max-width: 25em), whereas not all and (min-width: 25em) includes (max-width: 25em). (max-width: 24.99em) is simply a...
...onsider debouncing the event listener such that it is not called as often. also note that there is a huge difference between the media queries (max-width: 25em), not all and (min-width: 25em), and (max-width: 24.99em): (max-width: 25em) excludes (max-width: 25em), whereas not all and (min-width: 25em) includes (max-width: 25em). (max-width: 24.99em) is simply a poor man's version of not all and (min-width: 25em): do not use (max-width: 24.99em) because the layout might break on very high font sizes on very high definition devices in the future. always be very deliberate about choosing the right media query and choosing the right >=, <=, >, or < in any corresponding javascript because it is very easy to get these mixed up, resulting in the website looking wonking right at the screen size wher...
...are specific for each browser. they indicate the os, but also often its version and information on the relying hardware (32 or 64 bits, or intel/ppc for mac). like in all cases, these strings may change in the future, one should use them only in conjunction with the detection of already released browsers. a technological survey must be in place to adapt the script when new browser versions are coming out. mobile, tablet or desktop the most common reason to perform user agent sniffing is to determine which type of device the browser runs on. the goal is to serve different html to different device types. never assume that a browser or a rendering engine only runs on one type of device. especially don't make different defaults for different browsers or rendering engines. never use the os ...
HTTP headers - HTTP
Web › HTTP › Headers
is used to transmit data only when the cache is out of date. if-unmodified-since makes the request conditional, and expects the entity to be transmitted only if it has not been modified after the given date. this ensures the coherence of a new fragment of a specific range with previous ones, or to implement an optimistic concurrency control system when modifying existing documents. vary determines how to match request headers to decide whether a cached response can be used rather than requesting a fresh one from the origin server. connection management connection controls whether the network connection stays open after the current transaction finishes. keep-alive controls how long a persistent connection should stay open. content negotiation accept informs the server about ...
...eflight request can be cached. access-control-request-headers used when issuing a preflight request to let the server know which http headers will be used when the actual request is made. access-control-request-method used when issuing a preflight request to let the server know which http method will be used when the actual request is made. origin indicates where a fetch originates from. timing-allow-origin specifies origins that are allowed to see values of attributes retrieved via features of the resource timing api, which would otherwise be reported as zero due to cross-origin restrictions. do not track dnt expresses the user's tracking preference. tk indicates the tracking status of the corresponding response. downloads content-disposition indicates if the resource t...
...ers. it is semantically equivalent to the html <link> element. push-policy a push-policy defines the server behaviour regarding push when processing a request. retry-after indicates how long the user agent should wait before making a follow-up request. signature the signature header field conveys a list of signatures for an exchange, each one accompanied by information about how to determine the authority of and refresh that signature. signed-headers the signed-headers header field identifies an ordered list of response header fields to include in a signature. server-timing communicates one or more metrics and descriptions for the given request-response cycle. service-worker-allowed used to remove the path restriction by including this header in the response of the service w...
...e service worker script. sourcemap links generated code to a source map. upgrade the relevant rfc document for the upgrade header field is rfc 7230, section 6.7. the standard establishes rules for upgrading or changing to a different protocol on the current client, server, transport protocol connection. for example, this header standard allows a client to change from http 1.1 to http 2.0, assuming the server decides to acknowledge and implement the upgrade header field. neither party is required to accept the terms specified in the upgrade header field. it can be used in both client and server headers. if the upgrade header field is specified, then the sender must also send the connection header field with the upgrade option specified. for details on the connection header field please see...
Details of the object model - JavaScript
properties, and manager is a subclass of employee that adds the reports property. in this case, an instance of the manager class would have all three properties: name, dept, and reports. javascript implements inheritance by allowing you to associate a prototypical object with any constructor function. so, you can create exactly the employee — manager example, but you use slightly different terminology. first you define the employee constructor function, specifying the name and dept properties. next, you define the manager constructor function, calling the employee constructor and specifying the reports property. finally, you assign a new object derived from employee.prototype as the prototype for the manager constructor function. then, when you create a new manager, it inherits the name a...
...rk object as a workerbee with the following statement: var mark = new workerbee; when javascript sees the new operator, it creates a new generic object and implicitly sets the value of the internal property [[prototype]] to the value of workerbee.prototype and passes this new object as the value of the this keyword to the workerbee constructor function. the internal [[prototype]] property determines the prototype chain used to return property values. once these properties are set, javascript returns the new object and the assignment statement sets the variable mark to that object. this process does not explicitly put values in the mark object (local values) for the properties that mark inherits from the prototype chain. when you ask for the value of a property, javascript first checks to ...
... in property inheritance revisited. because these constructors do not let you supply instance-specific values, this information is generic. the property values are the default ones shared by all new objects created from workerbee. you can, of course, change the values of any of these properties. so, you could give specific information for mark as follows: mark.name = 'doe, mark'; mark.dept = 'admin'; mark.projects = ['navigator']; adding properties in javascript, you can add properties to any object at run time. you are not constrained to use only the properties provided by the constructor function. to add a property that is specific to a single object, you assign a value to the object, as follows: mark.bonus = 3000; now, the mark object has a bonus property, but no other workerbee has...
...ype = new employee; var amy = new workerbee; employee.prototype.name = 'unknown'; in this case, the name property of amy becomes "unknown". as these examples show, if you want to have default values for object properties and you want to be able to change the default values at run time, you should set the properties in the constructor's prototype, not in the constructor function itself. determining instance relationships property lookup in javascript looks within an object's own properties and, if the property name is not found, it looks within the special object property __proto__. this continues recursively; the process is called "lookup in the prototype chain". the special property __proto__ is set when an object is constructed; it is set to the value of the constructor's prototype ...
Functions - JavaScript
ial(2); // b gets the value 2 c = factorial(3); // c gets the value 6 d = factorial(4); // d gets the value 24 e = factorial(5); // e gets the value 120 there are other ways to call functions. there are often cases where a function needs to be called dynamically, or the number of arguments to a function vary, or in which the context of the function call needs to be set to a specific object determined at runtime. it turns out that functions are themselves objects—and in turn, these objects have methods. (see the function object.) one of these, the apply() method, can be used to achieve this goal. function scope variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function. however, a function ...
...t, starting at 0. so, the first argument passed to a function would be arguments[0]. the total number of arguments is indicated by arguments.length. using the arguments object, you can call a function with more arguments than it is formally declared to accept. this is often useful if you don't know in advance how many arguments will be passed to the function. you can use arguments.length to determine the number of arguments actually passed to the function, and then access each argument using the arguments object. for example, consider a function that concatenates several strings. the only formal argument for the function is a string that specifies the characters that separate the items to concatenate. the function is defined as follows: function myconcat(separator) { var result = ''; //...
...6, 7, 9] var a3 = a.map(s => s.length); console.log(a3); // logs [8, 6, 7, 9] no separate this until arrow functions, every new function defined its own this value (a new object in the case of a constructor, undefined in strict mode function calls, the base object if the function is called as an "object method", etc.). this proved to be less than ideal with an object-oriented style of programming. function person() { // the person() constructor defines `this` as itself. this.age = 0; setinterval(function growup() { // in nonstrict mode, the growup() function defines `this` // as the global object, which is different from the `this` // defined by the person() constructor. this.age++; }, 1000); } var p = new person(); in ecmascript 3/5, this issue was fixed by a...
...++; // |this| properly refers to the person object }, 1000); } var p = new person(); predefined functions javascript has several top-level, built-in functions: eval() the eval() method evaluates javascript code represented as a string. uneval() the uneval() method creates a string representation of the source code of an object. isfinite() the global isfinite() function determines whether the passed value is a finite number. if needed, the parameter is first converted to a number. isnan() the isnan() function determines whether a value is nan or not. note: coercion inside the isnan function has interesting rules; you may alternatively want to use number.isnan(), as defined in ecmascript 2015, or you can use typeof to determine if the value is not-a-number. parse...
Indexed collections - JavaScript
ployee number. so emp[0] would be employee number zero, emp[1] employee number one, and so on. javascript does not have an explicit array data type. however, you can use the predefined array object and its methods to work with arrays in your applications. the array object has methods for manipulating arrays in various ways, such as joining, reversing, and sorting them. it has a property for determining the array length and other properties for use with regular expressions. creating an array the following statements create equivalent arrays: let arr = new array(element0, element1, ..., elementn) let arr = array(element0, element1, ..., elementn) let arr = [element0, element1, ..., elementn] element0, element1, ..., elementn is a list of values for the array's elements. when these values ...
...ence to the array. let myarray = new array('1', '2', '3') myarray.reverse() // transposes the array so that myarray = ["3", "2", "1"] sort() sorts the elements of an array in place, and returns a reference to the array. let myarray = new array('wind', 'rain', 'fire') myarray.sort() // sorts the array so that myarray = ["fire", "rain", "wind"] sort() can also take a callback function to determine how array elements are compared. the sort method (and others below) that take a callback are known as iterative methods, because they iterate over the entire array in some fashion. each one takes an optional second argument called thisobject. if provided, thisobject becomes the value of the this keyword inside the body of the callback function. if not provided, as with other cases where a funct...
...b.length - 1]) return 1; if (a[a.length - 1] == b[b.length - 1]) return 0; } myarray.sort(sortfn) // sorts the array so that myarray = ["wind","fire","rain"] if a is less than b by the sorting system, return -1 (or any negative number) if a is greater than b by the sorting system, return 1 (or any positive number) if a and b are considered equivalent, return 0. ...
...urn 0. indexof(searchelement[, fromindex]) searches the array for searchelement and returns the index of the first match. let a = ['a', 'b', 'a', 'b', 'a'] console.log(a.indexof('b')) // logs 1 // now try again, starting from after the last match console.log(a.indexof('b', 2)) // logs 3 console.log(a.indexof('z')) // logs -1, because 'z' was not found lastindexof(searchelement[, fromindex]) works like indexof, but starts at the end and searches backwards. let a = ['a', 'b', 'c', 'd', 'a', 'b'] console.log(a.lastindexof('b')) // logs 5 // now try again, starting from before the last match console.log(a.lastindexof('b', 4)) // logs 1 console.log(a.lastindexof('z')) // logs -1 foreach(callback[, thisobject]) executes callback on every array item and returns undefined.
JavaScript modules - JavaScript
r in our main.js file, we import the default function using this line: import randomsquare from './modules/square.js'; again, note the lack of curly braces. this is because there is only one default export allowed per module, and we know that randomsquare is it. the above line is basically shorthand for: import {default as randomsquare} from './modules/square.js'; note: the as syntax for renaming exported items is explained below in the renaming imports and exports section. avoiding naming conflicts so far, our canvas shape drawing modules seem to be working ok. but what happens if we try to add a module that deals with drawing another shape, like a circle or triangle? these shapes would probably have associated functions like draw(), reportarea(), etc. too; if we tried to import diff...
... deals with drawing another shape, like a circle or triangle? these shapes would probably have associated functions like draw(), reportarea(), etc. too; if we tried to import different functions of the same name into the same top-level module file, we'd end up with conflicts and errors. fortunately there are a number of ways to get around this. we'll look at these in the following sections. renaming imports and exports inside your import and export statement's curly braces, you can use the keyword as along with a new feature name, to change the identifying name you will use for a feature inside the top-level module. so for example, both of the following would do the same job, albeit in a slightly different way: // inside module.js export { function1 as newfunctionname, function2 as a...
... function1 as newfunctionname, function2 as anothernewfunctionname }; // inside main.js import { newfunctionname, anothernewfunctionname } from './modules/module.js'; // inside module.js export { function1, function2 }; // inside main.js import { function1 as newfunctionname, function2 as anothernewfunctionname } from './modules/module.js'; let's look at a real example. in our renaming directory you'll see the same module system as in the previous example, except that we've added circle.js and triangle.js modules to draw and report on circles and triangles. inside each of these modules, we've got features with the same names being exported, and therefore each has the same export statement at the bottom: export { name, draw, reportarea, reportperimeter }; when importing thes...
...ugh a server. github pages is ideal as it also serves .js files with the correct mime type. because .mjs is a non-standard file extension, some operating systems might not recognise it, or try to replace it with something else. for example, we found that macos was silently adding on .js to the end of .mjs files and then automatically hiding the file extension. so all of our files were actually coming out as x.mjs.js. once we turned off automatically hiding file extensions, and trained it to accept .mjs, it was ok. ...
Regular expression syntax cheatsheet - JavaScript
ed more information on a specific topic, please follow the link on the corresponding heading to access the full article or head to the guide. character classes if you are looking to contribute to this document, please also edit the original article characters meaning . has one of the following meanings: matches any single character except line terminators: \n, \r, \u2028 or \u2029. for example, /.y/ matches "my" and "ay", but not "yes", in "yes make my day". inside a character set, the dot loses its special meaning and matches a literal dot. note that the m multiline flag doesn't change the dot behavior. so to match a pattern across multiple lines, the character set [^] can be used — it will match any character including newl...
... in "yes make my day". inside a character set, the dot loses its special meaning and matches a literal dot. note that the m multiline flag doesn't change the dot behavior. so to match a pattern across multiple lines, the character set [^] can be used — it will match any character including newlines. es2018 added the s "dotall" flag, which allows the dot to also match line terminators. \d matches any digit (arabic numeral). equivalent to [0-9]. for example, /\d/ or /[0-9]/ matches "2" in "b2 is the suite number". \d matches any character that is not a digit (arabic numeral). equivalent to [^0-9]. for example, /\d/ or /[^0-9]/ matches "b" in "b2 is the suite number". \w matches any alphanumeric character from t...
...ample, /(?<=jack)sprat/ matches "sprat" only if it is preceded by "jack". /(?<=jack|tom)sprat/ matches "sprat" only if it is preceded by "jack" or "tom". however, neither "jack" nor "tom" is part of the match results. (?<!y)x negative lookbehind assertion: matches "x" only if "x" is not preceded by "y". for example, /(?<!-)\d+/ matches a number only if it is not preceded by a minus sign. /(?<!-)\d+/.exec('3') matches "3". /(?<!-)\d+/.exec('-3') match is not found because the number is preceded by the minus sign. groups and ranges if you are looking to contribute to this document, please also edit the original article characters meaning x|y matches either "x" or "y". for example, /green|red/ matches "green" in "green apple" an...
...the preceding item "x" 1 or more times. equivalent to {1,}. for example, /a+/ matches the "a" in "candy" and all the "a"'s in "caaaaaaandy". x? matches the preceding item "x" 0 or 1 times. for example, /e?le?/ matches the "el" in "angel" and the "le" in "angle." if used immediately after any of the quantifiers *, +, ?, or {}, makes the quantifier non-greedy (matching the minimum number of times), as opposed to the default, which is greedy (matching the maximum number of times). x{n} where "n" is a positive integer, matches exactly "n" occurrences of the preceding item "x". for example, /a{2}/ doesn't match the "a" in "candy", but it matches all of the "a"'s in "caandy", and the first two "a"'s in "caaandy". x{n,} where "n" is...
Working with objects - JavaScript
tween a name (or key) and a value. a property's value can be a function, in which case the property is known as a method. in addition to objects that are predefined in the browser, you can define your own objects. this chapter describes how to use objects, properties, functions, and methods, and how to create your own objects. objects overview objects in javascript, just as in many other programming languages, can be compared to objects in real life. the concept of objects in javascript can be understood with real life, tangible objects. in javascript, an object is a standalone entity, with properties and type. compare it with a cup, for example. a cup is an object, with properties. a cup has a color, a design, weight, a material it is made of, etc. the same way, javascript objects can hav...
...any valid javascript string, or anything that can be converted to a string, including the empty string. 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. this notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime). examples are as follows: // four variables are created and assigned in a single go, // separated by commas var myobj = new object(), str = 'mystring', rand = math.random(), obj = new object(); myobj.type = 'dot syntax'; myobj['date created'] = 'string with space'; myobj[str] = 'string value'; myo...
...e a constructor function and then instantiate an object invoking that function in conjunction with the new operator. using object initializers in addition to creating objects using a constructor function, you can create objects using an object initializer. using object initializers is sometimes referred to as creating objects with literal notation. "object initializer" is consistent with the terminology used by c++. the syntax for an object using an object initializer is: var obj = { property_1: value_1, // property_# may be an identifier... 2: value_2, // or a number... // ..., 'property n': value_n }; // or a string where obj is the name of the new object, each property_i is an identifier (either a name, a number, or a string litera...
...if you already go for the object initializer when defining a prototype you will probably most of the time choose the first form. this form is more compact and natural. however, if you need to add getters and setters later — because you did not write the prototype or particular object — then the second form is the only possible form. the second form probably best repre...
SyntaxError: missing variable name - JavaScript
we all have been there. ...
...we all have been there. ...
...we all have been there. var ohgodwhy = "foo"; reserved keywords can't be variable names there are a few variable names that are reserved keywords. you can't use these. ...
...we all have been there. var ohgodwhy = "foo"; reserved keywords can't be variable names there are a few variable names that are reserved keywords. you can't use these. ...
Date() constructor - JavaScript
ontain a number that represents milliseconds since 1 january 1970 utc. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax 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. if you simply call the date object directly, such as now = date(), the returned value is a string rather than a date object. parameters there are four basic forms for the date() constructor: no parameters when no parameters are provided, the newly-created d...
...tructor: no parameters when no parameters are provided, the newly-created date object represents the current date and time as of the time of instantiation. time value or timestamp number value an integer value representing the number of milliseconds since january 1, 1970, 00:00:00 utc (the ecmascript epoch, equivalent to the unix epoch), with leap seconds ignored. keep in mind that most unix timestamp functions are only accurate to the nearest second. timestamp string datestring a string value representing a date, specified in a format recognized by the date.parse() method. (these formats are ietf-compliant rfc 2822 timestamps, and also strings in a version of iso8601.) note: parsing of date strings with the date constructor (and date.parse()...
...ces and inconsistencies. support for rfc 2822 format strings is by convention only. support for iso 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as utc, not local. individual date and time component values given at least a year and month, this form of date() returns a date object whose component values (year, month, day, hour, minute, second, and millisecond) all come from the following parameters. any missing fields are given the lowest possible value (1 for day and 0 for every other component). year integer value representing the year. values from 0 to 99 map to the years 1900 to 1999. all other values are the actual year. see the example below. monthindex integer value representing the month,...
...from 0 to 99 map to the years 1900 to 1999. all other values are the actual year. see the example below. monthindex integer value representing the month, beginning with 0 for january to 11 for december. day optional integer value representing the day of the month. the default is 1. hours optional integer value representing the hour of the day. the default is 0 (midnight). minutes optional integer value representing the minute segment of a time. the default is 0 minutes past the hour. seconds optional integer value representing the second segment of a time. the default is 0 seconds past the minute. milliseconds optional integer value representing the millisecond segment of a time. the default is 0 milliseconds past the second. examples several wa...
Date.prototype.setHours() - JavaScript
e, and returns the number of milliseconds since january 1, 1970 00:00:00 utc until the time represented by the updated date instance. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax dateobj.sethours(hoursvalue[, minutesvalue[, secondsvalue[, msvalue]]]) versions prior to javascript 1.3 dateobj.sethours(hoursvalue) parameters hoursvalue ideally, an integer between 0 and 23, representing the hour. if a value greater than 23 is provided, the datetime will be incremented by the extra hours. minutesvalue optional. ideally, an integer between 0 and 59, representing the minutes. if a value greater than 59 ...
...avascript 1.3 dateobj.sethours(hoursvalue) parameters hoursvalue ideally, an integer between 0 and 23, representing the hour. if a value greater than 23 is provided, the datetime will be incremented by the extra hours. minutesvalue optional. ideally, an integer between 0 and 59, representing the minutes. if a value greater than 59 is provided, the datetime will be incremented by the extra minutes. secondsvalue optional. ideally, an integer between 0 and 59, representing the seconds. if a value greater than 59 is provided, the datetime will be incremented by the extra seconds. if you specify the secondsvalue parameter, you must also specify the minutesvalue. msvalue optional. ideally, a number between 0 and 999, representing the milliseconds. if a value greater than 999 is provided...
...rovided, the datetime will be incremented by the extra seconds. if you specify the secondsvalue parameter, you must also specify the minutesvalue. msvalue optional. ideally, a number between 0 and 999, representing the milliseconds. if a value greater than 999 is provided, the datetime will be incremented by the extra milliseconds. if you specify the msvalue parameter, you must also specify the minutesvalue and secondsvalue. return value the number of milliseconds between january 1, 1970 00:00:00 utc and the updated date. description if you do not specify the minutesvalue, secondsvalue, and msvalue parameters, the values returned from the getminutes(), getseconds(), and getmilliseconds() methods are used. if a parameter you specify is outside of the expected range, sethours() attempts...
...e updated date. description if you do not specify the minutesvalue, secondsvalue, and msvalue parameters, the values returned from the getminutes(), getseconds(), and getmilliseconds() methods are used. if a parameter you specify is outside of the expected range, sethours() attempts to update the date information in the date object accordingly. for example, if you use 100 for secondsvalue, the minutes will be incremented by 1 (minutesvalue + 1), and 40 will be used for seconds. examples using sethours() var thebigday = new date(); thebigday.sethours(7); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.sethours' in that specification. ...
Number - JavaScript
rns the number 123 number('123') === 123 // true number("unicorn") // nan number(undefined) // nan constructor number() creates a new number value. static properties number.epsilon the smallest interval between two representable numbers. number.max_safe_integer the maximum safe integer in javascript (253 - 1). number.max_value the largest positive representable number. number.min_safe_integer the minimum safe integer in javascript (-(253 - 1)). number.min_value the smallest positive representable number—that is, the positive number closest to zero (without actually being zero). number.nan special "not a number" value. number.negative_infinity special value representing negative infinity. returned on overflow. number.positive_infinity special value representing ...
...itive number closest to zero (without actually being zero). number.nan special "not a number" value. number.negative_infinity special value representing negative infinity. returned on overflow. number.positive_infinity special value representing infinity. returned on overflow. number.prototype allows the addition of properties to the number object. static methods number.isnan() determine whether the passed value is nan. number.isfinite() determine whether the passed value is a finite number. number.isinteger() determine whether the passed value is an integer. number.issafeinteger() determine whether the passed value is a safe integer (number between -(253 - 1) and 253 - 1). number.parsefloat(string) this is the same as the global parsefloat() function. number.parseint(s...
...ostring() method. number.prototype.valueof() returns the primitive value of the specified object. overrides the object.prototype.valueof() method. examples using the number object to assign values to numeric variables the following example uses the number object's properties to assign values to several numeric variables: const biggestnum = number.max_value const smallestnum = number.min_value const infinitenum = number.positive_infinity const neginfinitenum = number.negative_infinity const notanum = number.nan integer range for number the following example shows the minimum and maximum integer values that can be represented as number object. (more details on this are described in the ecmascript standard, chapter 6.1.6 the number type.) const biggestint = number.ma...
... a possible workaround is to use string instead. ...
eval() - JavaScript
h eval() was invoked, which can lead to possible attacks in ways to which the similar function is not susceptible. eval() is also slower than the alternatives, since it has to invoke the javascript interpreter, while many other constructs are optimized by modern js engines. additionally, modern javascript interpreters convert javascript to machine code. this means that any concept of variable naming gets obliterated. thus, any use of eval() will force the browser to do long expensive variable name lookups to figure out where the variable exists in the machine code and set its value. additonally, new things can be introduced to that variable through eval() such as changing the type of that variable, forcing the browser to re-evaluate all of the generated machine code to compensate. fortunat...
...efunction(obj){ return function('"use strict";return (' + obj + ')')()( date ); } console.log(runcodewithdatefunction( "function(date){ return date(5) }" )) the code above may seem inefficiently slow because of the triple nested function, but let's analyze the benefits of the above efficient method: it allows the code in the string passed to runcodewithdatefunction() to be minified. function call overhead is minimal, making the far smaller code size well worth the benefit function() more easily allows your code to utilize the performance buttering "use strict"; the code does not use eval(), making it orders of magnitude faster than otherwise. lastly, let's examine minification. with using function() as shown above, you can minify the code string passed to runcodew...
...rth the benefit function() more easily allows your code to utilize the performance buttering "use strict"; the code does not use eval(), making it orders of magnitude faster than otherwise. lastly, let's examine minification. with using function() as shown above, you can minify the code string passed to runcodewithdatefunction() far more efficiently because the function arguments names can be minified too as seen in the minified code below. console.log(function('"use strict";return(function(a){return a(5)})')()(function(a){ return"monday tuesday wednesday thursday friday saturday sunday".split(" ")[a%7||0]})); there are also additional safer (and faster!) alternatives to eval() or function() for common use-cases. accessing member properties you should not use eval() to convert propert...
... {c: 0}}}; var proppath = getproppath(); // returns e.g. "a.b.c" var result = setdescendantprop(obj, proppath, 1); // obj.a.b.c will now be 1 use functions instead of evaluating snippets of code javascript has first-class functions, which means you can pass functions as arguments to other apis, store them in variables and objects' properties, and so on. many dom apis are designed with this in mind, so you can (and should) write: // instead of settimeout(" ... ", 1000) use: settimeout(function() { ... }, 1000); // instead of elt.setattribute("onclick", "...") use: elt.addeventlistener('click', function() { ... } , false); closures are also helpful as a way to create parameterized functions without concatenating strings. parsing json (converting strings to javascript objects) if the s...
delete operator - JavaScript
an expression evaluating to an object. property the property to delete. return value true for all cases except when the property is an own non-configurable property, in which case, false is returned in non-strict mode. exceptions throws typeerror in strict mode if the property is an own non-configurable property. description unlike what common belief suggests (perhaps due to other programming languages like delete in c++), the delete operator has nothing to do with directly freeing memory. memory management is done indirectly via breaking references. see the memory management page for more details. the delete operator removes a given property from an object. on successful deletion, it will return true, else false will be returned. however, it is important to consider the following ...
...(delete variable2); // false function func(param) { // syntaxerror in strict mode. console.log(delete param); // false } // syntaxerror in strict mode. console.log(delete func); // false cross-browser notes although ecmascript makes iteration order of objects implementation-dependent, it may appear that all major browsers support an iteration order based on the earliest added property coming first (at least for properties not on the prototype). 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. in explorer, while the property value is indeed set to undefined, if one later adds back a property with the same name, the prop...
...e iteration sequence as one might expect after having deleted the property and then added it back. if you want to use an ordered associative array in a cross-browser environment, use a map object if available, or simulate this structure with two separate arrays (one for the keys and the other for the values), or build an array of single-property objects, etc. examples // creates the property adminname on the global scope. adminname = 'xyz'; // creates the property empcount on the global scope. // since we are using var, this is marked as non-configurable. the same is true of let and const. var empcount = 43; employeedetails = { name: 'xyz', age: 5, designation: 'developer' }; // adminname is a property of the global scope. // it can be deleted since it is created without var, // a...
...xyz'; // creates the property empcount on the global scope. // since we are using var, this is marked as non-configurable. the same is true of let and const. var empcount = 43; employeedetails = { name: 'xyz', age: 5, designation: 'developer' }; // adminname is a property of the global scope. // it can be deleted since it is created without var, // and is therefore configurable. delete adminname; // returns true // on the contrary, empcount is not configurable // since var was used. delete empcount; // returns false // delete can be used to remove properties from objects. delete employeedetails.name; // returns true // even when the property does not exist, delete returns "true". delete employeedetails.salary; // returns true // delete does not affect built-in static ...
MathML attribute reference - MathML
table columns. unimplemented crossout <mscarry> specifies what kind of line is drawn to cross out carries. unimplemented decimalpoint <mstyle> if the decimalpoint value is used to specify the alignment, this attribute is specifying the character for the alignment point within <mstack> and <mtable> columns. denomalign <mfrac> the alignment of the denominator under the fraction. depth <mpadded> sets or increments the depth. see length. dir <math>, <mi>, <mo>, <mrow>, <ms>, <mtext> the text direction. possible values are either ltr (left to right) or rtl (right to left). display <math> specifies the rendering mode. the values block and inline are allowed. displaystyle <mstyle>, <mtable> a ...
...tml color names. mathcolor all the text color. you can use #rgb, #rrggbb and html color names. mathsize <mi>, <mn>, <mo>, <ms>, <mtext> the size of the content. mathvariant <mi>, <mn>, <mo>, <ms>, <mtext> the logical class of the identifier, which varies in typography. maxsize <mo> the maximum size of the operator. unimplemented minlabelspacing <mtable> a length value specifing the minimum space between a label and the adjacent cell in the row. minsize <mo> the minimum size of the operator. movablelimits <mo> specifies whether attached under- and overscripts move to sub- and superscript positions. notation <menclose> a list of notations, separated by white space, to apply to...
...ative integer value that indicates on how many rows does the cell extend. rspace <mo> the amount of space after the operator. rquote <ms> the closing quote mark (depends on dir) to enclose the content. the default value is "&quot;". scriptlevel <mstyle> controls mostly the font-size. the higher the scriptlevel, the smaller the font size. scriptminsize <mstyle> specifies a minimum font size allowed due to changes in scriptlevel. scriptsizemultiplier <mstyle> specifies the multiplier to be used to adjust font size due to changes in scriptlevel. selection <maction> the child element which is addressed by the action. separator <mo> there is no visual effect for this attribute, but it specifies...
...ide <mtable> specifies the position where <mlabeledtr> label elements should be placed. unimplemented src <mglyph> the location of the image resource. unimplemented stackalign <mstack> stretchy <mo> specifies whether the operator stretches to the size of the adjacent element. subscriptshift <mmultiscripts>, <msub>, <msubsup> the minimum space by which to shift the subscript below the baseline of the expression. supscriptshift <mmultiscripts>, <msup>, <msubsup> the minimum space by which to shift the superscript above the baseline of the expression. symmetric <mo> if stretchy is true, this attribute specifies whether the operator should be vertically symmetric around the imaginary math axis (ce...
<mfrac> - MathML
Web › MathML › Element › mfrac
possible values are: left, center (default), and right. ...
...possible values are: left, center (default), and right. ...
...possible values are: left, center (default), and right. ...
...possible values are: left, center (default), and right. this attribute is deprecated and will be removed in the future. use css text-align instead. href used to set a hyperlink to a specified uri. linethickness the thickness of the horizontal fraction line. this attributes accepts any length values. ...
baseline-shift - SVG: Scalable Vector Graphics
the baseline-shift attribute allows repositioning of the dominant-baseline relative to the dominant-baseline of the parent text content element. the shifted object might be a sub- or superscript. note: as a presentation attribute baseline-shift can be used as a css property. note: this property is going to be deprecated and authors are advised to use vertical-align instead. ...
...: this property is going to be deprecated and authors are advised to use vertical-align instead. ...
...-align instead. as a presentation attribute, it can be applied to any element but it has effect only on the following four elements: <altglyph>, <textpath>, <tref>, and <tspan> usage notes value <length-percentage> | sub | super default value 0 animatable yes sub the dominant-baseline is shifted to the default position for subscripts. super the dominant-baseline is shifted to the default position for superscripts. ...
...>, and <tspan> usage notes value <length-percentage> | sub | super default value 0 animatable yes sub the dominant-baseline is shifted to the default position for subscripts. super the dominant-baseline is shifted to the default position for superscripts. <length-percentage> a length value raises (positive value) or lowers (negative value) the dominant-baseline of the parent text content element by the specified length. a percentage value raises (positive value) or lowers (negative value) the dominant-baseline of the parent text content element by the specified percentage of the line-height. specifications specification status comment css inline layoutthe definition of 'alignment-baseline' in that specificatio...
SVG Attribute reference - SVG: Scalable Vector Graphics
Web › SVG › Attribute
etype autoreverse azimuth b basefrequency baseline-shift baseprofile bbox begin bias by c calcmode cap-height class clip clippathunits clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering contentscripttype contentstyletype cursor cx cy d d decelerate descent diffuseconstant direction display divisor dominant-baseline dur dx dy e edgemode elevation enable-background end exponent externalresourcesrequired f fill fill-opacity fill-rule filter filterres filterunits flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight format from fr fx fy g g1 g2 glyph-name glyph-orientation-horizontal glyph-orien...
...-x i id ideographic image-rendering in in2 intercept k k k1 k2 k3 k4 kernelmatrix kernelunitlength kerning keypoints keysplines keytimes l lang lengthadjust letter-spacing lighting-color limitingconeangle local m marker-end marker-mid marker-start markerheight markerunits markerwidth mask maskcontentunits maskunits mathematical max media method min mode n name numoctaves o offset opacity operator order orient orientation origin overflow overline-position overline-thickness p panose-1 paint-order path pathlength patterncontentunits patterntransform patternunits ping pointer-events points pointsatx pointsaty pointsatz preservealpha preserveaspectratio primitiveunits r r radius referrerpolicy re...
...nguage. xlink attributes xlink:href, xlink:type, xlink:role, xlink:arcrole, xlink:title, xlink:show, xlink:actuate presentation attributes note that all svg presentation attributes can be used as css properties. ...
...oration, text-rendering, transform, transform-origin, unicode-bidi, vector-effect, visibility, word-spacing, writing-mode filters attributes filter primitive attributes height, result, width, x, y transfer function attributes type, tablevalues, slope, intercept, amplitude, exponent, offset animation attributes animation attribute target attributes attributetype, attributename animation timing attributes begin, dur, end, min, max, restart, repeatcount, repeatdur, fill animation value attributes calcmode, values, keytimes, keysplines, from, to, by, autoreverse, accelerate, decelerate animation addition attributes additive, accumulate event attributes animation event attributes onbegin, onend, onrepeat document event attributes onabort, onerror, onresize, onscroll, onunload g...
<pattern> - SVG: Scalable Vector Graphics
Web › SVG › Element › pattern
value type: <length>|<percentage>; default value: 0; animatable: yes href this attribute reference a template pattern that provides default values for the <pattern> attributes. value type: <url>; default value: none; animatable: yes patterncontentunits this attribute defines the coordinate system for the contents of the <pattern>. value type: userspaceonus...
...ault value: none; animatable: yes patternunits this attribute defines the coordinate system for attributes x, y, width , and height. value type: userspaceonuse|objectboundingbox; default value: objectboundingbox; animatable: yes preserveaspectratio this attribute defines how the svg fragment must be deformed if it is embedded in a container with a different aspect ratio. value type: (none| xminymin| xmidymin| xmaxymin| xminymid| xmidymid| xmaxymid| xminymax| xmidymax| xmaxymax) (meet|slice)? ; default value: xmidymid meet; animatable: yes viewbox this attribute defines the bound of the svg viewport for the pattern fragment. value type: <list-of-numbers> ; default value: none; animatable: yes width this attribute determines the width of the pattern tile. value type: <length>|<perce...
...midymax| xmaxymax) (meet|slice)? ; default value: xmidymid meet; animatable: yes viewbox this attribute defines the bound of the svg viewport for the pattern fragment. value type: <list-of-numbers> ; default value: none; animatable: yes width this attribute determines the width of the pattern tile. value type: <length>|<percentage> ; default value: 0; animatable: yes x this attribute determines the x coordinate shift of the pattern tile. value type: <length>|<percentage> ; default value: 0; animatable: yes xlink:href deprecated since svg 2 this attribute reference a template pattern that provides default values for the <pattern> attributes. value type: <url>; default value: none; animatable: yes note: for browsers implementing href, if both href and xlink:href are set, xlink:href...
...ercentage> ; default value: 0; animatable: yes xlink:href deprecated since svg 2 this attribute reference a template pattern that provides default values for the <pattern> attributes. value type: <url>; default value: none; animatable: yes note: for browsers implementing href, if both href and xlink:href are set, xlink:href will be ignored and only href will be used. y this attribute determines the y coordinate shift of the pattern tile. value type: <length>|<percentage> ; default value: 0; animatable: yes global attributes core attributes most notably: id, tabindex styling attributes class, style conditional processing attributes most notably: requiredextensions, systemlanguage presentation attributes most notably: clip-path, clip-rule, color, color-interpolation, color-...
Loading and running WebAssembly code - WebAssembly
ly.compile/webassembly.instantiate methods require you to create an arraybuffer containing your webassembly module binary after fetching the raw bytes, and then compile/instantiate it. this is analogous to new function(string), except that we are substituting a string of characters (javascript source code) with an array buffer of bytes (webassembly source code). the newer webassembly.compilestreaming/webassembly.instantiatestreaming methods are a lot more efficient — they perform their actions directly on the raw stream of bytes coming from the network, cutting out the need for the arraybuffer step. so how do we get those bytes into an array buffer and compiled? the following sections explain. using fetch fetch is a convenient, modern api for fetching network resources. the quickest, m...
...ir actions directly on the raw stream of bytes coming from the network, cutting out the need for the arraybuffer step. so how do we get those bytes into an array buffer and compiled? the following sections explain. 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! }); if we used the older webassembly.instantiate() method, which doesn'...
...ument, and returns a promise directly containing the instance object as the result. see second overload example. running your webassembly code once you've got your webassembly instance available in your javascript, you can then start using features of it that have been exported via the webassembly.instance.exports property. ...
... exported table: var table = obj.instance.exports.table; console.log(table.get(0)()); }) note: for more information on how exporting from a webassembly module works, have a read of using the webassembly javascript api, and understanding webassembly text format. using xmlhttprequest xmlhttprequest is somewhat older than fetch, but can still be happily used to get a typed array. again, assuming our module is called simple.wasm: create a new xmlhttprequest() instance, and use its open() method to open a request, setting the request method to get, and declaring the path to the file we want to fetch. the key part of this is to set the response type to 'arraybuffer' using the responsetype property. next, send the request using xmlhttprequest.send(). we then use the onload event handl...
Compiling from Rust to WebAssembly - WebAssembly
the latest stable rust release, which you can use for general rust development. rustup installs rustc, the rust compiler, as well as cargo, rust's package manager, rust-std, rust's standard libraries, and some helpful docs — rust-docs. note: pay attention to the post-install note about needing cargo's bin directory in your system path. ...
... to get node.js and npm, go to the get npm! page and follow the instructions. ...
...n::prelude::*; #[wasm_bindgen] extern { pub fn alert(s: &str); } #[wasm_bindgen] pub fn greet(name: &str) { alert(&format!("hello, {}!", name)); } this is the contents of our rust project. it has three main parts; let's talk about them in turn. we give a high-level explanation here, and gloss over some details; to learn more about rust, please check the free online book the rust programming language. using wasm-bindgen to communicate between rust and javascript the first part looks like this: use wasm_bindgen::prelude::*; libraries are called "crates" in rust. get it? cargo ships crates. the third line contains a use command, which imports code from a library into your code. in this case, we're importing everything in the wasm_bindgen::prelude module. we use these features in...
...into what that means in this tutorial. for more, consult the cargo and rust linkage documentation. the last section is the [dependencies] section. here's where we tell cargo what version of wasm-bindgen we want to depend on; in this case, that's any 0.2.z version (but not 0.3.0 or above). building the package now that we've got everything set up, let's build the package. type this into your terminal: $ wasm-pack build this does a number of things (and they take a lot of time, especially the first time you run wasm-pack). to learn about them in detail, check out this blog post on mozilla hacks. in short, wasm-pack build: compiles your rust code to webassembly. runs wasm-bindgen on that webassembly, generating a javascript file that wraps up that webassembly file into a module npm can ...
Classes and Inheritance - Archive of obsolete content
d by creating a constructor function for that class. to illustrate this, let's define a simple constructor for a class shape: function shape(x, y) { this.x = x; this.y = y; } we can now use this constructor to create instances of shape: let shape = new shape(2, 3); shape instanceof shape; // => true shape.x; // => 2 shape.y; // => 3 the keyword new tells javascript that we are performing a constructor call. constructor calls differ from ordinary function calls in that javascript automatically creates a new object and binds it to the keyword this for the duration of the call. moreover, if the constructor does not return a value, the result of the call defaults to the value of this. constructors are just ordinary functions, however, so it is perfectly legal to perform ordinary fun...
...cle.prototype = object.create(shape.prototype); now when javascript looks for the method draw on an instance of circle, it first looks for it on the object itself. when it cannot find the property there, it looks for it on the prototype of circle. when it cannot find the property there either, it looks for it on shape, at which point the lookup succeeds. the resulting behavior is what we were aiming for. inheritance and instanceof the single line of code we added in the previous section solved the problem with prototypes, but introduced a new problem with the instanceof operator. consider the following: let circle = circle(2, 3, 5); circle instanceof shape; // => false since instances of circle inherit from shape, we definitely want the result of this expression to be true. to understa...
... classes in the add-on sdk we have shown how to emulate classical inheritance in javascript using constructors and prototypes. however, as we have seen, this takes a significant amount of boilerplate code. the add-on sdk team consists of highly trained professionals, but they are also lazy: that is why the sdk contains a helper function that handles this boilerplate code for us. it is defi...
Content Processes - Archive of obsolete content
to understand this article, it's probably best to read it as if content and add-on processes actually exist. ...
...owards a multiprocess model. in this model, the ui would be rendered in one process (called the chrome process), whereas each tab and each add-on would run in their own dedicated process (called content and add-on processes, respectively). the project behind this refactor was known as electrolysis, or e10s. although e10s has now been suspended, the sdk was designed with this multiprocess model in mind. afterwards, it was decided to keep the design the way it is: even though it's no longer necessary, it turns out that from a security point of view there are several important advantages to thinking about content and add-on code as living in different processes. many add-ons have to interact with content. the problem with the multiprocess model is that add-ons and content are now in different p...
...he window object via a content script is sometimes inconvenient, so it is possible to circumvent this: by defining the property on window.wrappedobject, the property is defined on the underlying object, rather than the wrapper itself. this feature should only be used when you really need it, however. a few notes on security as we stated earlier, the sdk was designed with multiprocess support in mind, despite the fact that work on implementing this in firefox has currently been suspended. 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 scri...
/loader - Archive of obsolete content
be unable to resolve the required module's location. id add-on debugging requires knowing which objects belong to which add-on. when created with this option, loader will transparently mark all new global objects with the provided value. all together all of these options can be combined to configure the loader for a specific use case. don't get too excited about configuration options, keep in mind that modules are more useful if they can be used across loader instances. unless you have specific needs it's best to stick to an sdk-compatible configuration, like this: let { loader } = require('toolkit/loader'); let loader = loader({ // please note: illustrated `paths` is expected to be a default base, // but depending on your use case you may have more mappings. paths: { // resolv...
...nvironment with a different state to test how specific modules handle unloads. @loader/unload this pseudo module exposes an object that is unique per loader instance. it is used as a subject for observer notification to allow use of the observer service for defining hooks reacting on the unload of a specific loader. the sdk builds a higher level api on top of this for handling unloads and performing cleanup: let unloadsubject = require('@loader/unload'); let observerservice = cc['@mozilla.org/observer-service;1']. getservice(ci.nsiobserverservice); let observer = { observe: function onunload(subject, topic, reason) { // if this module is unloaded then `subject.wrappedjsobject` will be // `unloadsubject`. `topic` will be `'sdk:loader:destroy'`, and // `reason` w...
...at. in such cases you can create a requirer module instance and a version of require exposed to it with this function: let requirer = module(requirerid, requireruri); let require = require(loader, requirer); let boostrap = require(bootstrapid); resolveuri() this function is used by the loader to resolve module uri from an id using a mapping array generated from the loader's paths option. ...
Displaying annotations - Archive of obsolete content
r).attr('annotation', annotation.annotationtext); } save this in data as matcher.js. ...
...> <head> <title>annotation</title> <style media="all" type="text/css"> body { font: 100% arial, helvetica, sans-serif; background-color: #f5f5f5; } div { text-align:left; } </style> </head> <body> <div id="annotation"> </div> </body> </html> save this in data/annotation as annotation.html. annotation panel content script the annotation panel has a minimal content script that sets the text: self.on('message', function(message) { $('#annotation').text(message); }); save this in data/annotation as annotation.js. updating main.js finally, update main.js with the code to construct the annotation panel: var annotation = panels.panel({ width: 200, height: 180, contenturl: data.url('annotation/annotation.html'), contentscriptfile: [data...
... that sets the text: self.on('message', function(message) { $('#annotation').text(message); }); save this in data/annotation as annotation.js. updating main.js finally, update main.js with the code to construct the annotation panel: var annotation = panels.panel({ width: 200, height: 180, contenturl: data.url('annotation/annotation.html'), contentscriptfile: [data.url('jquery-1.4.2.min.js'), data.url('annotation/annotation.js')], onshow: function() { this.postmessage(this.content); } }); execute cfx run one last time. activate the annotator and enter an annotation. you should see a yellow border around the item you annotated: when you move your mouse over the item, the annotation should appear: obviously this add-on isn't complete yet. it could ...
Bootstrapped extensions - Archive of obsolete content
unction is called, it must manually inject its user interface and other behavior into the application. similarly, when its shutdown() function is called, it must remove anything that it has added to the application, as well as all references to any of its objects. there are several scenarios in which the startup() function may be called; for example: when the extension is first installed, assuming that it's both compatible with the application and is enabled. when the extension becomes enabled using the add-ons manager window. when the application is started up, if the extension is enabled and compatible with the application. some examples of when the shutdown() function may be called: when the extension is uninstalled, if it's currently enabled. when the extension becomes disable...
... method being called. add-on debugger from firefox 31 onwards, you can use the add-on debugger to debug bootstrapped add-ons. localization (l10n) localizing bootstrapped add-ons is very much the same since firefox 7, as that is when chrome.manifest compatibility landed. js and jsm files - using property files to localize your .js and .jsm files you have to use property files. the absolute minimum needed here is: file: install.rdf file: chrome.manifest file: bootstrap.js folder: locale folder: valid_locale_here file: anything.properties in the locale folder you must have folders for each of the languages you want to provide; each folder must be named a valid locale (ex: en-us). inside this folder must be a property file. inside the chrome.manifest ...
...three changes you must make: you have to change the html file's extension to be .xhtml the doctype must be defined point to a dtd file in your locale folder such as: <!doctype html system "chrome://l10n/locale/mozilla.dtd"> must add xmlns attribute to html tag for example: <html xmlns="http://www.w3.org/1999/xhtml"> if you have multiple dtd files read on here: using multiple dtds the bare minimum needed is: file: install.rdf file: chrome.manifest file: bootstrap.js folder: locale folder: valid_locale_here file: anything.dtd the chrome.manifest file must include a definition for content for example: content name_of_your_addon ./ the chrome.manifest file must also include a line pointing to the locale, just like in the above property section, if yo...
StringView - Archive of obsolete content
anscrtype & 4) { /* input is string */ vsource = vinput; noutptlen = ninptlen = vsource.length; ntranscrtype ^= this.encoding === "utf-32" ? 0 : 2; /* ...or...: ntranscrtype ^= number(this.encoding !== "utf-32") << 1; */ nstartidx = ncharstart = noffset ? math.max((noutptlen + noffset) % noutptlen, 0) : 0; nendidx = ncharend = (number.isinteger(nlength) ? ...
... noutptlen, 0) : 0; nendidx = ncharend = (number.isinteger(nlength) ? math.min(math.max(nlength, 0) + nstartidx, noutptlen) : noutptlen) - 1; } else { /* input is stringview */ vsource = vinput.rawdata; ninptlen = vinput.makeindex(); nstartidx = ncharstart = noffset ? math.max((ninptlen + noffset) % ninptlen, 0) : 0; noutptlen = number.isinteger(nlength) ? ...
...ike this: var mybuffer = new stringview(1024); /* mybuffer: 12 character followed by 1012 nulls... */ var mycontent = new stringview("hello world!"); mybuffer.rawdata.set(mycontent.rawdata, mycontent.rawdata.length); stringview is a constructor and a collection of methods whose aim is to work strictly on arrays of numbers, rather than on creating new immutable javascript strings. keep it in mind when you try to extend its prototype. since stringview, unlike c strings, has a length property, there is no reason to add a null codepoint ('\0') after the termination of a string. stringview has been proposed as strawman for es2015 on ecmascript bugs. everyone can participate in the discussion at bug 1557 or at esdiscuss. ...
xml:base support in old browsers - Archive of obsolete content
however, it is working in some of the cases tested. ...
...however, it is working in some of the cases tested. ...
... // var ns = 'http://www.w3.org/xml/1998/namespace'; ...
Extension Etiquette - Archive of obsolete content
ask for focus, they should get it. overriding their request isn't very nice. about dialogs there is a default popup about dialog that is created from install.rdf data; creating a new xul about box is usually unnecessary. you can decrease download size by omitting a customized about box. make one only if you have a special feature that needs to be included — for example, a custom updater. theming if you have xul buttons in your extension that do functions similar to ones that already exist in a browser — for example, a feed reader that reloads and stops — use icons from the browser's theme. the icons makes the extension lighter, while providing more consistency, especially for users using different themes. extension icons unique icons are usually worth their download weight. they ...
...out: page urls. xpcom contract ids, which are often registered in chrome.manifest files. while these are among the most common examples of namespaces in which conflicts can occur, there are many others. in general, care must be taken whenever defining a name anywhere that other code might do likewise. strategies to avoid such conflicts include: avoid shared namespaces where possible many naming conflicts are best avoided by simply not sharing namespaces. scripts can be loaded into their own globals, such as commonjs modules, javascript modules, or sandboxes, to avoid most global variable and prototype conflicts. expando properties are best avoided using tools such as weakmaps. prefix names in shared namespaces when shared namespaces can't be avoided, the simplest solution to preven...
...ed noconflict, or similar, which revert any global variables they've declared, and return the object itself. for instance, calling jquery.noconflict(true) will remove the window.jquery and window.$ variables, and return the jquery object itself, for future use by the caller. when available, these methods should always be used to prevent conflicts with third-party code. names and metadata naming be creative! don't be redundant and include "extension," "mozilla/firefox/thunderbird," or the version number in the name. be original! descriptions use something that is descriptive, but that would fit in the default add-on manager width. the mozilla extensions (inspector/reporter/talkback) believe starting with a verb is the best way. for example, "does an action in the browser." documenta...
Chapter 1: Introduction to Extensions - Archive of obsolete content
cript enables and disables javascript execution on a site-by-site basis. web application integration extensions fixme: update this. the use the apis of certain web applications to provide certain pieces of information. new feature extensions fixme: update this. extensions can add completely new features to firefox. this class of extension requires a greater level of knowledge and programming ability. greasemonkey userchrome.js both of these provide an environment for running user scripts (javascript) in firefox itself, where the scripts can target specific websites. adblock plus blocks the display of unwanted advertisements on web pages. all-in-one gestures adds mouse-gesture functionality. application level extensions fixme: update this. these are sophisticated exte...
... yes; you can change the userchrome.css file, or use the stylish extension. user scripts (change appearance and functionality through javascript) yes; you can use the greasemonkey extension or "bookmarklets." yes; you can change userchrome.js to add functionality through javascript. extensions (these can do anything) yes yes theming (this changes the look of the browser) no yes let's build an extension table 1 shows the various customization options available to a user in firefox. users have flexible customization options, using css in user style sheets and javascript/dom in user scripts (these depend on stylish, greasemonkey, and userchrome.js). in addition to css and javascript, extensions can take advantag...
...ons, using css in user style sheets and javascript/dom in user scripts (these depend on stylish, greasemonkey, and userchrome.js). in addition to css and javascript, extensions can take advantage of xul and xpcom technologies for more sophisticated features. themes, which alter firefox's appearance, are a kind of add-on. in order to create an extension, you need an idea and just a little programming ability. the following chapters explain in detail the extension-writing techniques of some of japan's leading extension authors. we encourage you to try your hand at it as well. 1 one of the authors of this special edition, piro, is world-famous as one of the original developers. « previousnext » ...
Chapter 2: Technologies used in developing extensions - Archive of obsolete content
« previousnext » this document was authored by hiroshi shimoda of clear code inc. and was originally published in japanese for the firefox developers conference summer 2007. shimoda-san is a co-author of firefox 3 hacks (o'reilly japan, 2008). before we dive into a thorough explanation, we'll quickly introduce the technologies used to develop firefox extensions. we will also look at the minimum knowledge you'll need to have in order to develop for firefox. technologies used to develop firefox extensions firefox and its extensions are both based on and developed with technologies widely used on the web. its structure is similar to that of the dynamic html used on some web pages, or the html applications used on windows. if you've had experience developing with dynamic html, you'll ...
...ss, javascript, and xpcom. extensions are also built using these four technologies. figure 1: role of each technology in firefox in addition to these technologies, extension development will require you to learn about how to confer privileges to overcome security restrictions on code that you write, and how to embed your code into the firefox ui. these issues are discussed in chapter 5. the minimum knowledge required in the interest of brevity, i will omit explanations of widely understood technologies, and focus instead on introducing new technologies you will need to understand in order to develop for firefox. i will assume that you have experience developing with dynamic html, as well as the topics below. for more information on these technologies, please refer to other sources. ...
...ll. nevertheless, the rise of web services like google maps, which used javascript and asynchronous communications, created an awareness of a set of technologies nicknamed ajax (asynchronous javascript and xml); that plus the advent of a number of libraries that paper over implementation differences between different web browsers has more recently led to a re-evaluation of javascript as a programming language. javascript is a prototype-based object-oriented language, and as shown in listing 3, also permits independent class definitions. it does not have strict typing like java, making it extremely flexible and giving it qualities that in some senses could be considered similar to lisp. firefox 3.5 includes a number of extensions to the specification standardized in ecmascript 3rd edition, ...
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. this article is aimed at presenting alternatives to common eval uses in add-ons and other javascript code. add-on authors are strongly encouraged to update their code to eliminate all instances of eval, no matter if the add-on is to be hosted in the mozilla add-ons gallery or not. in order to host your add-on with mozilla it is crucial to minimize or completely eliminate eval use in order to receive a positive review and have your add-on made public. if it cannot be easily proven that an eval() call is benign and necessary b...
... firefox 3. there is simply no need to parse json using eval. additionally, parsing json retrieved from a remote location becomes a security vulnerability when parsed with the eval function. basically, you are executing remote code with full chrome access; that is, introducing a remote code execution vulnerability. even if you trust the remote server; for example, because it is one you rent and administer yourself, there is a huge security risk, because of, but not limited to: you might discontinue your project or sell it, so that it is possible another person with malicious intentions takes over your domain. the server and/or domain name might be compromised. if using an unencrypted, insecure connection, a man-in-the-middle attacker might replace the json with attack code before it arri...
..._original.apply(gbrowser, arguments); // execute some action afterwards. try { myaddon.doneaddtab(rv); } catch (ex) { /* might handle this */ } // return the original result return rv; }; })(); this is admittedly a bit more verbose, but at the same time it should be easier to understand. you don't have to parse what the resulting function will look like in your mind. there won't be any problems if various add-ons override the same function (using this method). you don't have to care about parameter naming (or changes in naming in future application versions) or short-hand/arrow functions. note: it is not safe to remove such an override again, as this method constitutes in a single-linked function chain. if you want to disable your overrides again, then ...
Custom XUL Elements with XBL - Archive of obsolete content
son.xml. <bindings xmlns="http://www.mozilla.org/xbl" xmlns:xbl="http://www.mozilla.org/xbl" xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> the bindings element is the root of the document, and it's a container for binding elements. notice how the default namespace for the document is xbl, and the xul namespace is defined as "xul". you'll need to keep this in mind when defining the content of the binding, because weird things can happen if you don't add "xul:" to your content nodes. <binding id="person"> in general, you should only have one binding per file. bindings tend to require many lines of code, and having more than one ends up making gigantic, unbrowsable files. on the other hand, if your bindings are small and have a strong relationship wit...
...chrome scripts. the main setback is that you can't have script tags defined in a binding, so you depend on the scripts that have been included in the xul files that use the binding. also unlike scripts, you can include stylesheets using the stylesheet xbl element. dtd and properties files can be handled just like in regular xul. there are two conflicting patterns that you should always keep in mind: encapsulation and separation of presentation and logic. encapsulation mandates that you try to keep your xbl free of outside dependencies. that is, you shouldn't assume that script x will be included somewhere, because not including it will cause the binding to fail. this suggests that you should keep everything inside your binding. on the other hand, a binding is really just a presentation mod...
...nd properties you wish to override. all you need to do is match the names of the originals. all methods and properties that are not overriden will maintain their original behavior. with inheritance you could take the richlistbox element and modify it to make a rich item tree, or create a switch button that changes state everytime it's clicked. and all with very little additional code. keep it in mind when creating your custom elements because it can save you lots of time. replacing existing xul elements as seen in the beginning of this section, the actual binding process is determined by a simple css rule that associates the tag name with the binding. this means that you can change the binding for pretty much any element in firefox by just adding a css rule! this is very powerful: it allow...
Mozilla Documentation Roadmap - Archive of obsolete content
portant feeds you should consider following: planet mozilla. this is the ultimate source for everything related to mozilla. it brings together the feeds of most mozilla employees, as well as several other members of the mozilla community. feeds are added frequently, so the information available through it will only grow with time. it can be hard to follow due of the sheer mass of information coming out of it (dozens of posts per day), but you'll certainly be up to date with pretty much everything if you take the time to read at least part of it. the about:mozilla newsletter is a weekly publication that includes the highlights of what is posted at planet mozilla. it is a good alternative if you feel planet mozilla is too much. you can also subscribe to receive it by email if you prefer tha...
...nother somewhat obscure communication channel is the mozilla newsgroups. they are also very diverse and active, and there's a good chance you'll get your queries answered. thunderbird also comes in handy for reading and posting to the newsgroups. another advantage is that discussions are archived and searchable through google groups. other and finally, a couple resources you should also keep in mind: other extensions. there are thousands of extensions out there, and you may strike luck and find one that does exactly what you need. be sure to look at the license the extension's code is released with before thinking about copying large sections of it. also, remember to give credit when it's due. mozilla's bugzilla repository. pretty much every code change done in firefox and mozilla proje...
...y what you need. be sure to look at the license the extension's code is released with before thinking about copying large sections of it. also, remember to give credit when it's due. mozilla's bugzilla repository. pretty much every code change done in firefox and mozilla projects is documented in this huge tracking database. but this also means that finding exactly what you need can be time-consuming, and often fruitless. the advanced search is very useful in filtering results, but it is our experience that it's often better to be too general than too specific. better to scan a list of hundreds of bugs than getting no results at all, right? anywhere else. use your favorite search engine and patiently look for answers. it's better to take a long time finding an answer than taking even longer...
Useful Mozilla Community Sites - Archive of obsolete content
. amo amo (mozilla add-ons) is the official mozilla repository for add-ons. it allows you to upload, search and download all types of add-ons for mozilla applications. this is the best way to get your extension to users from all around the world. adding your extension to amo is easy. ...
...mo is easy. all you need is your xpi, a few screenshots (good ones will make your extension much more appealing), and a few minutes to fill a couple of forms. but this won't make your extension public right away. amo has a review process that prevents malicious, insecure or low quality extensions to make it to the public site. your extension begins in a sandbox with limited access, and once you nominate it an editor will review it and see if it is appropriate for the public amo site, where everyone can see it and install it. the review process often takes a few weeks. just be patient and make sure your extension follows amo's policies when you nominate it. you can still get a good number of downloads while being in the sandbox. one of the main advantages of using amo is that it handles updat...
...google code that are also very good, but not as specialized as mozdev. you should pick the one that best fits your development needs. conclusion that's it! this is the end of the xul school tutorial. hopefully this guide has helped you get started with add-on development and you're on your way to joining the large mozilla add-ons developer community. the sheer volume of material can be overwhelming, but you can always come back and use this tutorial as a reference for your future development. now all you need is a good idea (in case you didn't have one already) and get started. happy coding! « previous this tutorial was kindly donated to mozilla by appcoast. ...
Performance best practices in extensions - Archive of obsolete content
ou can use an nsitimer or the window.settimeout() method to schedule that work for later. even a short delay can have a big impact. general performance tips avoid creating memory leaks memory leaks require the garbage collector and the cycle collector to work harder, which can significantly degrade performance. zombie compartments are a particular kind of memory leak that you can detect with minimal effort. see the zombie compartments page, especially the proactive checking of add-ons section. see common causes of memory leaks in extensions for ways to avoid zombie compartments and other kinds of leaks. as well as looking for these specific kinds of leaks, it's worth exercising your extension's functionality and checking the contents of about:memory for any excessive memory usage. fo...
...s i/o this cannot be stressed enough: never do synchronous i/o on the main thread. any kind of i/o on the main thread, be it disk or network i/o, can cause serious ui responsiveness issues. never use synchronous xmlhttprequests. netutils.jsm provides helpers for asynchronous reading and copying of files. never access a sqlite database synchronously. use the asynchronous api instead. 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. these events happen with high frequency, so their listeners can trivially create very high cpu overhead. when these events cannot be avoided, computation during the li...
...perations can often be greatly simplified using promises. avoid mouse movement events avoid using mouse event listeners, including mouseover, mouseout, mouseenter, mouseexit, and especially mousemove. these events happen with high frequency, so their listeners can trivially create very high cpu overhead. when these events cannot be avoided, computation during the listeners should be kept to a minimum and real work throttled. the listeners should be added to the most specific element possible, and removed when not immediately necessary. avoid animated images animated images are much more expensive than generally expected, especially when used in xul tree elements.. consider using chrome workers you can use a chromeworker to execute long running tasks or do data processing. ...
Creating a status bar extension - Archive of obsolete content
extension identification information certain information is needed so firefox can uniquely identify your extension. in this sample, these fields are: property name description id...
...extension identification information certain information is needed so firefox can uniquely identify your extension. in this sample, these fields are: property name description id a unique identi...
...ct the extension so that only supported versions of the target application will attempt to use it. the target application information is contained within the em:targetapplication description block. property name description id an id indicating the target application. "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}" is a guid that uniquely identifies firefox as the target. minversion the oldest version of the target application on which the extension is supported. maxversion the most recent version of the target application on which the extension is known to work. for details on the format of an install manifest, read the install manifests section. the chrome manifest the chrome manifest is a file that tells the target application where to look for...
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
veloping web pages, in which developers format text layouts into pages and link those pages to related content, is analogous to a book or a magazine: readers view pages, go to other pages for more information, and view resources listed as references on that page. html and web standards have evolved and now offer flexible and fine-grained control to layout as well supporting dhtml, powerful programming languages like javascript, and additional media through embeddable third-party resources like flash, java, vrml, etc. additionally, server-side technologies have also evolved, supporting and connecting different resources to different browsers. despite all the evolution, we still see the underpinnings of the original model in modern web sites. we still connect through a set of links that mostly ...
...e real showcase for new browser features and web standards like html 4.0 and dom level 2, and xml are models like inner-browsing, where these technologies can begin to be used in the way that they were envisioned. many of the new web technologies in the html 4.0 specification, xml 1.0, dom level 3 were explicitly created with application-like behavior and more sophisticated navigational models in mind. in the next section we will introduce inner-browsing as an extension to the traditional model. let's start defining what we mean by inner-browsing. in this model, when a request goes to the web server, the current page is updated rather than replaced. without leaving the page, the user browses new information and preserves the page's context. this new navigational method allows us to make html ...
... using soap-based rpc mechanism or using interfaces like xmlhttprequest (currently offered in netscape 7 and internet explorer 6). data bind: mutation in the current document this step takes care of applying the changes into the current document, based on the data loaded, and uses dom interfaces. the mechanism can be as simple as copying new content to the current document, or as complex as performing dynamic transformations on the data source before applying the changes into the current document. for example, if a given web site's framework uses xslt to format xml contents as html, would be appropriate to reuse xslt to format new data that is about to be part of the current document. the next section illustrates a case of implementation using javascript, iframes and dom. inner-browsing with ...
JXON - Archive of obsolete content
lor_swatch": { "@image": "black_cardigan.jpg", "keyvalue": "black" } } }] }, "script": { "@type": "text/javascript", "keyvalue": "function matchwo(a,b) {\n if (a < b && a < 0) { return 1; }\n else { return 0; }\n}" } } } this is a recommended technique if you know the structure of the xml document. algorithm #4: a very minimalist way the following is another possible way to do the conversion. it is very close to the parker convention, too. with this algorithm, all element nodes that contain other child element, text, or cdatasection nodes in the same level are treated as instances of boolean, number, string, or date constructors. so any child element node, if exists, will be nested in these types of objects. for ...
...f of all the collected text content of each tag and the absorption of solitary text and/or cdatasection nodes into primitive values). it is called “parker convention” in opposition to “badgerfish convention”, after the comic parker & badger by cuadrado. see also: badgerfish convention. the following is a transcription of the parker convention paper (version 0.4), from the page “transformingrules” of the xml2json-xslt project site. this convention was written in order to regulate the conversion to json from xslt, so parts of it are futile for javascript. note: on october 29th, 2013, the world wide web consortium relased in a note on official algorithm for converting html5 microdata to json. however, html microdata is not html: microdata is a formatted subset of html. translatio...
...onversion between xml and json is lossless regarding the whole content and the structure of an xml document, it is not lossless regarding the ordering of elements, which for some xml dialects (like xhtml) is part of the information. for instance, a bidirectional conversion of the following html paragraph: <p>she <strong>loves</strong> you. and definitely <strong>hates</strong> me.</p> would determine a result like the following: <p><strong>loves</strong><strong>hates</strong>sheyou. and definitelyme.</p> as you can see in this special case, the whole information is preserved, the ordering of the elements is not. it turns out then that for some xml dialects jxon can be not the best choise, while it can be a really powerful tool in dealing with standard xml. one conversion method which is los...
Environment variables affecting crash reporting - Archive of obsolete content
the breakpad crash reporting used in mozilla projects supports some environment variables, primarily for testing purposes. the following environment variables affect crash reporting: moz_crashreporter_url sets the url that the crash reporter will submit reports to. moz_crashreporter_fulldump store full application memory in the minidump, so you can open it in a microsoft debugger. don't submit it to the server. ...
...t variables affect crash reporting: moz_crashreporter_url sets the url that the crash reporter will submit reports to. moz_crashreporter_fulldump store full application memory in the minidump, so you can open it in a microsoft debugger. don't submit it to the server. (windows only.) moz_crashreporter_no_delete_dump don't delete the crash report dump file after submitting it to the server. minidumps will still be moved to the "crash reports/pending" directory. moz_crashreporter_no_report save the minidump file but don't launch the crash reporting ui or send the report to the server. minidumps will be stored in the user's profile directory, in a subdirectory named "minidumps". moz_crashreporter_disable disable breakpad crash reporting completely. you can use this if you would rather...
...this is useful for content crashes that don't normally close the chrome (main application) processes. this variable would cause the application to close as well. moz_crashreporter the opposite of moz_crashreporter_disable, force crash reporting on even if disabled in application.ini. ...
No Proxy For configuration - Archive of obsolete content
initially, proxy servers were used for access control and performance. many networks had limited access to the public network via proxy servers. ...
...ing. david baron has pointed out that the original pac code in the "classic" tree is written in c++. the pac in c++ has not been tested in mozilla, so porting pac in c++ forward would not be a panacea. the relevant code lives in nsprotocolproxyservice.cpp. nsprotocolproxyservice::prefschanged - loads preferences nsprotocolproxyservice::loadfilters - parses filters nsprotocolproxyservice::examineforproxy - decides to check filters if configuration is "manual" nsprotocolproxyservice::canuseproxy - performs url vs. filter comparison notable bugs bug 172083 - [meta] proxy: "no proxy for" items bug 80917 - proxy: "no proxy" w/ form based ui bug 91587 - proxy: "no proxy for" default domain filtering fails w/ non-fqdn (e.g., http://web/) bug 201685 - no proxy for: support ipv6 address...
...mo.us, dor.intranet note that you don't need to (read shouldn't) put a * for all hosts with that domain ending. corollary- a no_proxies_on entry of netscape.com will be applicable to all hosts ending at netscape.com including foonetscape.com but an entry of .netscape.com will specifically be applicable to all hosts in the domain of netscape.com. original document information author(s): benjamin chuang last updated date: november 2, 2005 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creative commons license | details. ...
ActiveX Control for Hosting Netscape Plug-ins in IE - Archive of obsolete content
ect. if you're wondering how microsoft used to support the np api, look for a file called plugin.ocx in your windows system directory. this 100k activex control contains the entire np api implementation and probably worked much like pluginhostctrl.dll does now. the sections below tell you how to fetch, build and use the pluginhostctrl.dll . get the source you need cvs to get the source code. ...
... other plug-ins vendors may have installed. it is advisable to rename the control and not to install somewhere like the windows directory where it is likely to be overridden. use a tool such as guidgen.exe or uuidgen.exe to create the new guids. package it there is a subdirectory named cab/ which contains a script and a readme.txt for producing your own signed cab files. manual installation assuming you have the precompiled pluginhostctrl.dll and wish to install it on a machine, you must register it either through an install script or manually: regsvr32 pluginhostctrl.dll you must have administrator privileges to install a new control on operating systems such as windows nt, 2000 & xp. usage insert some html like this into your content: <object classid="clsid:dbb2de32-61f1-4f7f-beb8-...
...sting control, the width and height specify the dimensions in pixels. you may optionally specify a codebase attribute if you have packaged the control into a cab file and wish for it to be installed automatically. the following <embed> attributes have <param> tag equivalents: <param name="type" ...> is equivalent to typespecifies the mime type of the plug-in. the control uses this value to determine which plug-in it should create to handle the content. <param name="src" ...> is equivalent to srcspecifies an url for the initial stream of data to feed the plug-in. if you havent't specified a "type" param, the control will attempt to use the mime type of this stream to create the correct plug-in. <param name="pluginspage" ...> is equivalent to pluginspagespecifies a url where the plug-in may...
Getting Started - Archive of obsolete content
municator communicator contains all the toolbar icons, as well as the icons for the bookmark manager and the preferences window. skin\classic\editor editor contains files of composer. skin\classic\global global contains almost all of the important css files that define the appearance of the suite. this is the most critical directory in a theme. skin\classic\help help contains all the files for theming the help dialog window. skin\classic\messenger messenger contains styles of the mail client. skin\classic\messenger-newsblog messenger-newsblog contains the only css file. skin\classic\mozapps mozapps contains all the styles and icons for the browser peripherals, such as the extension manager or update wizard. skin\classic\navigator navigator contains some icons and styles for all sm components.
...le is a small xml database that describes the skin. <description about="urn:mozilla:install-manifest"> <em:id>{themes_uuid}</em:id> <em:version>themes_version</em:version> the first section requires that you establish a uuid for your theme and that you give your theme a version number. once you've done this, insert the information as above, and scroll down. ...
... that you give your theme a version number. once you've done this, insert the information as above, and scroll down. you will also have to update the minimum and maximum compatible versions for the target application (seamonkey) in the following section: <em:targetapplication> <description> <!-- seamonkey's uuid --> <em:id>{92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a}</em:id> <em:minversion>min_sm_version</em:minversion> <em:maxversion>max_sm_version</em:maxversion> </description> </em:targetapplication> establishing both minimum and maximum compatible versions lets you avoid conflicts with versions of seamonkey your theme wasn't designed for -- or wasn't tested on. see install manifests for the reference information about the install.rdf file. css files the css ...
Creating a Skin for Firefox/Getting Started - Archive of obsolete content
cons, as well as the icons for the bookmark manager and the preferences window. skin\classic\communicator doesn't do a whole lot and can typically be forgotten about promptly. skin\classic\global global contains almost all of the important css files that define the appearance of the browser. this is the most critical directory in a theme. skin\classic\help help contains all the files for theming the help dialog window. skin\classic\mozapps mozapps contains all the styles and icons for the browser peripherals, such as the extension manager or update wizard. install your new theme before you can see the changes you make to a firefox theme (since live edits are restrictively difficult to set up) you must first learn how to repackage the classic theme to make it installable. for the sa...
...is a small xml database that describes the skin. <description about="urn:mozilla:install-manifest"> <em:id>{themes_uuid}</em:id> <em:version>themes_version</em:version> the first section requires that you establish a uuid for your theme and that you give your theme a version number. once you've done this, insert the information as above, and scroll down. ...
...nd that you give your theme a version number. once you've done this, insert the information as above, and scroll down. you will also have to update the minimum and maximum compatible versions for the target application (firefox) in the following section: <em:targetapplication> <description> <!-- firefox's uuid --> <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> <em:minversion>min_ff_version</em:minversion> <em:maxversion>max_ff_version</em:maxversion> </description> </em:targetapplication> establishing both minimum and maximum compatible versions lets you avoid conflicts with versions of firefox your theme wasn't designed for -- or wasn't tested on. see install manifests for the reference information about the install.rdf file. css files the cs...
Dehydra Object Reference - Archive of obsolete content
often, the best way to become familiar with the dehydra objects is to print out the objects: dehydra example code an online tool for pretty-printing dehydra data understanding properties dehydra only sets properties that are applicable. for example, class types and typedefs are declared and will have a .loc property. intrinsic types such as "int" are not declared and will not have a .loc. dehydra only sets boolean flags when they are true. ...
...y type description .isarray boolean flag .max integer or normal fixed-size arrays, the index of the largest element of the array. ...
...ean flag .max integer or normal fixed-size arrays, the index of the largest element of the array. ...
Documentation for BiDi Mozilla - Archive of obsolete content
ibmbidi), written by simon montagu and posted to the mozilla-layout mailing list. while it was published in 2001 and might not be totally accurate, it does help understanding the internals of the bidi code. overview of bidi processing bidi text is reordered according to the unicode bidi algorithm (uba). the implementation is based on ibm's international components for unicode (icu), which was chosen after comparing and testing the available open-source implementations. ...
...the available open-source implementations. as far as we could discover, icu is the only one which is 100% compatible with uba, including support for explicit directional controls (lro, rlo, etc, and their html equivalents). bidi processing for a given html document will only take place if one of the following is true: the page includes a hebrew or arabic character or a hindi digit. this is determined in nstextfragment::setto the page includes a element with the attribute dir=rtl, either explicitly (nsgenerichtmlelement::mapcommonattributesinto), or as a consequence of a style rule (mapdeclarationtextinto in nscssstylerule.cpp) all these cases use nsdocument::enablebidi to set the flag mbidienabled. in a bidi-enabled document, the following things happen: during a reflow, nsbidipresutils::...
...ent with the attribute dir=rtl, either explicitly (nsgenerichtmlelement::mapcommonattributesinto), or as a consequence of a style rule (mapdeclarationtextinto in nscssstylerule.cpp) all these cases use nsdocument::enablebidi to set the flag mbidienabled. in a bidi-enabled document, the following things happen: during a reflow, nsbidipresutils::resolve is called. this method uses the uba to determine the directional properties of the text and reorder frames if necessary. if necessary, text frames are split so that every frame has the same directionality. framemanager::setframeproperty is used to set the following flags and pointers (for terminology see the specification of the uba): embeddinglevel: the embedding level of the frame textclass: the text class of the frame. baselevel: the base...
Style System Overview - Archive of obsolete content
ment nsistyleruleprocessor. the nsistyleruleprocessor interface implemented by cssruleprocessor, htmlstylesheetimpl, and htmlcssstylesheetimpl has a rulesmatching method, which is required to call nsrulewalker::forward on any rules that match the element. (we'll see what this does later.) the main argument to rulesmatching is a structure of enumeration data that implementations use to determine more quickly which rules match. has a separate rulesmatching method for pseudo-elements. cssruleprocessor one cssruleprocessor per origin (ua, user, author) css rule processor sorts all the rules in cascade order, and then puts them in rulehash, which remembers order and then hashes by first of id, class, tag, namespace, or unhashed. to match rules, we do lookups in the rulehash's tables...
...to. if the computation in compute*data used any data from the parent style context, we cache the struct on the style context. otherwise, we cache the struct in the rule tree, on the first rule node that contributed any data, and mark dependent bits on the path up to that rule node. managing style contexts style contexts must (in most cases) be created before frames are constructed, to determine what frame to create. parent style context determines inheritance; it should always be the content parent. [design flaw in frame/sc relationship] three functions for creating style contexts on nsistyleset, wrapped by similarly named ones on nsiprescontext: resolvestylecontextfor: for elements. resolvepseudostylecontextfor: for pseudo-elements (:first-letter, :before, etc.) resolves...
...cssruleprocessor implementation does a slightly modified form of selector matching to implement it (includes matching on the middle of selectors to catch p:hover a). style attribute changes we handle style attribute (“inline style”) changes in a different way from other changes to style rules. as for other style changes, we have to “walk” the rule tree and clear all the style data coming from the old inline style nsistylerule, since there could be an !important rule that overrides it, which would allow dynamic changes to put the style attribute in multiple places in the rule tree. however, we maintain a hashtable just for inline style rules so that we don't have to walk the whole tree to find the nodes. nscssframeconstructor::attributechanged only re-resolves style on the subtr...
Supporting per-window private browsing - Archive of obsolete content
you can then take action based on this value, as any data or actions originating from this window should be considered private. ...
... privatebrowsingenabled; if (!inprivatebrowsing) { ... } } catch(e) { components.utils.reporterror(e); return; } } obtaining an nsiloadcontext for privacy-sensitive apis some apis (such as nsitransferable and nsiwebbrowserpersist) take nsiloadcontext arguments that are used to determine whether they should be classed as private or not (for example, whether the uri being persisted by saveuri should be added to the permanent download history). to do this, import resource://gre/modules/privatebrowsingutils.jsm and use privatebrowsingutils.getprivacycontextfromwindow(win), passing a window object that is related to the content in question. as an example, if an add-on adds a context...
... notification. function pbobserver() { /* clear private data */ } var os = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); os.addobserver(pbobserver, "last-pb-context-exited", false); preventing a private session from ending if there are unfinished transactions involving private data, where the transactions will be terminated by the ending of a private session, an add-on can vote to prevent the session from ending (prompting the user is recommended). to do this, observe the last-pb-context-exiting notification and set the data field of the nsisupportsprbool subject to true. var os = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); os.ad...
The new nsString class implementation (1999) - Archive of obsolete content
ntrinsic i18n support few efficiencies, notably a lack of support for narrow (1-byte) character strings no support for external memory management policy lack of xpcom interface notable features of the new nsstrimpl implementation are: intrinsic support for 1 and 2 byte character widths provides automatic conversion between strings with different character sizes inviolate base structure eliminates class fragility problem; safe across dll boundaries offers c-style function api to manipulate nsstrimpl offers simple memory allocator api for specialized memory policy shares binary format with bstring coming soon: a new xpcom (nsistring) interface non-templatized; this is a requirement for gecko very efficient buffer manipulation architecture the fundamental data type in the new arch...
... found in nsstrimpl) for construction, searching and comparison. also note that the new nsstring interface mimics fully the interface in the existing nsstring class found in mozilla/base/src/nsstring.h. nsautostring we still offer an nsautostring that provides its own stack based buffer. this very useful class allows programmers to take advantage of the nsstring/nsstrimpl implementation, while eliminating heap based allocations. an additional improvement has been made to nsautostring that allows it to use an arbitrarily sized stack based buffer rather than its own internal buffer. this means that you can continue to use efficient (temporary) stack buffers for string storage with the bonus of storage pools that serve your specific need. (sounds complicated, but it's really easy). this class fu...
...ply that everyone needs to use the same allocators, that they acquire via a global com service called cogetmalloc(). our nsstrimpl uses an allocator pattern so that programmers can install their own policy, but this may also make allocation simpler in a multiprocess environment. i'm wondering if this is sufficient, namely, that a string can return it's own (shared) allocator for this purpose. our minimalistic nsimemoryagent interface is just rich enough to support the nsstring idiom, and could be extended to serve as the general memory allocation idiom. here's it's api: class nsimemoryagent : nsisupports { void* new(nsint32 asize)=0; //used for both alloc and realloc void* delete(void* aptr)=0; }; internationalization the new nsstrimpl/nsstring implementation addresses at least two of t...
Using Breakpoints in Venkman - Archive of obsolete content
this article continues a series of articles on venkman that began with venkman introduction. one of the basic tasks of debugging any language is setting breakpoints. breakpoints are places in code where execution is suspended. when you set a breakpoint in a debugging application such as venkman, you can take advantage of the suspension to examine variables, objects, and other featues of the execution. this article describes breakpoints in javascript and how to use venkman to set and examine breakpoints. basic breakpoints the stop button and debugger keyword are useful features of the javascript debugger, but when you are debugging deep in code—especially code you have authored yourself and are responsible for troubleshooting—you're going to need breakpoints. types of breakpoints v...
...iles in which breakpoints have been set, along with the line number where the function begins whose code is being stopped. 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. one of the most important aspects of debugging a script or software program is the ability to examine variables—function return values, errors, counters, variable scopes—as they change over the course of the script execution. the onflipx function in figure 1, for example, uses the variable newsign to figure out what image to use for the fish. when you set a breakpoint at line 81, you can start animation on the web page in the browser window and see venkman stop execution as it enters the onf...
...vanced feature and other options you can see for the associated script are available from the future breakpoint properties dialog, which you can access by right-clicking a breakpoint and selecting properties. once you've created a script that will be executed when the associated breakpoint is hit, you can select a number of different options from the future breakpoint properties dialog that determine how venkman will deal with the output of the associated script. the following options are available: continue regardless of result causes venkman to continue normal execution after running the breakpoint script. this can be useful to try out additional code, on the fly. stop regardless of result causes venkman to stop execution after executing the breakpoint script, allowing you to inspect ...
When To Use ifdefs - Archive of obsolete content
pp ifdefs are not acceptable in tier 9, but are acceptable (even necessary) in later tiers. for an example of feature ifdefs, see layout/makefile.in. application-specific ifdefs finally, each application/project needs to build different pieces of code. application ifdefs should only be made in application-specific code. this is the trickiest kind of ifdef, because it is frequently hard to determine what code is "shared" and what code is "application-specific". as a general rule, any code in tier 2, tier 9, or tier 50 is shared code, and should not have application-specific ifdefs. any code in later tiers is application-specific. this rule has many exceptions, some of which are listed here: the code in editor/ui/ is built by the suite, standalone composer, and thunderbird, but it is consi...
...derbird, but it is considered application-specific. the code in xpfe/ (except for xpfe/appshell/ and xpfe/components/shistory/) is a hodgepodge mess of "toolkit" and "application-specific" code. this code is all going to be moved elsewhere (most of it to toolkit/ or suite/), but for the time being most application-specific ifdefs are allowed because we can't help it. if you're not sure, ask benjamin smedberg. for an example of an application-specific ifdef that is bad and should be removed, see nsnativeappsupportwin.cpp. types of ifdef there are two major types of ifdef: preprocessor ifdefs and makefile ifdefs. preprocessor ifdefs are generally easy to spot: in c, c++, and plaintext preprocessed code there will be an #ifdef or #if instruction. makefile ifdefs, however, are sometimes hard...
...s with the same name which are built conditionally. for example (at the time of writing) there are two nsiextensionmanager interfaces: toolkit version and suite version. the makefile ifdefs that choose which one to build are not obvious (see makefile.in and xpfe/components/makefile.in). if you are introducing a makefile ifdef of any sort, please ask review from one of the build-config peers: benjamin smedberg is generally happy to review these changes. ...
initInstall - Archive of obsolete content
se. pass 0 as the default value. returns an integer error code. for a list of possible values, see return codes. description the initinstall method initializes the installation of the specified software. you must call this method immediately after the constructor. it is an error to call any other install methods before calling initinstall. ...
...sible values, see return codes. description the initinstall method initializes the installation of the specified software. you must call this method immediately after the constructor. it is an error to call any other install methods before calling initinstall. after calling initinstall, your script must call performinstall or cancelinstall before it finishes. ...
...orminstall or cancelinstall before it finishes. if your script does not call performinstall or cancelinstall, netscape 6 will not be able to clean up properly after your script finishes. example to start installation for the royal airways plug-in, you could use this code: initinstall("royal airways tripplanner","/royalairways/ tripplanner","1.0.0.0"); ... ...
SQLite Templates - Archive of obsolete content
rate xul content. to do this, set the querytype attribute on the root node of the template to the value storage. this will cause the datasource to be treated as an sqlite database. the datasources attribute may be set to one of two possible types of values. first, it may a file url pointing to a file on disk. in this case, you will often be setting the datasources attribute dynamically after determining the file path. (if you intend to set it by script, you must set datasources in the xul to rdf:null). 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. this is useful for user data, and is suitable as you do not need to calculate where this directory is located. the file within t...
... so that the getelementbyid method may be used to refer to it. you can add as many parameters as necessary for the query. the example above used a string parameter. if you want a numeric parameter, you should also set the type attribute. <listbox id="friends" datasources="profile:userdata.sqlite" ref="*" querytype="storage"> <template> <query> select name, from myfriends where age >= :minage && age <= :maxage <param id="minage" name="minage" type="integer">30</param> <param id="maxage" name="maxage" type="integer">40</param> </query> <action> <listitem uri="?" label="?name"/> </action> </template> </listbox> here, the age is an integer number, so the type attribute is set to integer. integers are 32-bit values, but you can use the value int64 for 6...
...> </template> </listbox> here, the age is an integer number, so the type attribute is set to integer. integers are 32-bit values, but you can use the value int64 for 64-bit integers. you can also use the value double for double precision floating point values. if no type is specified, a string is assumed. we could later change the age to use in the query with a short script: function adjustage(min, max) { document.getelementbyid("minage").textcontent = min; document.getelementbyid("maxage").textcontent = max; document.getelementbyid("friends").builder.rebuild(); } this function takes two arguments, the minimum and maximum values to use. we retrieve the param elements and set their textcontent properties to the desired value. finally, we rebuild the entire template. « previousn...
The Joy of XUL - Archive of obsolete content
g applications right away. also described are some reasons application developers might choose to leverage xul and mozilla technology for building cross-platform applications. this same investigation will provide sufficient explanation of mozilla's motivation to build xul and why the mozilla platform is constructed using it. the key features and benefits of xul will be explored followed by an examination of supporting mozilla technologies. finally, a mini case study of a calendar application written in xul will reinforce the benefits of building applications with mozilla. key features and benefits powerful widget-based markup language the goal of xul is to build cross platform applications, in contrast with dhtml which is intended for developing web pages. for this reason, xul ...
...it to overlays for software developers who intend to add features to mozilla that they wish to keep proprietary. the netscape public license (npl) and mozilla public license (mpl) require developers who alter original work (source code files that are provided with mozilla) to release the source code for these changes to their customers. overlays can be used to add features to mozilla without contaminating the original open source code with proprietary alterations. xpcom/xpconnect xpcom and xpconnect are complementary technologies that enable the integration of external libraries with xul applications. xpcom, which stands for cross platform component object model, is a framework for writing cross-platform, modular software. xpcom components can be written in c, c++, and jav...
...tall enables users to effortlessly install new xul applications over the internet or from corporate intranet servers. to install a new application the user need only click a hypertext link on a web page or in an email message and accept the new package through a mozilla install dialog. todo: describe cool toolkit and xul runner features case study: a mozilla calendar application this mini case study describes how oeone corporation (now part of hipplay; this calendar application is no longer listed on their site) integrated its calendar application with the core mozilla product. the calendar application is comprised of a xul front end and an xpcom component that leverages libical, a native library written in c, for date operations and calendar data storage. the calendar was initia...
Adding more elements - Archive of obsolete content
a spacer has been added in between each element to separate them. these spacers have been given an explicit width of 10 pixels each. you will notice that if the window is resized, the textbox grows but the other components do not. you will also notice that the label was removed. if you resize the window vertically, the...
...the first spacer adds extra spacing in between the title label and the search criteria elements. it might look nicer if there was a border around the search criteria. there are two ways to do this. we could use t...
... the style on the box itself. we will use the latter method, however. a groupbox has the advantage that it draws a box with a nice beveled look, suitable for the current theme. let us change the box into a groupbox: <groupbox orient="horizontal"> <caption label="search criteria"/> <menulist id="searchtype"> . . . <spacer style="width: 10px;"/> <textbox id="find-text" flex="1" style="min-width: 15em;"/> </groupbox> there are other cosmetic problems as well. we could also have the groupbox grow so that it extends vertically to the bottom of the box. also, we could modify some of the margins so that the elements are positioned better. we will see more examples of the box model and some of its features as we continue to add elements throughout the tutorial. find files example so...
Additional Install Features - Archive of obsolete content
s section described a basic installer. you may wish to perform some more elaborate processing during the installation. for example, you may want to install a package only when certain conditions are met, such as having a particular library installed. in addition to the install object, a file object is also available during an installation script. it provides some functions which can be used to examine and modify files on disk. you can use these to move, copy or delete files before or after the files are installed. for example, you might want to make a backup of some files first. the following code will make a copy of the file "/bin/grep" and put it in the directory "/main". var binfolder = getfolder("file:///","bin"); var grep = getfolder(binfolder, "grep"); var mainfolder = getfolder("file...
... to the destination. functions also exist to move(), rename() and execute() files. thus, you can move files that might conflict with your package out of the way. handling errors you will likely want to handle errors gracefully. this will occur if a file or directory cannot be found, there is insufficient disk space or for a number of other reasons. you can use the getlasterror() function to determine whether an error occured. if it returns success, no error occured. otherwise, the number will be an error code which indicates the type of error that occured. you can call this function at any point during the installation script to determine whether an error occured during the last operation. if an error occurs, you will likely want to abort the installation. you may also want to display an err...
...during installation, a log file is created that contains the operations that are performed. it will also show any errors that occured. ...
Box Objects - Archive of obsolete content
object. conversely, some content nodes have no layout objects at all. for instance, the key element doesn't have any layout objects since it isn't displayed in any way. similarly, any element that has been hidden will not have a layout object either. the dom is generally used only to get and modify information pertaining to the content or structure of the document. it's relatively simple to determine what kind of content tree node will be created for a given element. a xul element, for example, will have a xulelement type of content node. the layout objects that will be created are determined in a more complex manner. various pieces of information are used such as the tag name, the attributes on an element, various css properties, the elements and layout objects around the element, and the x...
...le by methods mapped directly onto the element, since those types are generally only used with one particular element. the base box object, or the interface nsiboxobject, however, has a number of properties which are quite useful for xul development. the base box object has two useful features. first, you can retrieve the position and size of the xul element as displayed, and second, you can determine the order of the elements in the box as displayed, instead of their order as they are stored in the dom. retrieving position and size the box object provides six read only properties, x, y, screenx, screeny, width and height, for determining the currently displayed position and size of an element. all values returned are in pixels. x, y the x and y coordinates are referenced from the top left c...
...="document.getelementbyid('thelabel').collapsed = false;"/> <button label="show position/size" oncommand="showpositionandsize();"/> <label id="thelabel" value="i am a label"/> note that if you hide and collapse the label, it will be treated as hidden. you will then have to unhide and uncollapse the label for it to appear again. xul element ordering the box object may also be used to determine the display order of elements, which may not be the same as the order in the source. recall that dom properties such as childnodes, firstchild, and nextsibling may be used to navigate the document tree. the box object also allows navigation in a similar means but retrieves the elements in display order. the box object provides several properties, firstchild, lastchild, nextsibling, previoussibli...
Creating a Window - Archive of obsolete content
. you would normally add this line as is at the top of each xul file. <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> this line is used to specify the style sheets to use for the file. this is the syntax that xml files use to import style sheets. in this case, we import the styles found in the global part of a skin package. we didn't specify a specific file so mozilla will determine which files in the directory to use. in this case, the all-important global.css file is selected. this file contains all the default declarations for all of the xul elements. because xml does not have any knowledge of how elements should be displayed, the file indicates how. generally, you will put this line at the top of every xul file. you can also import other style sheets using a similar syn...
... finally, we need to close the window tag at the end of the file. opening a window in order to open a xul window, there are several methods that can be used. if you are only in the development stage, you can just type the url (whether a chrome:, file: or other url type) into the location bar in a mozilla browser window. you should also be able to double-click the file in your file manager, assuming that xul files are associated with mozilla. the xul window will appear in the browser window as opposed to a new window, but this is often sufficient during the early stages of development. note: the local xul document can be opened in the browser as mentioned above only if |dom.allow_xul_xbl_for_file| preference in "about:config" has been set to |true| . if it does not exist, then it needs to ...
... '-chrome' to specify the xul file to open when mozilla starts. if this is not specified, the default window will open. (usually the browser window.) for example, we could open the find files dialog with either of the following: mozilla -chrome chrome://findfile/content/findfile.xul mozilla -chrome resource:/chrome/findfile/content/findfile.xul if you run this command from a command-line (assuming you have one on your platform), the find files dialog will open by default instead of the mozilla browser window. of course, because we haven't put any ui elements in the window, you won't see a window appear. we'll add some elements in the next section. to see the effect though, the following will open the bookmarks window: mozilla -chrome chrome://communicator/content/bookmarks/bookmarksmana...
Introduction - Archive of obsolete content
sherlock or the find file dialog in windows. note that only the user interface will be created, with only limited functionality. the actual finding of files will not be implemented. a blue line will appear to the left of a paragraph where the find file dialog is being modified. you can follow along by looking for these sections. what is xul and why was it created? xul (pronounced "zool" and rhyming with "cool") was created to make development of the mozilla browser easier and faster. it is an xml language so all features available to xml are also available to xul. most applications need to be developed using features of a specific platform making building cross-platform software time-consuming and costly. a number of cross-platform solutions have been developed in the past. java, for exam...
...eate standalone xul applications. a browser isn't required to run these applications, as they have their own executable file. xul package in between the other two are applications which are created in the same way as an extension, but they act like a separate application in a separate window. this is used when you don't want to have the larger size of a complete xulrunner application, but don't mind requiring a mozilla browser to be installed to be able to run the application. remote xul application you could also just place xul code on a web server and open it in firefox, as you would any other web page, however this is discouraged and was disabled in firefox 8. it is still possible to enable this for selected sites to let legacy apps to continue working, but for new remote applications...
... be packaged into a single file and downloaded and installed by the user. mozilla applications such as firefox provide an extension manager which allows packages to be installed without having to write a lot of complex code. what do i need to know to use this tutorial? you should have an understanding of html and at least a basic understanding of xml and css. here are some guidelines to keep in mind: xul elements and attributes should all be entered in lowercase as xml is case-sensitive (unlike html). attribute values in xul must be placed inside quotes, even if they are numbers. xul files are usually split into four files, one each for the layout and elements, for style declarations, for entity declarations (used for localization) and for scripts. in addition, you may have extra files...
More Tree Features - Archive of obsolete content
er's bookmarks list. the tree view has a number of functions which specify the hierarchy of the items in a tree. each item in the tree has a level starting at 0. the topmost items in the tree will have a level of 0, the children of those items will have a level of 1, the children below that will have a level of 2, and so on. the tree will query the view for the level of each item in order to determine how to draw the rows. the tree will draw the open and close icons to open and close a parent item as well as lines connecting the children to their parents. the tree will also handle drawing the rows with the right level of indenting. however, the view will need to make sure it keeps track of the level of the rows as necessary. this can sometimes be quite tricky, but fortunately, the built-in co...
...="bob" /> <treecell label="carpenter" /> </treerow> </treeitem> <treeitem> <treerow> <treecell label="jerry" /> <treecell label="hodge" /> </treerow> </treeitem> </treechildren> </treeitem> </treechildren> </tree> this has created a hierarchical tree. as can be seen in the image, a small plus or minus sign (often called a twisty) has appeared next to the first row, indicating that it contains child rows. by clicking the row, the user can open and close the list. the child rows are indented. notice how the guys row only needs one column as it is a placeholder item for its children. the outer treeitem element contains a single treerow element and a treechildren element. the former creates the ...
...rrange the order of the columns. a user will also likely want to change the column widths. you can do this by placing a splitter element in between each treecol element. a small notch will appear in between each column header which the user may drag to change the width of a column. you can use the style class tree-splitter to hide the notch, although the column may still be resized. you can set a minimum or maximum width of a column using the minwidth or maxwidth attributes. you can set the hidden attribute on a column to true to have the column hidden by default. the user can choose to show the column by selecting it from the drop-down on the end of the header row. remembering state of columns as with all elements, the persist attribute can be used to save the state of the columns in...
Simple Menu Bars - Archive of obsolete content
ced in a menupopup. you can customize the menus on the menubar to have whatever you want on them on all platforms except the macintosh. this is because the macintosh has its own special menu along the top of the screen controlled by the system. although you can create custom menus, any special style rules or non-menu elements that you place on a menu may not be applied. you should keep this is mind when creating menus. example of a simple menu bar example 1 : source view <toolbox flex="1"> <menubar id="sample-menubar"> <menu id="file-menu" label="file"> <menupopup id="file-popup"> <menuitem label="new"/> <menuitem label="open"/> <menuitem label="save"/> <menuseparator/> <menuitem label="exit"/> </menupopup> </menu> <me...
...f box. this means that you could create a vertical menubar by setting the orient attribute to vertical. menu element the menu element works much like the button element. it accepts some of the same attributes plus some additional ones: id the unique identifier of the menu title button. label the text to appear on the menu, such as file or edit. disabled this boolean attribute determines whether the menu is disabled. although you can, there's rarely a need to disable an entire menu. this attribute can be set to either true or false. of course, the latter is the default. accesskey this is the key that the user can press to activate the menu item. this letter is typically shown underlined on the menu title. mozilla will look at the label attribute and add an underline charac...
...menuseparators would be placed on a menupopup. you can place any element on a menupopup, however they will be ignored on a macintosh. menuitem element the menuitem element is much like the menu element and has some of the same attributes. id the unique identifier of the menu item. label the text to appear on the menu item, such as open or save. disabled this boolean attribute determines whether the menu item is disabled. this attribute can be set to either true or false where the latter is the default. accesskey this is the key that the user can press to activate the menu item. this letter is typically shown underlined on the menu title. mozilla will look at the label attribute and add an underline character to the character specified here. for that reason, you should spe...
Using Spacers - Archive of obsolete content
acer is shown below. insert it just before the find button. <spacer flex="1"/> <button id="find-button" label="find"/> more about flexibility xul lays out elements on a window by calculating suitable widths and heights for the elements and then adding space where they are flexible. unless you specify information about the width and height of an element, the default size of an element is determined by its contents. you'll notice that the cancel button in the dialogs has always set its width so that it fits the text inside it. if you create a button with a very long label, the button's default size will be large enough to hold the entire label. other elements, such as the text box have chosen a suitable default size. the flex attribute is used to specify if an element can change size to fi...
...ll grow at twice the rate of the first one. in effect, a flex of 2 says that this element has a flex that is two times the elements that have a flex of one. the flex attribute isn't used to specify an actual size. instead, it specifies how empty space it divided among the children of a container box. we'll look at boxes in the next section. once the default sizes of the children of a box are determined, the flexibility values are used to divide up the remaining empty space in the box. for example, if a box is 200 pixels wide and contains two flexible buttons, the first 50 pixels and the other 90 pixels, there will be 60 pixels of space left over. if both buttons have a flex value of 1, the space will be divided evenly with 30 extra pixels of width going to each button. if the second button's ...
... the effect would be the same if the flex attributes were left out. example 6 because the flex values are the same on both buttons, they will flex equally. this would work just as well with flex values of one instead of 145. there's no difference in this case. it is recommended that you use lower numbers for readability. note that other factors, such as the button labels and button minimum sizes, will affect the actual sizes of the buttons. for instance, a button won't shrink less than the space needed to fit its label. specifying a flex value of 0 has the same effect as leaving the flex attribute out entirely. it means that the element is not flexible at all. you may also sometimes see a flex value specified as a percentage. this has no special meaning and is treated as if the...
XPCOM Interfaces - Archive of obsolete content
aces. it is for these reasons that two steps are involved in getting an interface to call functions through. however, there is a shortcut we can use because we'll often use both of these lines together: var alocalfile = components.classes["@mozilla.org/file/local;1"].createinstance(components.interfaces.nsilocalfile); this will do the same thing as the two lines but in one line of code. it eliminates the need to create the instance and then query it for an interface in two separate steps. if you call queryinterface() on an object and the requested interface is not supported by an object, an exception is thrown. if you're not sure that an interface is supported by a component, you can use the instanceof operator to check: var afile = components.classes["@mozilla.org/file/local;1"].create...
...l/mozilla'. leafname the filename without the directory part. filesize the size of the file. isdirectory() returns true if the nsilocalfile represents a directory. remove(recursive) deletes a file. if the recursive parameter is true, a directory and all of its files and subdirectories will also be deleted. copyto(directory,newname) copies a file to another directory, optionally renaming the file. the directory should be a nsilocalfile holding the directory to copy the file to. moveto(directory,newname) moves a file to another directory, or renames a file. the directory should be a nsilocalfile holding the directory to move the file to. in order to delete a file we first need to assign a file to the nsilocalfile. we can call the method initwithpath() to indicate which file ...
...you do not create instances of them because only one should exist. services provide general functions which either get or set global data or perform operations on other objects. instead of calling createinstance(), you call getservice() to get...
Writing Skinnable XUL and CSS - Archive of obsolete content
in our particular mozilla skin, there is a special package calledglobal. this package contains a special skin called theglobal skin. ...
...e seeing are being caused by people writing buggy or syntactically incorrect css. read the spec! study a book! know it! love it! make it a part of you! each skin has a master skin file. the skin for a package should always have a master skin file whose name corresponds to the name of the package. for example, the skin for the navigator package should contain a file called navigator.css that determines the default look of all xul windows posed from this package. if inheriting the global skin, a skin file must import the global skin explicitly. if your skin file wishes to inherit the global skin, then it should import the global skin explicitly. this is done using an @import directive placed at the top of the file. @import url(chrome://global/skin/) ... rest of skin file ... css files f...
...vely grotesque. i'll show you the evil rule i put into the global skin a few months back that was making trees slow. treehead treerow treecell { bad! evil! yuck! ... } this evil rule caused the style system, for every treecell that wasn't in a treehead (which is practically every treecell in a typical tree), to crawl up the whole parent chain to the root of the document in order to determine that the style rule wasn't a match. i'm usually seeing this rule misused by people who really wanted to use the child selector instead. that was my mistake with the above rule. i should have used treehead > treerow > treecell. after all, that's what i meant anyway. never use an attribute selector rule for the class attribute. this is inefficient and you should just use the class notation (...
arrowscrollbox - Archive of obsolete content
if false,...
...if false, the mouse ...
... the tab order is the order in which the focus is moved when the user presses the "tab" key. elements with a higher tabindex are later in the tab sequence. properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width disabled type: boolean gets and sets the value of the disabled attribute. scrollboxobject type: nsiscrollboxobject the scroll box object implements the nsiscrollboxobject interface, which may be used to re...
assign - Archive of obsolete content
s the variable to assign the value to; otherwise it's a reference to a template variable such as "?name". ...
...ble to assign the value to; otherwise it's a reference to a template variable such as "?name". ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
bbox - Archive of obsolete content
Archive › Mozilla › XUL › bbox
to using an hbox element with an align attribute set to baseline. ...
...n hbox element with an align attribute set to baseline. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
binding - Archive of obsolete content
f a rule. properties object, predicate, subject examples fixme: (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties object type: string the object of the element. it can be a variable reference, an rdf resource uri, or an rdf l...
... or property to match. this must be a uri of the property. subject type: string the subject of the element. it can be a variable reference or an rdf resource uri. ...
...y to match. this must be a uri of the property. subject type: string the subject of the element. it can be a variable reference or an rdf resource uri. ...
bindings - Archive of obsolete content
ule element. more information is available in the template guide. examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width object type: string the object of the element. it can be a variable reference, an rdf resource uri, or an rdf literal val...
... match. this must be a uri of the property. subject type: string the subject of the element. it can be a variable reference or an rdf resource uri. ...
...s must be a uri of the property. subject type: string the subject of the element. it can be a variable reference or an rdf resource uri. ...
broadcaster - Archive of obsolete content
ation is available in the broadcasters and observers xul tutorial. ...
...ailable in the broadcasters and observers xul tutorial. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
broadcasterset - Archive of obsolete content
not displayed. more information is available in the xul tutorial. ...
...ed. more information is available in the xul tutorial. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
columns - Archive of obsolete content
information about columns is available in the xul tutorial. example see grid for an example. ...
... about columns is available in the xul tutorial. example see grid for an example. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
conditions - Archive of obsolete content
query element. more information is available in the xul tutorial. ...
...nt. more information is available in the xul tutorial. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
grippy - Archive of obsolete content
the splitter. more information is available in the xul tutorial. ...
...er. more information is available in the xul tutorial. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
groupbox - Archive of obsolete content
hite"/> <radio label="colour"/> </radiogroup> <checkbox label="enabled"/> </groupbox> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the ele...
... top, uri, wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the element. ...
...wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the element. ...
listcell - Archive of obsolete content
to enable the element, leave this attribute out entirely. visible controls have a disabled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. image type: uri the uri of the image to appear on the element. if this attribute is empty or left out, no image appears. the position of the image is determined by the dir and orient attributes. label type: string the label that will appear on the element. if this is left out, no text appears. for an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. type type: string this attribute is reserved for use by anonymous children of listitem; do not use. ...
...d for use by anonymous children of listitem; do not use. properties disabled type: boolean gets and sets the value of the disabled attribute. ...
...y anonymous children of listitem; do not use. properties disabled type: boolean gets and sets the value of the disabled attribute. ...
menulist - Archive of obsolete content
dered as a textbox with a drop-down arrow beside it. the user may enter text into the textbox or select one of the choices by clicking from the drop-down. focused type: boolean this attribute is true if the element is focused. image type: uri the uri of the image to appear on the element. if this attribute is empty or left out, no image appears. the position of the image is determined by the dir and orient attributes. label type: string the label that will appear on the element. if this is left out, no text appears. for an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. oncommand type: script code this event handler is called when the command is activated. this occurs whe...
.... this attribute only has any effect when used inside a prefwindow. more information is available in the preferences system article. readonly type: boolean if set to true, then the user cannot change the value of the element. however, the value may still be modified by a script. sizetopopup type: one of the values below indicates how the menu width and the menupopup width are determined. if the sizetopopup attribute is left out or set to none, the menu will be its preferred width and the popup may extend outside of this width, unaffected by the maximum width of the menu itself. otherwise, the menu will size itself to at least the size of the popup. if the menu has a maximum width, the popup will also be this width. none the width of the popup will not be constrained to...
...wise, the menu will size itself to at least the size of the popup. if the menu has a maximum width, the popup will also be this width. none the width of the popup will not be constrained to the size of the menu. pref the preferred width of the menu label or button will be the size needed for the popup contents. this is the default value for menulists. always both the preferred and minimum width of the menu label or button will be the same as that necessary for the menupopup. tabindex type: integer the tab order of the element. the tab order is the order in which the focus is moved when the user presses the "tab" key. elements with a higher tabindex are later in the tab sequence. value type: string the string attribute allows you to associate a data value wi...
notificationbox - Archive of obsolete content
this pro...
...this property is re...
... , image , priority , buttons, eventcallback ) return type: element create a new notification and display it. if another notification is already present with a higher priority, the new notification will be added behind it. label - label to appear on the notification. this should be either a string, or, from gecko 37 onwards, you can pass a documentfragment with rich content as well. 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. value - value used to identify the notification image - url of image to appear on the notification. if "" then an icon appropriate for the priority level is used. priority - notification priority; see priority levels. buttons - array of button descriptions to appear o...
observes - Archive of obsolete content
not observed. element type: id the id of the broadcaster element that the observer is observing. ...
...d. element type: id the id of the broadcaster element that the observer is observing. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
page - Archive of obsolete content
Archive › Mozilla › XUL › page
should be used for xul files that are to be loaded into an iframe. ...
...sed for xul files that are to be loaded into an iframe. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
query - Archive of obsolete content
Archive › Mozilla › XUL › query
which returns results. any namespace prefixes declared on the element may be used within the expression. ...
...rns results. any namespace prefixes declared on the element may be used within the expression. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
queryset - Archive of obsolete content
query elements when more than one query is used. for more information, see multiple queries. ...
...ents when more than one query is used. for more information, see multiple queries. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
resizer - Archive of obsolete content
lly, this type of resizer element will be hidden and ensure that the window does not get an extra resizer. ...
...ype of resizer element will be hidden and ensure that the window does not get an extra resizer. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
rows - Archive of obsolete content
Archive › Mozilla › XUL › rows
e rows. more information is available in the xul tutorial. example see grid for an example. ...
...re information is available in the xul tutorial. example see grid for an example. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
script - Archive of obsolete content
used (like you get when including a javascript file from web content without specifying a version number). ...
...you get when including a javascript file from web content without specifying a version number). ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
scrollcorner - Archive of obsolete content
r the small box where the horizontal and vertical scrollbars meet. ...
... box where the horizontal and vertical scrollbars meet. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
separator - Archive of obsolete content
ates vertically placed elements. vertical the separator separates horizontally placed elements. ...
...ally placed elements. vertical the separator separates horizontally placed elements. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
spinbuttons - Archive of obsolete content
nce, spinbuttons are used for the number type textbox, and with the timepicker and datepicker. ...
...ttons are used for the number type textbox, and with the timepicker and datepicker. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
stringbundleset - Archive of obsolete content
s | methods | related ] a container for stringbundle elements. ...
...s | related ] a container for stringbundle elements. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
tabpanel - Archive of obsolete content
n place of it. more information is available in the xul tutorial. ...
...it. more information is available in the xul tutorial. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
template - Archive of obsolete content
ied, the variable specified in the uri attribute in the action body of the template's first rule is used. ...
...riable specified in the uri attribute in the action body of the template's first rule is used. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
textnode - Archive of obsolete content
es value type: uri the text value to display. this value should be an rdf property (predicate). ...
...lue type: uri the text value to display. this value should be an rdf property (predicate). ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
toolbar - Archive of obsolete content
en a toolbar is first displayed. in earlier versions, a copy of each item was created and placed on the toolbar. this means that the palette now only contains items not already in the toolbar. this introduces a potential compatibility problem for extensions that depend on being able to identify all possible toolbar items by looking in the toolbarpalette. ...
...nubar" and a menubar element. currentset not in seamonkey 1.x type: comma-separated string the current set of displayed items on the toolbar. this will be modified when the user customizes the toolbar. the value of this attribute should be a comma-separated list of item ids from the toolbarpalette or, additionally, any of the following strings: "separator", "spring", "spacer". customindex not in seamonkey 1.x type: integer this value is the index of the toolbar in the list of the custom toolbars. the value is updated automatically by the toolbar customization dialog. customizable not in seamonkey 1.x type: boolean set this attribute to true on toolbars that can be customized. this causes the set of buttons to be persisted across sessions. defaultset not in se...
...ext seamonkey only type: string the text to appear on the tooltip for the toolbar's grippy when the toolbar is collapsed. this would be used to label the grippy so that the user knows which toolbar it represents. height type: string (representing an integer) the preferred height of the element in pixels. the actual displayed height may be different if the element or its contents have a minimum or maximum height. the css height property may also be used. iconsize type: string indicates whether the toolbar should display large icons or small icons; this should be the string "large" or "small", respectively. these can vary from one toolbar to another within a given toolbox, whose iconsize attribute defines the default for all toolbars that don't specify an icon size. m...
toolbarbutton - Archive of obsolete content
rent behavior for how the states are adjusted, set the autocheck attribute to false and adjust the state with a script. the type attribute must be set to checkbox for buttons with a check state. constants for the possible values for this attribute are in the nsidomxulbuttonelement interface. checked type: boolean indicates whether the element is checked or not. use hasattribute() to determine whether this attribute is set instead of getattribute(). for buttons, the type attribute must be set to checkbox or radio for this attribute to have any effect. command type: id set to the id of a command element that is being observed by the element. crop type: one of the values below if the label of the element is too big to fit in its given space, the text ...
... buttons with type="radio" and the same value for their group attribute are put into the same group. only one button from each group can be checked at a time. if the user selects one the buttons, the others in the group are unchecked. image type: uri the uri of the image to appear on the element. if this attribute is empty or left out, no image appears. the position of the image is determined by the dir and orient attributes. label type: string the label that will appear on the element. if this is left out, no text appears. for an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. oncommand type: script code this event handler is called when the command is activated. this occurs whe...
...bindex are later in the tab sequence. title type: string this functionality only applies when toolbarbutton is used in the customize toolbar dialog. the text that is displayed as a button's label when it's in the customize toolbar palette. it overrides the value of label, which is used if title is not set. this does not affect the button's label when it is in a toolbar, which remains determined by the label attribute. type type: string the type of button. if this attribute is not present, a normal button is created. you can set this attribute to the value menu to create a button with a menu popup. this will typically cause the button to be displayed differently. menu: set the type attribute to the value menu to create a button with a menu popup. place a menupopup element ...
toolbargrippy - Archive of obsolete content
ation is available in the xul tutorial. properties accessible examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties accessible type: nsiaccessible returns the accessibility object for the element. inheri...
...ltip, tooltiptext, top, uri, wait-cursor, width properties accessible type: nsiaccessible returns the accessibility object for the element. ...
...iptext, top, uri, wait-cursor, width properties accessible type: nsiaccessible returns the accessibility object for the element. ...
toolbarseparator - Archive of obsolete content
1"/> <toolbarseparator /> <toolbarbutton label="button 2"/> </toolbar> </toolbox> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the eleme...
...xt, top, uri, wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the element. ...
...i, wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the element. ...
toolbarset - Archive of obsolete content
ner for custom toolbars, which are added in the custom toolbar dialog. ...
...tom toolbars, which are added in the custom toolbar dialog. ...
...querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundi...
treecell - Archive of obsolete content
ree must be a content tree for this to work on treecells. label type: string the label that will appear on the element. if this is left out, no text appears. for an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. mode type: one of the values below for columns that are progress meters, this determines the type of progress meter to use. none no progress meter is displayed. the cell text is displayed instead. normal the cell uses its value attribute to determine the amount of the bar that is filled in. undetermined the progressmeter is indeterminate. properties type: space-separated list of property names sets the properties of the element, which can be used to sty...
....value syntax. for those elements, setattribute("value", myvalue) and getattribute("value") do not access or affect the contents displayed to the user. ...
...ax. for those elements, setattribute("value", myvalue) and getattribute("value") do not access or affect the contents displayed to the user. ...
treechildren - Archive of obsolete content
ee's rows will alternate between two colors. you can use the :-moz-tree-row css style to do this instead. ...
...ill alternate between two colors. you can use the :-moz-tree-row css style to do this instead. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
treerow - Archive of obsolete content
perties of the element, which can be used to style the element. for more information, see styling a tree. ...
...the element, which can be used to style the element. for more information, see styling a tree. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
treeseparator - Archive of obsolete content
perties of the element, which can be used to style the element. for more information, see styling a tree. ...
...the element, which can be used to style the element. for more information, see styling a tree. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
where - Archive of obsolete content
Archive › Mozilla › XUL › where
bject type: string the variable or string to compare. value type: string the value to compare. ...
...: string the variable or string to compare. value type: string the value to compare. ...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
Application Update - Archive of obsolete content
// whether or not app updates are enabled pref("app.update.enabled", true); // this preference turns on app.update.mode and allows automatic download and // install to take place. we use a separate boolean toggle for this to make // the ui easier to construct. pref("app.update.auto", true); // defines how the application update service notifies the user about updates: // // aum set to: minor releases: major releases: // 0 download no prompt download no prompt // 1 download no prompt download no prompt if no incompatibilities // 2 download no prompt prompt // // see chart in nsupdateservice.js.in for more details // pref("app.update.mode", 1); // if set to true, the update service will present no ui for any event. pref("app.
...this is off in firefox by default since we show a // upgrade start page instead! other apps may wish to sh...
...pp.update.nagtimer.download", 86400); // interval: time before prompting the user to restart to install the latest // download (in seconds) default=30 minutes pref("app.update.nagtimer.restart", 1800); // interval: when all registered timers should be checked (in milliseconds) // default=5 seconds pref("app.update.timer", 600000); // whether or not we show a dialog box informing the user that the update was // successfully applied. this is off in firefox by default since we show a // upgrade start page instead! other apps may wish to show this ui, and supply // a whatsnewurl field in their brand.properties that contains a link to a page // which tells users what's new in this new update. pref("app.update.showinstalledui", false); // 0 = suppress prompting for incompati...
2006-10-26 - Archive of obsolete content
of search engine cloaking mark describes the magic of search engine cloaker. (what it is, how to use it) cross-post-and followup fx2 announcment to support-firefox request for when the announcement about firefox 2's release to be posted on the mozilla.dev.apps.firefox newsgroup. firefox killer features suggestion john describes his suggestions for "killer features" for firefox. debug minefield on intel mac an inqury about how to debug minefield on an intel mac. rebuild firefox after modifying source code an inqury about how to rebuild the code after making a minor change - the user is unfamiliar with how to use the command prompt. bug in firefox when import passwords from seamonkey a possible bug find - perhaps a version error instead? there should be a 'changes' faq ...
... nsialertsservice under linux an inqury about why nsialertsservice is not a service found in firefox 2. is this a bug in firefox? an inqury about inaccurate layout for firefox being a bug - shaver suggests its a bug with gecko instead. ...
... bug - shaver suggests its a bug with gecko instead. ...
2006-10-27 - Archive of obsolete content
of search engine cloaking mark describes the magic of search engine cloaker. (what it is, how to use it) cross-post-and followup fx2 announcment to support-firefox request for when the announcement about firefox 2's release to be posted on the mozilla.dev.apps.firefox newsgroup. firefox killer features suggestion john describes his suggestions for "killer features" for firefox. debug minefield on intel mac an inqury about how to debug minefield on an intel mac. rebuild firefox after modifying source code an inqury about how to rebuild the code after making a minor change - the user is unfamiliar with how to use the command prompt. bug in firefox when import passwords from seamonkey a possible bug find - perhaps a version error instead? there should be a 'changes' faq ...
... nsialertsservice under linux an inqury about why nsialertsservice is not a service found in firefox 2. is this a bug in firefox? an inqury about inaccurate layout for firefox being a bug - shaver suggests its a bug with gecko instead. ...
... bug - shaver suggests its a bug with gecko instead. ...
Shipping a plugin as a Toolkit bundle - Archive of obsolete content
every add-on must have a unique id. this can be in a guid form but the simpler email form is preferred now. you should aim to use a domain-name that you own and then your ...
... every add-on must have a unique id. this can be in a guid form but the simpler email form is preferred now. you should aim to use a domain-name that you own and then your own unique short-na...
...use a domain-name that you own and then your own unique short-name for the plugin before the @. the plugin must have a name to identify the plugin to the user in the list of add-ons. the version is fairly self-descriptive, it must be a toolkit version format. the target application block says which versions of an application the plugin is compatible with. it includes the application id and the minimum and maximum version of the application that the plugin works with. there can be multiple targetapplication blocks listed. 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. providing updates when plugins are packaged in this way they can make use of the built in add-on update system. this allo...
Encryption and Decryption - Archive of obsolete content
a cryptographic algorithm, also called a cipher, is a mathematical function used for encryption or decryption. in most cases, two related functions are employed, one for encryption and the other for decryption. with most modern cryptography, the ability to keep encrypted information secret is based not on the cryptographic algorithm, which is widely known, but on a number called a key that must be used with the algorithm to produce an encrypted result or to decrypt previously encrypted information. ...
...hat the message was signed with your private key and that it hasn't been tampered with since being signed. "digital signatures" describes how this confirmation process works. key length and encryption strength breaking an encryption algorithm is basically finding the key to the access the encrypted data in plain text. for symmetric algorithms, breaking the algorithm usually means trying to determine the key used to encrypt the text. for a public key algorithm, breaking the algorithm usually means acquiring the shared secret information between two recipients. one method of breaking a symmetric algorithm is to simply try every key within the full algorithm until the right key is found. for public key algorithms, since half of the key pair is publicly known, the other half (private key) can ...
...nce half of the key pair is publicly known, the other half (private key) can be derived using published, though complex, mathematical calculations. manually finding the key to break an algorithm is called a brute force attack. breaking an algorithm introduces the risk of intercepting, or even impersonating and fraudulently verifying, private information. the key strength of an algorithm is determined by finding the fastest method to break the algorithm and comparing it to a brute force attack. for symmetric keys, encryption strength is often described in terms of the size or length of the keys used to perform the encryption: in general, longer keys provide stronger encryption. key length is measured in bits. for example, 128-bit keys for use with the rc4 symmetric-key cipher supported by s...
Security - Archive of obsolete content
ity articles is highly discouraged. doing so may put your systems at risk. digital signaturesencryption and decryption address the problem of eavesdropping, one of the three internet security issues mentioned at the beginning of this document. ...
...cryption address the problem of eavesdropping, one of the three internet security issues mentioned at the beginning of this document. but encryption and decryption, by themselves, do not address another problem: tampering.encryption and decryptionencryption is the process of transforming information so it is unintelligible to anyone but the intended recipient. decryption is the process of transforming encrypted information so that it is intelligible again.introduction to public-key cryptographypublic-key cryptography and related standards and techniques underlie the security features of many products such as signed and encrypted email, single sign-on, and secure sockets layer (ssl) communications. this document introduces the basic concepts of public-key cryptography. for an overview of ssl, ...
...cryption, see "encryption and decryption." information on digital signatures is available from "digital signatures." introduction to sslthis document introduces the secure sockets layer (ssl) protocol. ssl has been universally accepted on the world wide web for authenticated and encrypted communication between clients and servers.nspr release engineering guidethis paper is for engineers performing formal release for the netscape portable runtime (nspr) across all platforms.ssl and tlsthe secure sockets layer (ssl) and transport layer security (tls) protocols are universally accepted standards for authenticated and encrypted communication between clients and servers. both client and server authentication occur over ssl/tls. ...
Building a Theme - Archive of obsolete content
ion's folder hierarchy and put this inside: <?xml version="1.0"?> <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest"> <em:id>sample@example.net</em:id> <em:version>1.0</em:version> <em:type>4</em:type> <!-- target application this theme can install into, with minimum and maximum supported versions. --> <em:targetapplication> <description> <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> <em:minversion>29.0</em:minversion> <em:maxversion>39.*</em:maxversion> </description> </em:targetapplication> <!-- front end metadata --> <em:name>my theme</em:name> <em:internalname>sample</em:internalname> ...
...(example.example.example) 4 - the type of the add-on. '4' declares that it is installing a theme. if you were to install an extension it would be 2 (see install manifests#type for other type codes). {ec8030f7-c20a-464f-9b0e-13a3a9e97384} - firefox's application id. 29.0 - the exact version number of the earliest version of firefox you're saying this extension will work with. never use a * in a minversion, it almost certainly will not do what you expect it to. 39.* - the maximum version of firefox you're saying this extension will work with. set this to be no newer than the newest currently available version! in this case, "39.*" indicates that the extension works with firefox 39 and any subsequent 39.x release. themes are compatible by default, unless you set strict compatibility mode for...
...know css, it's going to be a steep learning curve, and you may want to try some html-based tutorials to start with. the browser ui has absolutely no styling on its own - if you try to start up with an empty theme, firefox will be unusable, as the button elements will be drawn as plain text. this is why we copied the default styles in the setup step. when writing a theme, the easiest way to determine what css selectors you need to write is to use the dom inspector which you should have installed in the setup step. you can use this to inspect any element in a web page or an xul document, which makes it invaluable for themes. updating the toolbar's styling note in firefox 4.0 and up, the highlight feature of dom inspector is broken. to workaround this, disable hardware acceleration in firef...
Settings - Archive of obsolete content
pause on exceptions when this option is enabled, execution of the script will automatically pause whenever a javascript exception is thrown. ...
... pause on exceptions when this option is enabled, execution of the script will automatically pause whenever a javascript exception is thrown. ...
...lay non-enumerable javascript properties. show variables filter box enabling this option adds a "filter variables" search box to the variables pane, so that you can filter the displayed list of variables. show original sources enabling this option will make the debugger use source maps, if they are available, to display the original source for code which has been combined, minified, or even compiled to javascript from a language like coffeescript. defaults to true. automatically black box minified sources new in firefox 33. automatically black box sources whose url ends with ".min.js". defaults to true. ...
Scratchpad - Archive of obsolete content
scratchpad is deprecated as of firefox 70 (bug 1565380), and will be removed as of firefox 72 (bug 1519103). as an alternative, starting in firefox 71, you can use the multi-line mode of the javascript console input. scratchpad provides an environment for experimenting with javascript code. you can write, run, and examine the results of code that interacts with the web page. unlike the web console, which is designed for interpreting a single line of code at a time, scratchpad lets you edit larger chunks of javascript code, then execute it in various ways depending on how you want to use the output. the featured video tutorial shows a case of using scratchpad with a page run by a local web server. it is also possible to use scratchpad over pages opened from a local file system, if per...
...there are four execution options available. run when you choose the run option, the selected code is executed. this is what you'd use to execute a function or other code that manipulates the content of your page without needing to see the result. inspect the inspect option executes the code just like the run option; however, after the code returns, an object inspector is opened to let you examine the returned value. for example, if you enter the code: window then choose inspect, the object inspector is shown that looks something like this: display the display option executes the selected code, then inserts the result directly into your scratchpad editor window as a comment, so you can use it as a repl. reload and run the reload and run option is only available in the execute me...
...of the browser as a whole rather than a specific web page. this is useful if you are working on firefox itself or developing add-ons. to do this check "enable chrome and add-on debugging" in the developer tool settings. once you've done this, the environment menu has a browser option; once that's selected, your scope is the entire browser rather than just the page content, as you will see from examining some globals: window /* [object chromewindow] */ gbrowser /* [object xulelement] */ the scratchpad execution context is set to browser when a snippet file has // -sp-context: browser on the first line. keyboard shortcuts command windows macos linux open the scratchpad shift + f4 shift + f4 shift + f4 run scratchpad code ctrl + r cmd + r...
Updating an extension to support multiple Mozilla applications - Archive of obsolete content
ifest the first step is to revise the extension's install manifest to indicate that it can be installed in thunderbird and sunbird. ...
...p is to revise the extension's install manifest to indicate that it can be installed in thunderbird and sunbird. ...
... <description> <em:id>{3550f703-e582-4d05-9a08-453d09bdfdc6}</em:id> <em:minversion>1.5</em:minversion> <em:maxversion>2.0.0.*</em:maxversion> </description> </em:targetapplication> <!-- describe the sunbird versions we support --> <em:targetapplication> <description> <em:id> {718e30fb-e89b-41dd-9da7-e25a45638b28}</em:id> <em:minversion>0.2</em:minversion> <em:maxversion>0.4.*</em:maxversion> </description> </em:targetapplication> these two blocks indicate that the extension supports thunderbird versions 1.5 through 2.0.0.x, sunbird versions 0.2 through 0.4.x. after inserting this code, you can successfully install the extension into any (or all) of firefox, thunderbird, and sunbird, but you won't see a...
Using workers in extensions - Archive of obsolete content
xtension's code to update the display in the status bar. this demonstrates not only how to use workers in an extension, but also how to perform xmlhttprequest in a worker, and how workers and main thread code can pass data back and forth. the worker the worker thread's job in this example is to issue the xmlhttprequest calls that fetch the updated stock information. that's all it does. every 10 minutes, it calls xmlhttprequest, and, when the results are received, sends an event back to the main thread with the received data. so we need to move the refreshinformation() method from the stockwatcher2.js file into a separate file that will host the worker thread. that file, ticker_worker.js, is shown here: var symbol = ""; function refreshinformation() { if (!symbol) { throw "no symbol...
...uest.send(null); } setinterval(function() { refreshinformation(); }, 10*60*1000); onmessage = function(event) { if (event.data) { symbol = event.data.touppercase(); } refreshinformation(); } when the worker thread is started, the main body of this code (in lines 26-35) is executed. it starts by setting up an interval handler (in lines 26-28) that calls refreshinformation() every 10 minutes. then it sets the worker's onmessage event handler to a function which looks at the event passed into it, and does one of two things: if there is a data field on the event, the stock symbol being tracked is set to the upper case version of that value. this is used to initialize the worker, and to change which stock is being monitored. if there is no data field, the refreshinformation() m...
...ol has not been set yet, an exception is thrown (lines 4-6). 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. this is because only the main thread is allowed to access the user interface. the main thread the changes here are also relatively minor, but crucial. the startup() method this method is called when the extension is first loaded, and needs to be updated to start up and configure the worker. let's take a look: startup: function() { // register to receive notifications of preference changes this.prefs = components.classes["@mozilla.org/preferences-service;1"] .getservice(components.interfaces.nsiprefservice...
-ms-content-zoom-limit - Archive of obsolete content
the -ms-content-zoom-limit css shorthand property is a microsoft extension that specifies values for the -ms-content-zoom-limit-min and -ms-content-zoom-limit-max properties. initial valueas each of the properties of the shorthand:-ms-content-zoom-limit-max: 400%-ms-content-zoom-limit-min: 100%applies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednopercentagesas each of the properties of the shorthand:-ms-content-zoom-limit-max: the largest allowed zoom factor. a zoom factor of 100% corresponds to no zooming. larger values zoom in. smaller values zoom out.-ms-content-zoom-limit-min: the smallest allowed zoom factor. a zoom factor of 100% corresponds to no zooming. larger values zoom in. smaller values zoom out.computed valueas each of the properties...
...gest allowed zoom factor. a zoom factor of 100% corresponds to no zooming. larger values zoom in. smaller values zoom out.-ms-content-zoom-limit-min: the smallest allowed zoom factor. a zoom factor of 100% corresponds to no zooming. larger values zoom in. smaller values zoom out.computed valueas each of the properties of the shorthand:-ms-content-zoom-limit-max: as specified-ms-content-zoom-limit-min: as specifiedanimation typediscrete syntax the -ms-content-zoom-limit shorthand property is specified as one or both of the following content zoom limit values, in order, separated by spaces. values -ms-content-zoom-limit-min value of the -ms-content-zoom-limit-min property. -ms-content-zoom-limit-max value of the -ms-content-zoom-limit-max property. formal syntax <'-ms-content-zoom...
...ecifiedanimation typediscrete syntax the -ms-content-zoom-limit shorthand property is specified as one or both of the following content zoom limit values, in order, separated by spaces. values -ms-content-zoom-limit-min value of the -ms-content-zoom-limit-min property. -ms-content-zoom-limit-max value of the -ms-content-zoom-limit-max property. formal syntax <'-ms-content-zoom-limit-min'> <'-ms-content-zoom-limit-max'> specifications not part of any specification. remarks this property has no effect on non-zoomable elements. see -ms-content-zooming for details on zoomable elements. starting with windows 8.1, this property is also supported for touchpad interaction. this property requires windows 8 or later. ...
-ms-content-zoom-snap-type - Archive of obsolete content
after the contact is picked up, the content will continue to move with inertia. proximity indicates that the motion of the content after the contact is picked up may be adjusted if the content would normally stop "close enough" to a snap-point. ...
...after the contact is picked up, the content will continue to move with inertia. proximity indicates that the motion of the content after the contact is picked up may be adjusted if the content would normally stop "close enough" to a snap-point. ...
...otion of the content after the contact is picked up is always adjusted so that it lands on a snap-point. the snap-point that is selected is the one that is closest to where the content zoom factor would normally stop. formal syntax none | proximity | mandatory specifications not part of any specification. remarks this property has no effect on non-zoomable elements. see -ms-content-zooming for details on zoomable elements. when a user pans or scrolls and then lifts his or her contact (for instance, a finger), the content can continue to move with inertia. snap-points can change the animation that runs when the user lifts his or her finger so that you can adjust where the content will stop. by placing snap-points, you can make it easy for your users to manipulate your content and ...
-ms-scroll-chaining - Archive of obsolete content
property set to chained, which means that when a user is scrolling through a nested scrollable element and it hits its boundary the parent scrollable element will begin to scroll in the same direction. had the -ms-scroll-chaining property been set to none, the user would observe a bounce effect when the nested element reaches its boundary. ...
...ling through a nested scrollable element and it hits its boundary the parent scrollable element will begin to scroll in the same direction. had the -ms-scroll-chaining property been set to none, the user would observe a bounce effect when the nested element reaches its boundary. for more information, see html scrolling, panning and zooming sample or internet explorer 10 scrolling, panning, and zooming with touch. ...
...oll in the same direction. had the -ms-scroll-chaining property been set to none, the user would observe a bounce effect when the nested element reaches its boundary. for more information, see html scrolling, panning and zooming sample or internet explorer 10 scrolling, panning, and zooming with touch. .imagecontainer { -ms-scroll-chaining: chained; -ms-overflow-style: none; -ms-content-zooming: zoom; -ms-scroll-rails: none; -ms-content-zoom-limit-min: 100%; -ms-content-zoom-limit-max: 500%; -ms-scroll-snap-type: proximity; -ms-scroll-snap-points-x: snaplist(100%, 200%, 300%, 400%, 500%); -ms-overflow-style: none; width: 480px; height: 270px; overflow: auto; } specifications not part of any specification. remarks this property only applies to touch and touchpad i...
New in JavaScript 1.8.5 - Archive of obsolete content
erable properties on an object. bug 307791 object.getownpropertynames() returns an array of all enumerable and non-enumerable properties on an object. bug 518663 object.preventextensions() prevents any extensions of an object. bug 492849 object.isextensible() determines if extending of an object is allowed. bug 492849 object.seal() prevents other code from deleting properties of an object. bug 492845 object.issealed() determines if an object is sealed. bug 492845 object.freeze() freezes an object: other code can't delete or cha...
...bug 492844 array.isarray() checks if a variable is an array. ...
...fined syntax has not been changed. these were all pretty esoteric and rarely used; if this affects you, see this blog post for details. new objects object description old proxy api offers support for creating object and function proxies that enable meta-programming in javascript. changed functionality in javascript 1.8.5 iso 8601 support in date: the date object's parse() method now supports simple iso 8601 format date strings. global objects made read only: the nan, infinity, and undefined global objects have been made read only, per the ecmascript 5 specification. ob...
LiveConnect Overview - Archive of obsolete content
this chapter describes using liveconnect technology to let java and javascript code communicate with each other. the chapter assumes you are familiar with java programming. working with wrappers in javascript, a wrapper is an object of the target language data type that encloses an object of the source language. when programming in javascript, you can use a wrapper object to access methods and fields of the java object; calling a method or accessing a property on the wrapper results in a call on the java object. on the java side, javascript objects are wrapped in an instance of the class netscape.javascript.jsobject and passed to java. when a javascript object is sent to java, the runtime engine creates a java wrapper of type jsobject; when a jsobject is sent from java to javascript, ...
...t objects are wrapped in an instance of the class netscape.javascript.jsobject and passed to java. when a javascript object is sent to java, the runtime engine creates a java wrapper of type jsobject; when a jsobject is sent from java to javascript, the runtime engine unwraps it to its original javascript object type. the jsobject class provides an interface for invoking javascript methods and examining javascript properties. javascript to java communication when you refer to a java package or class, or work with a java object or array, you use one of the special liveconnect objects. all javascript access to java takes place with these objects, which are summarized in the following table. table 9.1 the liveconnect objects object description javaarray a wrapped ...
...e are converted to javascript numbers. a java boolean is converted to a javascript boolean. an object of class netscape.javascript.jsobject is converted to the original javascript object. java arrays are converted to a javascript pseudo-array object; this object behaves just like a javascript array object: you can access it with the syntax arrayname[index] (where index is an integer), and determine its length with arrayname.length. a java object of any other class is converted to a javascript wrapper, which can be used to access methods and fields of the java object: converting this wrapper to a string calls the tostring method on the original object. converting to a number calls the doublevalue method, if possible, and fails otherwise. converting to a boolean in javascript 1.
Old Proxy API - Archive of obsolete content
ental feature. do not rely on it for production code. introduction proxies are objects for which the programmer has to define the semantics in javascript. the default object semantics are implemented in the javascript engine, often written in lower-level languages like c++. proxies let the programmer define most of the behavior of an object in javascript. they are said to provide a meta-programming api. terminology catch-all mechanism (or "intercession api") the technical term for this feature. handler the object that intercepts properties. proxy the object whose properties are being intercepted. proxy factory the object or method that creates intercessive proxies. traps the methods that provide property access. this is analogous to the concept of traps in operating systems. ...
... } that reifies “proxy(args)”. note: the this-binding of the calltrap function is the this-binding of the call-site. constructtrap is an optional variable-argument function(args) { return any-object; } that reifies “new proxy(args)”. the this-binding of the constructtrap is either undefined (in strict mode) or the global object (in non-strict mode). if no constructtrap is provided, performing new proxy(...args) calls the proxy’s calltrap with this bound to a new object delegating to the proxy's prototype. handler is an object that implements the handler api. handler api there are two kinds of traps: fundamental and derived traps. if one of the fundamental traps isn't implemented and the proxy is used in a way that expects the fundamental trap to be defined, then an error is thr...
...e emulated object. object.getpropertynames(proxy) getpropertynames: function() -> strings array this function doesn't exist in ecmascript 5. like getownpropertynames, but should also return non-overridden inherited properties. object.defineproperty(proxy,name,pd) defineproperty: function(name, propertydescriptor) -> any define a new property whose attributes are determined by the given propertydescriptor. the return value of this method is ignored. delete proxy.name delete: function(name) -> boolean delete the named property from the proxy. the boolean return value of this method should indicate whether or not the name property was successfully deleted. object.freeze(proxy) object.seal(proxy) object.preventextensions(proxy) ...
background-size - Archive of obsolete content
are based on gecko. both layout engines are mentioned in the table. people should refer to the webkit and gecko version to get the info they need. agreed; we should definitely encourage people to look stuff up by engine rather than browser. ...
...are based on gecko. both layout engines are mentioned in the table. people should refer to the webkit and gecko version to get the info they need. agreed; we should definitely encourage people to look stuff up by engine rather than browser. ...
...ber you have to test yourself, don't trust online references, don't trust webkit | apple | google homepage, they are wrong. don't trust the internet at alll! ] listing konqueror below the table is a compromise for consistency. feel free to put it inside, nothing is set in stone. konqueror's global market share is 0.05%, (< 5% of linux users). given the fact that this reference has serious shortcomings in many places and few contributors, i think spending much time here is not effective. people especially interested in this browser are welcome to contribute. it's hard to get reliable information about its css support without having this browser (read: multiple versions of this browser) installed. are you able and willing to do that for all css properties? if so, feel free to change the en/cs...
Reference - Archive of obsolete content
. well if you combine the two, you can have inherited private variables: function myclass(){ var property = 5; this.tellme = function(){ return property; } } function myotherclass(){ myclass.apply( this ); } var o = new myotherclass; alert( o.tellme() ); //alerts 5 as you'd expect — the preceding comment was added by psygnisfive (talk – contribs) on 22:23, 4 december 2006 terminology we need a terminology appendix. for example, "script" and "program" are synonymous. so are "current object" and "context object". we could also put in layman definitions there for js constructs like functions and variables. --maian 01:43, 30 september 2005 (pdt) we should define the terms we are using. in particular this means we should define activation object somewhere (and link to it whe...
...e (and link to it whenever we mention it). --nickolay 18:40, 16 july 2006 (pdt) js 1.2 and gecko 1.8 per the fix for bug 255895, "javascript1.2" values for the script's language attribute no longer work, e.g. <script language="javascript1.2"> will execute the script in the latest js version rather than js 1.2. so how should this be documented? in fx 1.0, js 1.2 is available, but not in the upcoming fx 1.5. there are 5 cases where "javascript1.2" is mentioned in this reference: special:search?search=javascript1.2&go=go. how should they be revised? --maian 23:43, 21 september 2005 (pdt) i think we need a new section in the reference that specifies the differences between versions, collecting this information into a single location rather than leaving it scattered haphazardly throughout the...
...s supposed to be fixed in the reorganization, which has still yet to occur. sevenspade 22:34, 26 february 2007 (pst) since it doesn't look like the reorganization is going to happen in the very near future, is there any reason i shouldn't take care of this now? ruakh 14:40, 27 february 2007 (pst) please don't start making large changes without getting an ok from dev-mdc. what did you have in mind? fwiw, i brought up the topic of jsref reorg again recently . imo, it's useful to have separates lists for global functions, global constructors, and other global properties on the contents page.--nickolay 19:10, 7 march 2007 (pst) ...
Building Mozilla XForms - Archive of obsolete content
firefox 3.5 and up: get the source code if you want to build xforms for firefox up to 3.0, you already have the required source code, it's part of your cvs checkout. skip to the next section. starting with firefox 3.5, you need to do two more mercurial checkouts: cd extensions hg clon...
.../dist/xpi-stage/xforms.xpi. congratulations, you've successfully built your first mozilla xforms extension! the built xpi file will only install on a nightly snapshot from the same day or your self-built firefox version. ...
...install on a nightly snapshot from the same day or your self-built firefox version. if you are sure that older or newer firefox versions are compatible with your extension, you can unzip the xpi file (it's a regular zip file), edit the install.rdf and change the minversion and maxversion entries. the following scheme usually works (replace {geckoversion} with the used gecko/toolkit version): <em:minversion>{geckoversion}.0</em:minversion> <em:maxversion>{geckoversion}.*</em:maxversion> for example, for the firefox 3.5 version of the extension, it might look like that: <em:minversion>1.9.1.0</em:minversion> <em:maxversion>1.9.1.*</em:maxversion> then zip the files again (or use an editor like vim that can edit files inside a zip archive). ...
Mozilla XForms User Interface - Archive of obsolete content
ing logical groups. ui common the ui common attribute set (see the spec) contains the attributes that are available for the xforms elements that are used to build the user interface presentation in a form. appearance - the value provided by the form author gives a hint to the processor as to which widget to use to represent the xforms control. three possible values are available to the author: minimal, compact and full. generally speaking, the main purpose for these values is to reflect how much space (screen real estate) the displayed widget will take. tabindex - defines the keyboard navigation sequence between controls. accesskey - keyboard shortcut for moving focus to an xforms element. binding attributes single-node (see the spec) and node-set (see the spec) attributes are used to...
...ms elements almost every xforms element can be presented as one of serveral different kinds of widgets. this section contains a short description of each xforms element and its representation. the xforms specification offers suggestions for some of the representations, but some of the widgets we use are only available in the mozilla xforms processor. the choice of widget that we use is often determined by the data type of the instance node that the xforms element is bound to. the form author can also influence the widget by using the appearance attribute on the element. form controls module this section contains a short description for each form control element. input a key xforms element to show and change the instance data to which it is bound. usually bound to data that can be well-represe...
...e image. upload provides a means for the user to select a file (see the spec). range allows the user to choose a value from within a specific range of values. it is represented by a slider widget (see the spec). trigger allows the user to initiate actions (see the spec). it can have the following representations: button - default representation. link/clickable text - used when appearance = 'minimal'. submit invokes the submission of the selected instance data to its target destination, which could be local or remote (see the spec). it can have the following representations: button - default representation. link/clickable text - used when appearance = 'minimal'. select list control. allows the user to choose one or multiple values from a list of pre-defined values (see the spec). ...
RDF in Mozilla FAQ - Archive of obsolete content
r. some examples of datasources that exist today are "browser bookmarks", "browser global history", "imap mail accounts", "nntp news servers", and "rdf/xml files". in mozilla, datasources can be composed together using the composite data source. this is like overlaying graphs, or merging collections of statements ("microtheories") together. statements about the same rdf resource can then be intermingled: for example, the "last visit date" of a particular website comes from the "browser global history" datasource, and the "shortcut keyword" that you can type to reach that website comes from the "browser bookmarks" datasource. both datasources refer to "website" by url: this is the "key" that allows the datasources to be "merged" effectively. for a more detailed account of how to write a data...
...her you'd like it to perform its operation synchronously ("blocking") or asynchrounously ("non-blocking"). you should never do a synchronous load unless you really know what you're doing: this will freeze the ui until the load completes! how can i tell if an rdf/xml datasource has loaded? using the nsirdfremotedatasource interface, it is possible to immediately query the loaded property to determine if the datasource has loaded or not: // get the rdf service var rdf = components .classes["@mozilla.org/rdf/rdf-service;1"] .getservice(components.interfaces.nsirdfservice); // get the datasource. var ds = rdf.getdatasource("http://www.mozilla.org/some-rdf-file.rdf"); // now see if it's loaded or not... var remote = ds.queryinterface(components.interfaces.nsirdfremotedatasource); if (r...
...ed compute the datasources that it wants to display in an onload handler. or, it may need to add a datasource later based on some user action. here's a simple example that illustrates how to do this. let's start with the following xul. <window xmlns="http://www.mozilla.org/keymaster/gat...re.is.only.xul"> ... <tree id="my-tree" datasources="rdf:null"> ... </tree> ... </window> assuming that we've aquired a datasource somehow (e.g., like this), the following sample code illustrates how to add that datasource to the template, and then force the template to rebuild itself based on the newly added datasource's contents. var ds = /* assume we got this somehow! */; // get the dom element for 'my-tree' var tree = document.getelementbyid('my-tree'); // add our datasource to it tree.d...
Game promotion - Game development
sons learned, and the ups and downs of being a game developer. continually publishing information about your games will help educate others, increase your reputation in the community, and further improve seo. a further option is to publish monthly reports that summarize all your progress — it helps you see what you've accomplished throughout the month and what's still left to do, and it keeps reminding people that your game is coming out soon — building buzz is always good. while you can create your website from scratch, there are also tools that can help make the process easier. manakeep is a website builder made for indie game developers and provides a great starting point to create your website. presskit() is a press kit builder that helps you create a press page to share with the m...
...st portals offer revenue share deals or will buy non exclusive license. free portals offer traffic, but only the best ones are popular enough to generate revenues from advertisements on in-app purchases. on the other hand they are a perfect tool to make games visible to a broader audience if you have no budget and limited time. press you can try and reach the press about your game, but bear in mind that they get a tonne of requests like this every single day, so be humble and patient if they don't answer right away, and be polite when talking to them. be sure to check first if they are dealing with specific genres of games or platforms, so you don't send them something that is not relevant to them in the first place. if you're honest with your approach and your game is good, then you've go...
...ssion in comments if people have any questions. if portals you contact are not interested in your content because you don't have any experience yet, try writing tutorials and publish them on your own blog first. it's the easiest way to train your writing skills on your own. youtubers it's a rising trend — don't underestimate the power of youtubers playing your game, talking about it and streaming their experience to give you lots of promotion. you should also be realistic however — don't think this alone will skyrocket your downloads or visits, and be prepared to deal with bad reviews as well as good ones. there are two options to get coverage from the youtubers: first is you contact them directly and send a link to your game via email or private message. the second is earned in time ...
GLSL Shaders - Game development
r you — if you wanted to create such an example in raw webgl, you'd have to write a lot of extra code to actually make it work. environment setup to start with the webgl shaders you don't need much. you should: make sure you are using a modern browser with good webgl support, such as the latest firefox or chrome. create a directory to store your experiments in. ...
...e a directory to store your experiments in. save a copy of the latest minimized three.js library inside your directory. html structure here's the html structure we will use. ...
...e both vertex and texture shaders applied. that's it — you've just created the simplest possible shader, congratulations! here's what the cube should look like: it looks exactly the same as the three.js cube demo but the slightly different position and the same blue color are both achieved using the shader. ...
Visual typescript game engine - Game development
ssible variant by default : * "register", "login" */ private startuphtmlform: string = "register"; private gamelist: any[]; /** * implement default gameplay variable's */ private defaultgameplaylevelname: string = "level1"; private autostartgameplay: boolean = true; start the dependency system from app.ts the first game template is platformer. this is high-level programming in this software. class gameplay extends platformer, it good for start. class starter is base class for my canvas part and matter.ts (matter.js) implementation. it is injected to the platformer to make full operated work. gameslist args for ioc constructor is for now just symbolic for now. (wip) in ioc, you can make strong class dependency relations. use it for your own structural changes. m...
...lear no. node.js is the best options. for email staff, i choose: npm i gmail-send. -run services database server (locally and leave it alive to develop process): npm run dataserver looks like this : mongod --dbpath ./server/database/data fix: "failed: address already in use" : netstat -ano | findstr :27017 taskkill /pid typeyourpidhere /f also important "run visual studio code as administrator". - a command for killing all node.js process for window users : taskkill /im node.exe /f networking multimedia communication: websocketserver running on node.js text-based protocol sip (session initiation protocol) used for signalling and controlling multimedia sessions. general networking config: config property defined in constructor from serverconfig class. this.networkd...
... source: matter.js https://github.com/liabru/matter-js matter.ts used because typescript orientation. https://www.npmjs.com/package/@types/matter-js crypto icons downloaded from https://www.behance.net/junikstudio todo list for 2019 i'm still far away from the project objective : make visual nodes for editor mode in gameplay. item's selling for crypto values. create examples demos in minimum 20 gameplay variants (table games, actions, platformers, basic demo throw the api doc etc.). implementing ar and webgl2. live demo platformer ...
First input delay - MDN Web Docs Glossary: Definitions of Web-related terms
fid) measures the time from when a user first interacts with your site (i.e. when they click a link, tap on a button, or use a custom, javascript-powered control) to the time when the browser is actually able to respond to that interaction. it is the length of time, in milliseconds, between the first user interaction on a web page and the browser’s response to that interaction. scrolling and zooming are not included in this metric. the time between when content is painted to the page and when all the functionality becomes responsive to human interaction often varies based on the the size and complexity of the javascript needing to be downloaded, parsed, and executed on the main thread, and on the device speed or lack thereof (think low end mobile devices). the longer the delay, the worse t...
... see also requestidlecallback lazy loading ...
... see also requestidlecallback lazy loading ...
JavaScript - MDN Web Docs Glossary: Definitions of Web-related terms
javascript is primarily used in the browser, enabling developers to manipulate webpage content through the dom, manipulate data with ajax and indexeddb, draw graphics with canvas, interact with the device running the browser through various apis, and more. ...
... javascript is primarily used in the browser, enabling developers to manipulate webpage content through the dom, manipulate data with ajax and indexeddb, draw graphics with canvas, interact with the device running the browser through various apis, and more. ...
... javascript is primarily used in the browser, enabling developers to manipulate webpage content through the dom, manipulate data with ajax and indexeddb, draw graphics with canvas, interact with the device running the browser through various apis, and more. ...
Mobile accessibility - Learn web development
ty best practices. there are some exceptions that need special consideration for mobile; the main ones are: control mechanisms — make sure interface controls such as buttons are accessible on mobiles (i.e., mainly touchscreen), as well as desktops/laptops (mainly mouse/keyboard). user input — make user input requirements as painless as possible on mobile (e.g., in forms, keep typing to a minimum). responsive design — make sure layouts work on mobile, conserve image download sizes, and think about the provision of images for high-resolution screens. summary of screenreader testing on android and ios the most common mobile platforms have fully functional screen readers. these function in much the same way as desktop screenreaders, except they are largely operated using touch gest...
...ble zoom. always ensure resizing is enabled, and set the width to the device's width in the <head>: <meta name="viewport" content="width=device-width; user-scalable=yes"> you should never set user-scalable=no if at all possible — many people rely on zoom to be able to see the content of your website, so taking this functionality away is a really bad idea. there are certain situations where zooming might break the ui; in such cases, if you feel that you absolutely need to disable zoom, you should provide some other kind of equivalent, such as a control for increasing the text size in a way that doesn't break your ui. keeping menus accessible because the screen is so much narrower on mobile devices, it is very common to use media queries and other technologies to make the navigation menu ...
...th navigating it. click here for a good hamburger menu example. user input on mobile devices, inputting data tends to be more annoying for users than the equivalent experience on desktop computers. it is more convenient to type text into form inputs using a desktop or laptop keyboard than a touchscreen virtual keyboard or a tiny mobile physical keyboard. for this reason, it is worth trying to minimize the amount of typing needed. as an example, instead of getting users to fill out their job title each time using a regular text input, you could instead offer a <select> menu containing the most common options (which also helps with consistency in data entry), and offer an "other" option that displays a text field to type any outliers into. you can see a simple example of this idea in action...
Web fonts - Learn web development
: @font-face { font-family: "myfont"; src: url("myfont.woff"); } below this you can then use the font family name specified inside @font-face to apply your custom font to anything you like, as normal: html { font-family: "myfont", "bitstream vera serif", serif; } the syntax does get a bit more complex than this; we'll go into more detail below. there are two important things to bear in mind about web fonts: browsers support different font formats, so you'll need multiple font formats for decent cross-browser support. for example, most modern browsers support woff/woff2 (web open font format versions 1 and 2), the most efficient format around, but older versions of ie only support eot (embedded open type) fonts, and you might need to include an svg version of the font to support ...
...our site). you shouldn't steal fonts and use them without giving proper credit. note: web fonts as a technology have been supported in internet explorer since version 4! you can use the firefox font editor to investigate and manipulate the fonts in use on your page, whether they are web fonts or not. this video provides a nice walkthrough: active learning: a web font example with this in mind, let's build up a basic web font example from first principles. 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. you should use the web-font-start.html and web-font-start.css files as a starting point to add your code to (see the live example). make a copy of these...
...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. you should use the web-font-start.html and web-font-start.css files as a starting point to add your code to (see the live example). make a copy of these files in a new directory on your computer now. in the web-font-start.css file, you'll find some minimal css to deal with the basic layout and typesetting of the example. finding fonts for this example, we'll use two web fonts, one for the headings, and one for the body text. to start with, we need to find the font files that contain the fonts. fonts are created by font foundries and are stored in different file formats. there are generally three types of sites where you can obtain fonts: a...
What text editors are available? - Learn web development
prerequisites: you should already know about various software you need to build a website. objective: learn how to choose a text editor that best suits your needs as a web developer. summary a website consists mostly of text files, so for a fun, pleasant development experience you should choose your text editor wisely. the sheer number of choices is a bit overwhelming, since a text editor is so basic to computer science (yes, web development is computer science). ideally, you'd try as many editors as you can and get a feel for what suits your workflow. but we'll give you some pointers for getting started. here are the primary questions you should consider: which os (operating system) do i want to work with? what kind of technologies do i want to manipula...
...you will learn more about customizing your editors and tools as you gain experience, and more importantly you will learn what features are more useful to y...
...d in that case you'll need to install an additional program to extract the content from the archive. windows supports .zip by default. mac. on the editor's website you can download a .dmg file. some text editors you can find directly in the apple store to make installation even simpler. linux. in the most popular distros you can start with your graphical package manager (ubuntu software center, mintinstall, gnome software, &c.). you can often find a .deb or .rpm file for prepackaged software, but most of the time you'll have to use your distro's repository server or, in worst case scenario, compile your editor from source. take the time to carefully check the installation instructions on the text editor's website. when you install a new text editor, your os will probably continue to open ...
How do I start to design my website? - Learn web development
your goals and save yourself from wasted effort. what needs to be done, and in what order, to reach my goals? now that you know what you want to accomplish, it's time to turn those goals into actionable steps. as a side note, your goals are not necessarily set in stone. they evolve over time even in the course of the project, especially if you run across unexpected obstacles or just change your mind. rather than go through a long explanation, let's go back to our example with this table: goals things to do let people hear your music record music prepare some audio files usable online (could you do this with existing web services?) give people access to your music on some part of your website talk about your music wr...
...able online (again, could you do this with existing web services?) give people access to your videos on some part of your website two things to notice. first, some of these items are not web-related (e.g., record music, write articles). often those offline activities matter even more than the web side of the project. in sales, for instance, it's far more important and time-consuming to handle supply, payment, and shipment than to build a website where people can place orders. second, setting out actionable steps leads to new questions you'll need to answer. usually there turn out to be more questions than we originally thought. (for example, should i learn how to do all this myself, ask someone to do it for me, or use third-party services?) conclusion as you can see, the...
...to new questions you'll need to answer. usually there turn out to be more questions than we originally thought. (for example, should i learn how to do all this myself, ask someone to do it for me, or use third-party services?) conclusion as you can see, the simple idea "i want to make a website" generates a long to-do list, which only grows longer as you think about it. soon it may look overwhelming, but don't panic. you don't need to answer all the questions and you don't need to do everything on your list. what matters is to have a vision of what you want and how to get there. once you have that clear vision, you need to decide how and when to do it. break down big tasks into small, actionable steps. and those small steps will add up to great achievements. from this article, you should n...
What is a Domain Name? - Learn web development
ught, the web would quickly fill up with unused domain names that were locked and couldn't be used by anyone. instead, you pay for the right to use a domain name for one or more years. you can renew your right, and your renewal has priority over other people's applications. but you never own the domain name. companies called registrars use domain name registries to keep track of technical and administrative information connecting you to your domain name. note : for some domain name, it might not be a registrar which is in charge of keeping track. for instance, every domain name under .fire is managed by amazon. finding an available domain name to find out whether a given domain name is available, go to a domain name registrar's website. most of them provide a “whois” service tha...
...1409563-lror creation date: 1998-01-24t05:00:00z updated date: 2013-12-08t01:16:57z registry expiry date: 2015-01-23t05:00:00z sponsoring registrar:markmonitor inc. (r37-lror) sponsoring registrar iana id: 292 whois server: referral url: domain status: clientdeleteprohibited domain status: clienttransferprohibited domain status: clientupdateprohibited registrant id:mmr-33684 registrant name:dns admin registrant organization:mozilla foundation registrant street: 650 castro st ste 300 registrant city:mountain view registrant state/province:ca registrant postal code:94041 registrant country:us registrant phone:+1.6509030800 as you can see, i can't register mozilla.org because the mozilla foundation has already registered it. on the other hand, let's see if i could register afunkydomainname.or...
...ation has already registered it. on the other hand, let's see if i could register afunkydomainname.org: $ whois afunkydomainname.org not found as you can see, the domain does not exist in the whois database (at the time of writing), so we could ask to register it. good to know! getting a domain name the process is quite straightforward: go to a registrar's website. usually there is a prominent “get a domain name” call to action. click on it. fill out the form with all required details. make sure especially that you have not misspelled your desired domain name. once it's paid for, it's too late! the registrar will let you know when the domain name is properly registered. within a few hours, all dns servers will have received your dns information. note: in this process the re...
Advanced form styling - Learn web development
ok like in your system — default on the left, and with the above css applied on the right (find it here also if you want to test it on other systems). in most cases, the effect is to remove the stylized border, which makes css styling a bit easier, but isn't really essential. in a couple of cases — search and radio buttons/checkboxes, it becomes way more useful. we'll look at those now. taming search boxes <input type="search"> is basically just a text input, so why is appearance: none; useful here? the answer is that in chromium-based browsers on macos, search boxes have some styling restrictions — you can't adjust their height or font-size freely, for example. this is because non-macos chrome browsers no longer use the webkit rendering engine, which enabled aqua appearance by def...
...height: 30px; } input[type="text"], input[type="datetime-local"], input[type="color"], select { box-shadow: inset 1px 1px 3px #ccc; border-radius: 5px; } label { margin-bottom: 5px; } button { width: 60%; margin: 0 auto; } note: if you want to test these examples across a number of browsers simultaneously, you can find it live here (also see here for the source code). also bear in mind that we've added some javascript to the page that lists the files selected by the file picker, below the control itself. this is a simplified version of the example found on the <input type="file"> reference page. as you can see, we've done fairly well at getting these to look uniform across modern browsers. we've applied some global normalizing css to all the controls and their labels, to ge...
...cripts may fail, especially in the mobile world, and you need to design your web site or app to handle these cases as well as possible. test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: advanced styling. bear in mind that some questions in this assessment series assume knowledge of the next article too, so you might want to work through that article first before attempting it. summary while there are still difficulties using css with html forms, there are ways to get around many of the problems. there are no clean, universal solutions, but modern browsers offer new possibilities. for now, the best solution...
Example 1 - Learn web development
xt-align : center; border-left : .2em solid #000; border-radius: 0 .1em .1em 0; background-color : #000; color : #fff; } .select .optlist { z-index : 2; list-style: none; margin : 0; padding: 0; background: #f0f0f0; border: .2em solid #000; border-top-width : .1em; border-radius: 0 0 .4em .4em; box-shadow: 0 .2em .4em rgba(0,0,0,.4); box-sizing : border-box; min-width : 100%; max-height: 10em; /* 100px */ overflow-y: auto; overflow-x: hidden; } .select .option { padding: .2em .3em; } .select .highlight { background: #000; color: #ffffff; } result for basic state active state html <div class="select active"> <span class="value">cherry</span> <ul class="optlist hidden"> <li class="option">cherry</li> <li class="option">lemo...
...xt-align : center; border-left : .2em solid #000; border-radius: 0 .1em .1em 0; background-color : #000; color : #fff; } .select .optlist { z-index : 2; list-style: none; margin : 0; padding: 0; background: #f0f0f0; border: .2em solid #000; border-top-width : .1em; border-radius: 0 0 .4em .4em; box-shadow: 0 .2em .4em rgba(0,0,0,.4); box-sizing : border-box; min-width : 100%; max-height: 10em; /* 100px */ overflow-y: auto; overflow-x: hidden; } .select .option { padding: .2em .3em; } .select .highlight { background: #000; color: #ffffff; } result for active state open state html <div class="select active"> <span class="value">cherry</span> <ul class="optlist"> <li class="option highlight">cherry</li> <li class="option">lem...
...t : .2em solid #000; border-radius: 0 .1em .1em 0; background-color : #000; color : #fff; } .select .optlist { z-index : 2; list-style: none; margin : 0; padding: 0; background: #f0f0f0; border: .2em solid #000; border-top-width : .1em; border-radius: 0 0 .4em .4em; box-shadow: 0 .2em .4em rgba(0,0,0,.4); -moz-box-sizing : border-box; box-sizing : border-box; min-width : 100%; max-height: 10em; /* 100px */ overflow-y: auto; overflow-x: hidden; } .select .option { padding: .2em .3em; } .select .highlight { background: #000; color: #fff; } result for open state ...
How to build custom form controls - Learn web development
orm: scale(1, 0) to give the optionlist no height and full width. beautification so now that we have the basic functionality in place, the fun can start. the following is just an example of what is possible, and will match the screenshot at the beginning of this article. however, you should feel free to experiment and see what you can come up with. .select { /* the computations are made assuming 1em == 16px which is the default value in most browsers. if you are lost with px to em conversion, try http://riddle.pl/emcalc/ */ font-size : 0.625em; /* this (10px) is the new font size context for em value in this context */ font-family : verdana, arial, sans-serif; box-sizing : border-box; /* we need extra room for the down arrow we will add */ padding : .1em 2.5em .2em .5...
... if it can't, the content will be truncated) */ max-height: 10em; /* 100px */ overflow-y: auto; overflow-x: hidden; border: .2em solid ...
...e actual <select> element - or we have not changed the body class, therefore the body class is still "no-widget", so the elements whose class is "select" must be hidden */ position : absolute; left : -5000em; height : 0; overflow : hidden; } this css visually hides one of the elements, but it is still available to screen readers. now we need a javascript switch to determine if the script is running or not. this switch is a couple of lines: if at page load time our script is running, it will remove the no-widget class and add the widget class, thereby swapping the visibility of the <select> element and the custom control. window.addeventlistener("load", function () { document.body.classlist.remove("no-widget"); document.body.classlist.add("widget"); }); ...
Other form controls - Learn web development
note: all browsers that support the <select> element also support the multiple attribute. autocomplete box you can provide suggested, automatically-completed values for form widgets using the <datalist> element with child <option> elements to specify the values to display. the <datalist> needs to be given an id. the data list is then bound to an <input> element (...
...rogress> this is for implementing anything requiring progress reporting, such as the percentage of total files downloaded, or the number of questions filled in on a questionnaire. the content inside the <progress> element is a fallback for browsers that don't support the element and for screen readers to vocalize it. meter a meter bar represents a fixed value in a range delimited by max and min values. this value is visually rendered as a bar, and to know how this bar looks, we compare the value to some other set values: the low and high values divide the range in three parts: the lower part of the range is between the min and low values, inclusive. the medium part of the range is between the low and high values, exclusive. the higher part of the range is between the high...
...the prefered part of the range, the bar is green. if the current value is in the average part of the range, the bar is yellow. if the current value is in the worst part of the range, the bar is red. such a bar is created using a <meter> element. this is for implementing any kind of meter, for example a bar showing total space used on a disk, which turns red when it starts to get full. <meter min="0" max="100" value="75" low="33" high="66" optimum="50">75</meter> the content inside the <meter> element is a fallback for browsers that don't support the element and for assistive technologies to vocalize it. support for <progress> and <meter> is fairly good — there is no support in internet explorer, but other browsers support it well. test your skills! you've reached the end of this ...
Installing basic software - Learn web development
ey rely on hidden elements that interfere with the rendering engines used by web browsers. web browsers, to test code in. currently, the most-used browsers are firefox, chrome, opera, safari, internet explorer and microsoft edge. 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. a graphics editor, like gimp, figma, paint.net, photoshop, or xd, to make images or graphics for your web pages. a version control system, to manage files on servers, collaborate on a project with a team, share code and assets and avoid editing conflicts. right now, git is the most popular version contro...
...ular version control system along with the github or gitlab hosting service. an ftp program, used on older web hosting accounts to manage files on servers (git is increasingly replacing ftp for this purpose). there are loads of (s)ftp programs available including cyberduck, fetch and filezilla. an automation system, like webpack, grunt, or gulp to automatically perform repetitive tasks, such as minifying code and running tests. libraries, frameworks, etc., to speed up writing common functionality. a library tends to be an existing javascript or css file that provides ready-rolled functionality for you to make use of in your code. a framework tend to take this idea further, offering a complete system with some custom syntaxes for you to write a web app on top of. more tools besides! what...
...f in your code. a framework tend to take this idea further, offering a complete system with some custom syntaxes for you to write a web app on top of. more tools besides! what tools do i actually need, right now? that looks like a scary list, but fortunately, you can get started in web development without knowing anything about most of these. in this article, we'll just set you up with a bare minimum — a text editor and some modern web browsers. installing a text editor you probably already have a basic text editor on your computer. by default windows includes notepad and macos comes with textedit. linux distros vary; ubuntu comes with gedit by default. for web development, you can probably do better than notepad or textedit. we recommend starting with visual studio code, which is a ...
Getting started with the Web - Learn web development
files explains how to set up a sensible file structure for your website and what issues you should be aware of. html basics hypertext markup language (html) is the code that you use to structure your web content and give it meaning and purpose. for example, is my content a set of paragraphs or a list of bullet points? do i have images inserted on my page? do i have a data table? without overwhelming you, html basics provides enough information to make you familiar with html. css basics cascading stylesheets (css) is the code that you use to style your website. for example, do you want the text to be black or red? where should content be drawn on the screen? what background images and colors should be used to decorate your website? css basics takes you through what you need to get started.
... to make you familiar with html. css basics cascading stylesheets (css) is the code that you use to style your website. for example, do you want the text to be black or red? where should content be drawn on the screen? what background images and colors should be used to decorate your website? css basics takes you through what you need to get started. javascript basics javascript is the programming language that you use to add interactive features to your website. some examples could be games, things that happen when buttons are pressed or data is entered in forms, dynamic styling effects, animation, and much more. javascript basics gives you an idea of what is possible with this exciting language, and how to get started. publishing your website once you have finished writing the code an...
...effects, animation, and much more. javascript basics gives you an idea of what is possible with this exciting language, and how to get started. publishing your website once you have finished writing the code and organizing the files that make up your website, you need to put it all online so people can find it. publishing your sample code describes how to get your simple sample code online with minimum effort. how the web works when you access your favorite website, a lot of complicated things happen in the background that you may not know about. how the web works outlines what happens when you view a webpage on your computer. ...
Use JavaScript within a webpage - Learn web development
harnessing javascript. learn in this article how to trigger javascript right from your html documents. prerequisites: you need to be familiar with how to create a basic html document. objective: learn how to trigger javascript in your html file, and learn the most important best practices for keeping javascript accessible. about javascript javascript is a programming language mostly used client-side to make webpages interactive. you can create amazing webpages without javascript, but javascript opens up a whole new level of possibilities. in this article we're going over the html code you need to make javascript take effect. if you want to learn javascript itself, you can start with our javascript basics article. if you already know something about javascr...
...s interactive. you can create amazing webpages without javascript, but javascript opens up a whole new level of possibilities. in this article we're going over the html code you need to make javascript take effect. if you want to learn javascript itself, you can start with our javascript basics article. if you already know something about javascript or if you have a background with other programming languages, we suggest you jump directly into our javascript guide. how to trigger javascript from html within a browser, javascript doesn't do anything by itself. you run javascript from inside your html webpages. to call javascript code from within html, you need the <script> element. there are two ways to use script, depending on whether you're linking to an external script or embedding a s...
...t update content, redirect, or refresh automatically. don't use carousels or display popups without warning. have a plan b for users without javascript. people may have javascript turned off to improve speed and security, and users often face network issues that prevent loading scripts. moreover, third-party scripts (ads, tracking scripts, browser extensions) might break your scripts. at a minimum, leave a short message with <noscript> like this: <noscript>to use this site, please enable javascript.</noscript> ideally, replicate the javascript functionality with html and server-side scripting when possible. if you're only looking for simple visual effects, css can often get the job done even more intuitively. since almost everybody does have javascript enabled, <noscript>...
Adding vector graphics to the Web - Learn web development
le contains shape and path definitions that the computer can use to work out what the image should look like when rendered on the screen. the svg format allows us to create powerful vector graphics for use on the web. to give you an idea of the difference between the two, let's look at an example. you can find this example live on our github repo as vector-versus-raster.html — it shows two seemingly identical images side by side, of a red star with a black drop shadow. the difference is that the left one is a png, and the right one is an svg image. the difference becomes apparent when you zoom in the page — the png image becomes pixellated as you zoom in because it contains information on where each pixel should be (and what color). when it is zoomed, each pixel is simply increased in...
...amples to get you started. you can also go to the svg element reference, find out more details about other toys you can use in svg, and try those out too. this section is all about practising your research skills, and having some fun. if you get stuck and can't get your code working, you can always reset it using the reset button. ...
...lls, and having some fun. if you get stuck and can't get your code working, you can always reset it using the reset button. ...
Responsive images - Learn web development
devices. responsive images are just one part of responsive design, a future css topic for you to learn. prerequisites: you should already know the basics of html and how to add static images to a web page. objective: learn how to use features like srcset and the <picture> element to implement responsive image solutions on websites. why responsive images? let's examine a typical scenario. a typical website may contain a header image and some content images below the header. the header image will likely span the whole of the width of the header, and the content image will fit somewhere inside the content column. here's a simple example: this works well on a wide screen device, such as a laptop or desktop (you can see the example live and find the source code...
...s technique could save mobile users a lot of bandwidth. note: when testing this with a desktop browser, if the browser fails to load the narrower images when you've got its window set to the narrowest width, have a look at what the viewport is (you can approximate it by going into the browser's javascript console and typing in document.queryselector('html').clientwidth). different browsers have minimum sizes that they'll let you reduce the window width to, and they might be wider than you'd think. when testing it with a mobile browser, you can use tools like firefox's about:debugging page to inspect the page loaded on the mobile using the desktop developer tools. to see which images were loaded, you can use firefox devtools's network monitor tab. older browsers that don't support these...
...ghter elva"> let's fix this, with <picture>! like <video> and <audio>, the <picture> element is a wrapper containing several <source> elements that provide different sources for the browser to choose from, followed by the all-important <img> element. the code in responsive.html looks like so: <picture> <source media="(max-width: 799px)" srcset="elva-480w-close-portrait.jpg"> <source media="(min-width: 800px)" srcset="elva-800w.jpg"> <img src="elva-800w.jpg" alt="chris standing up holding his daughter elva"> </picture> the <source> elements include a media attribute that contains a media condition — as with the first srcset example, these conditions are tests that decide which image is shown — the first one that returns true will be displayed. in this case, if the viewport widt...
Video and audio content - Learn web development
element, the src (source) attribute contains a path to the video you want to embed. it works in exactly the same way. 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. at a minimum, the interface must include a way to start and stop the media, and to adjust the volume. the paragraph inside the <video> tags this is called fallback content — this will be displayed if the browser accessing the page doesn't support the <video> element, allowing us to provide a fallback for older browsers. this can be anything you like; in this case, we've provided a direct link to the v...
..., 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. the video won't play, because different browsers support different video (and audio) formats. fortunately, there are things you can do to help prevent this from being a problem. contents of a media file first, let's go through the terminology quickly. formats like mp3, mp4 and webm are called container formats. they define a structure in which the audio and/or video tracks that make up the media are stored, along with metadata describing the media, what codecs are used to encode its channels, and so forth. a webm file containing a movie which has a main video track and one alternate angle track, plus audio for both english and s...
...icated task. see choosing the right container in media container formats (file types) for help selecting the container file format best suited for your needs; similarly, see choosing a video codec in web video codec guide and choosing an audio codec in web audio codec guide for help selecting the first media codecs to use for your content and your target audience. one additional thing to keep in mind: mobile browsers may support additional formats not supported by their desktop equivalents, just like they may not support all the same formats the desktop version does. on top of that, both desktop and mobile browsers may be designed to offload handling of media playback (either for all media or only for specific types it can't handle internally). this means media support is partly dependent on...
JavaScript building blocks - Learn web development
sics of html and css, and you should have also worked through our previous module, javascript first steps. note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin or glitch. guides making decisions in your code — conditionals in any programming language, code needs to make decisions and carry out actions accordingly depending on different inputs. for example, in a game, if the player's number of lives is 0, then it's game over. in a weather app, if it is being looked at in the morning, show a sunrise graphic; show stars and a moon if it is nighttime. in this article we'll explore how conditional structures work in javascript. looping ...
... in a game, if the player's number of lives is 0, then it's game over. in a weather app, if it is being looked at in the morning, show a sunrise graphic; show stars and a moon if it is nighttime. in this article we'll explore how conditional structures work in javascript. looping code sometimes you need a task done more than once in a row. for example, looking through a list of names. in programming, loops perform this job very well. here we will look at loop structures in javascript. functions — reusable blocks of code another essential concept in coding is functions. functions allow you to store a piece of code that does a single task inside a defined block, and then call that code whenever you need it using a single short command — rather than having to type out the same code multi...
...ential concept you must know about a function is return values. some functions don't return a significant value after completion, but others do. it's important to understand what their values are, how to make use of them in your code, and how to make your own custom functions return useful values. introduction to events events are actions or occurrences that happen in the system you are programming, which the system tells you about so you can respond to them in some way if desired. for example if the user clicks a button on a webpage, you might want to respond to that action by displaying an information box. in this final article we will discuss some important concepts surrounding events, and look at how they work in browsers. assessments the following assessment will test your understa...
Fetching data from the server - Learn web development
previous overview: client-side web apis next another very common task in modern websites and applications is retrieving individual data items from the server to update sections of a webpage without having to load an entire new page. this seemingly small detail has had a huge impact on the performance and behavior of sites, so in this article, we'll explain the concept and look at technologies that make it possible, such as xmlhttprequest and the fetch api. prerequisites: javascript basics (see first steps, building blocks, javascript objects), the basics of client-side apis objective: to learn how to fetch data from the server and use it to update the contents of a web page. what is the problem here? originally page loading on the web was simple — ...
...r. so what is going on in the fetch code? first of all, we invoke the fetch() method, passing it the url of the resource we want to fetch. this is the modern equivalent of request.open() in xhr, plus you don't need any equivalent to .send(). after that, you can see the .then() method chained onto the end of fetch() — this method is a part of promises, a modern javascript feature for performing asynchronous operations. fetch() returns a promise, which resolves to the response sent back from the server — we use .then() to run some follow-up code after the promise resolves, which is the function we've defined inside it. this is the equivalent of the onload event handler in the xhr version. this function is automatically given the response from the server as a parameter when the fetch(...
...omise structure from above again to see if we can make some more sense of it: fetch(url).then(function(response) { response.text().then(function(text) { poemdisplay.textcontent = text; }); }); the first line is saying "fetch the resource located at url" (fetch(url)) and "then run the specified function when the promise resolves" (.then(function() { ... })). "resolve" means "finish performing the specified operation at some point in the future". the specified operation, in this case, is to fetch a resource from a specified url (using an http request), and return the response for us to do something with. effectively, the function passed into then() is a chunk of code that won't run immediately. instead, it will run at some point in the future when the response has been returned. note...
Manipulating documents - Learn web development
delete it altogether. in this article we'll focus mostly on manipulating the document, but we'll show a few other useful bits besides. the document object model the document currently loaded in each one of your browser tabs is represented by a document object model. this is a "tree structure" representation created by the browser that enables the html structure to be easily accessed by programming languages — for example the browser itself uses it to apply styling and other information to the correct elements as it renders a page, and developers like you can manipulate the dom with javascript after the page has been rendered. we have created a simple example page at dom-example.html (see it live also). try opening this up in your browser — it is a very simple page containing a <secti...
...below it in the tree, but it is a descendant of body. parent node: a node which has another node inside it. for example, body is the parent node of section in the above example. sibling nodes: nodes that sit on the same level in the dom tree. for example, img and p are siblings in the above example. text node: a node containing a text string. it is useful to familiarize yourself with this terminology before working with the dom, as a number of the code terms you'll come across make use of them. you may have also come across them if you have studied css (e.g. descendant selector, child selector). active learning: basic dom manipulation to start learning about dom manipulation, let's begin with a practical example. take a local copy of the dom-example.html page and the image that goes...
...te that item off the list. the input should be emptied and focused ready for you to enter another item. the finished demo will look something like this: to complete the exercise, follow the steps below, and make sure that the list behaves as described above. to start with, download a copy of our shopping-list.html starting file and make a copy of it somewhere. you'll see that it has some minimal css, a list with a label, input, and button, and an empty list and <script> element. you'll be making all your additions inside the script. create three variables that hold references to the list (<ul>), <input>, and <button> elements. create a function that will run in response to the button being clicked. inside the function body, start off by storing the current value of the input eleme...
Client-side web APIs - Learn web development
in this module, we will explore what apis are, and how to use some of the most common apis you'll come across often in your development work. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. ...
...document object. in this article, we'll look at how to use the dom in detail, along with some other interesting apis that can alter your environment in interesting ways. fetching data from the server another very common task in modern websites and applications is retrieving individual data items from the server to update sections of a webpage without having to load an entirely new page. this seemingly small detail has had a huge impact on the performance and behavior of sites. in this article, we'll explain the concept, and look at technologies that make it possible, such as xmlhttprequest and the fetch api. third party apis the apis we've covered so far are built into the browser, but not all apis are. many large websites and services such as google maps, twitter, facebook, paypal, etc.
...llowing developers to make use of their data (e.g. displaying your twitter stream on your blog) or services (e.g. displaying custom google maps on your site, or using facebook login to log in your users). this article looks at the difference between browser apis and 3rd party apis and shows some typical uses of the latter. drawing graphics the browser contains some very powerful graphics programming tools, from the scalable vector graphics (svg) language, to apis for drawing on html <canvas> elements, (see the canvas api and webgl). this article provides an introduction to the canvas api, and further resources to allow you to learn more. video and audio apis html5 comes with elements for embedding rich media in documents — <video> and <audio> — which in turn come with their own apis f...
Handling text — strings in JavaScript - Learn web development
in this article, we'll look at all the common things that you really ought to know about strings when learning javascript, such as creating strings, escaping quotes in strings, and joining strings together. prerequisites: basic computer literacy, a basic understanding of html and css, an understanding of what javascript is. objective: to gain familiarity with the basics of strings in javascript. ...
...s a test'; these lines don't work because any text without quotes around it is assumed to be a variable name, property name, a reserved word, or similar. if the browser can't find it, then an error is raised (e.g. "missing; before statement"). if the browser can see where a string starts, but can't find the end of the string, as indicated by the 2nd quote, it complains with an error (with "unterminated string literal"). if your program is raising such errors, then go back and check all your strings to make sure you have no missing quote marks. the following will work if you previously defined the variable string — try it now: let badstring = string; badstring; badstring is now set to have the same value as string. single quotes vs. double quotes in javascript, you can choose sin...
...d as text, not part of the code. in javascript, we do this by putting a backslash just before the character. try this: let bigmouth = 'i\'ve got no right to take my place...'; bigmouth; this works fine. you can escape other characters in the same way, e.g. \", and there are some special codes besides. see escape notation for more details. concatenating strings concatenate is a fancy programming word that means "join together". joining together strings in javascript uses the plus (+) operator, the same one we use to add numbers together, but in this context it does something different. let's try an example in our console. let one = 'hello, '; let two = 'how are you?'; let joined = one + two; joined; the result of this is a variable called joined, which contains the value "hello, how...
What went wrong? Troubleshooting JavaScript - Learn web development
playing the game through again, you should get more success — the game should play through absolutely fine, until you end the game, either by guessing the right number, or by running out of guesses. at that point, the game fails again, and the same error is spat out that we got at the beginning — "typeerror: resetbutton.addeventlistener is not a function"! however, this time it's listed as coming from line 94. looking at line number 94, it is easy to see that we've made the same mistake here. we again just need to change addeventlistener to .addeventlistener. do this now. a logic error at this point, the game should play through fine, however after playing through a few times you'll undoubtedly notice that the "random" number you've got to guess is always 1. definitely not quite how ...
...tion as an argument. be careful with those parentheses! syntaxerror: missing } after function body this is easy — it generally means that you've missed one of your curly braces from a function or conditional structure. we got this error by deleting one of the closing curly braces near the bottom of the checkguess() function. syntaxerror: expected expression, got 'string' or syntaxerror: unterminated string literal these errors generally mean that you've left off a string value's opening or closing quote mark. in the first error above, string would be replaced with the unexpected character(s) that the browser found instead of a quote mark at the start of a string. the second error means that the string has not been ended with a quote mark. for all of these errors, think about how we tac...
...the unexpected character(s) that the browser found instead of a quote mark at the start of a string. the second error means that the string has not been ended with a quote mark. for all of these errors, think about how we tackled the examples we looked at in the walkthrough. when an error arises, look at the line number you are given, go to that line and see if you can spot what's wrong. bear in mind that the error is not necessarily going to be on that line, and also that the error might not be caused by the exact same problem we cited above! note: see our syntaxerror: unexpected token and syntaxerror: unterminated string literal reference pages for more details about these errors. summary so there we have it, the basics of figuring out errors in simple javascript programs. it won't al...
Object-oriented JavaScript for beginners - Learn web development
previous overview: objects next with the basics out of the way, we'll now focus on object-oriented javascript (oojs) — this article presents a basic view of object-oriented programming (oop) theory, then explores how javascript emulates object classes via constructor functions, and how to create object instances. prerequisites: basic computer literacy, a basic understanding of html and css, familiarity with javascript basics (see first steps and building blocks) and oojs basics (see introduction to objects). ...
...s how javascript emulates object classes via constructor functions, and how to create object instances. prerequisites: basic computer literacy, a basic understanding of html and css, familiarity with javascript basics (see first steps and building blocks) and oojs basics (see introduction to objects). objective: to understand the basic theory behind object-oriented programming, how this relates to javascript ("everything is an object"), and how to create constructors and object instances. object-oriented programming — the basics to start with, let's give you a simplistic, high-level view of what object-oriented programming (oop) is. we say simplistic, because oop can quickly get very complicated, and giving it a full treatment now would probably confuse more...
...to refer to, which is sometimes called a namespace), making it easy to structure and access; objects are also commonly used as data stores that can be easily sent across the network. defining an object template let's consider a simple program that displays information about the students and teachers at a school. here we'll look at oop theory in general, not in the context of any specific programming language. to start this off, we could return to our person object type from our first objects article, which defines the generic data and functionality of a person. there are lots of things you could know about a person (their address, height, shoe size, dna profile, passport number, significant personality traits ...) , but in this case we are only interested in showing their name, age, gender...
Multimedia: Images - Learn web development
this article looks at optimizing image and video to improve web performance. prerequisites: basic computer literacy, basic software installed, and basic knowledge of client-side web technologies. objective: to learn about the various image formats, their impact on performance, and how to reduce the impact of images on overall page load time. ...
...hat boast a high dpi screen (e.g. "retina"). so apart from creating plenty of intermediate image variants you also need a way to serve the right file to the right browser. that's where you would need to upgrade your <picture> and <source> elements with media and/or sizes attributes. a detailed article on how to combine all of these attributes can be found here. two interesting effects to keep in mind regarding high dpi screens is that: with high dpi screen, humans will spot compression artifacts a lot later, meaning that for images meant for these screens you can crank up compression beyond usual. only a very few people can spot an increase in resolution beyond 2× dpi, which means you don't need to serve images resolving higher than 2×. controlling the priority (and ordering) of dow...
...ce for them in the layout. for any background images, it's important you set a background-color value so any content overlaid is still readable before the image has downloaded. conclusion in this section we took a look at image optimization. you now have a general understanding of how to optimize half of the average web sites average bandwidth total. this is just one of the types of media consuming users bandwidth and slowing down page load. let's take a look at video optimization, tackling the next 20% of bandwidth consumption. previous overview: performance next in this module the "why" of web performance what is web performance? how do users perceive performance? measuring performance multimedia: images multimedia: video javascript performance best practices. html pe...
Web performance resources - Learn web development
is a quick review of best practices, tools, apis with links to provide more information about each topic. best practices start with learning the critical rendering path of the browser. knowing this will help you understand how to improve the performance of the site. using resource hints such as rel=preconnect, rel=dns-prefetch, rel=prefetch, and rel=preload keep the size of javascript to a minimum. only use as much javascript as needed for the current page. css performance factors use http/2 on your server (or cdn). use a cdn for resources which can reduce load times significantly. compress your resources using gzip, brotli, and zopfli. image optimization (use css animation, or svg if possible). lazy loading parts of your application outside the viewport. if you do, have a backup...
...ces using gzip, brotli, and zopfli. image optimization (use css animation, or svg if possible). lazy loading parts of your application outside the viewport. 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. it might not be absolute timing, but user perception. quick wins css web performance is all about user experience and perceived performance. as we learned in the critical rendering path document, linking css with a tradional link tag with rel="stylesheet" is synchronous and blocks rendering. optimize the rendering of your page by removing blocking css. to load css asynchronously one can simpy set the media type to print a...
...aspects of your site including performance, seo and accessibility. ...
Multimedia: video - Learn web development
ype support. why optimize your multimedia? for the average website, 25% of bandwidth comes from video. optimizing video has the potential for very large bandwidth savings that translate into better website performance. optimizing video delivery it's best to compress all video, optimize <source> order, set autoplay, remove audio from muted video, optimize video preload, and consider streaming the video. the sections below describe each of these optimization techniques. compress all videos most video compression work compares adjacent frames within a video, with the intent of removing detail that is identical in both frames. compress the video and export to multiple video formats, including webm, mpeg-4/h.264, and ogg/theora. your video editing software probably has a feature to re...
...obability of playback. offering more modest bandwidth savings, setting preload="metadata" may download up to 3% of the video on page load. this is a useful option for some small or moderately sized files. changing the setting to auto tells the browser to automatically download the entire video. do this only when playback is very likely. otherwise, it wastes a lot of bandwidth. consider streaming video streaming allows the proper video size and bandwidth (based on network speed) to be delivered to the end user. similar to responsive images, the correct size video is delivered to the browser, ensuring fast video startup, low buffering, and optimized playback. conclusion optimizing video has the potential to significantly improve website performance. video files are relatively large co...
...o the browser, ensuring fast video startup, low buffering, and optimized playback. conclusion optimizing video has the potential to significantly improve website performance. video files are relatively large compared to other website files, and always worthy of attention. this article explains how to optimize website video through reducing file size, with (html) download settings, and with streaming. previous overview: performance next in this module the "why" of web performance what is web performance? how do users perceive performance? measuring performance multimedia: images multimedia: video javascript performance best practices. html performance features css performance features fonts and performance mobile performance focusing on performance ...
The "why" of web performance - Learn web development
goals. prerequisites: basic computer literacy, basic software installed, and basic knowledge of client-side web technologies. objective: to gain basic familiarity of why web performance is important for good user experience. web performance refers to how quickly site content loads and renders in a web browser, and how well it responds to user interaction. bad performing sites are slow to display and slow to respond to input. bad performing sites increase site abandonment. at its worst, bad performance causes content to be completely inaccessible. a good goal for web performance is for users to not notice performance. while an individual's perception of site performance performance is subjective, loading and rendering can be measured. good performance may not be...
...ear-old ipad while commuting home on public transportation. the same site will be slow to load, possibly verging on unusable depending on cell coverage. you might give up before it finishes loading. imagine loading that same site on a $35 huawei device in a rural india with limited coverage or no coverage. 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. a 22.6 mb site could take up to 83 seconds to load on a 3g network, with domcontentloaded (meaning the site's base html structure) at 31.86 seconds. and it isn't just the time taken to download that is a major problem. a lot of countries still have internet connections that bill per megabyte. our example 22.6 mb cnn.com expe...
...t isn't just the time taken to download that is a major problem. a lot of countries still have internet connections that bill per megabyte. our example 22.6 mb cnn.com experience would cost about 11% of the average indian's daily wage to download. from a mobile device in northwest africa, it might cost two days of an average salary. and if this site were loaded on a us carrier's international roaming plan? the costs would make anyone cry. (see how much your site costs to download.) improve conversion rates reducing the dowload and render time of a site improves conversion rates and user retention. a conversion rate is the rate at which site visitors perform a measured or desired action. for example, this might be making a purchase, reading an article, or subscribing to a newsletter. the...
Ember Interactivity: Footer functionality, conditional rendering - Learn web development
t tackling the footer functionality in our app. here we'll get the todo counter to update to show the correct number of todos still to complete, and correctly apply styling to completed todos (i.e. where the checkbox has been checked). we'll also wire up our "clear completed" button. along the way, we'll learn about using conditional rendering in our templates. prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line. a deeper understanding of modern javascript features (such as classes, modules, etc), will be extremely beneficial, as ember makes heavy use of them. objective: to continue our learning about components classes, start looking at cond...
...ality. connecting the behavior in the footer to get the footer working, we need to implement the following thre areas of functionality: a pending todo counter. filters for all, active, and completed todos. a button to clear the completed todos. because we need access to our service from the footer component, we need to generate a class for the footer. ...
...now save and test, and you'll see the correct pluralization used when you only have one todo item present! note that this is the block form of if in ember; you could also use the the inline form: {{if this.todos.todocountisone "todo" "todos"}} completing todos as with the other components, we need a class to access the service. ...
Ember resources and troubleshooting - Learn web development
previous overview: client-side javascript frameworks next our final ember article provides you with a list of resources that you can use to go further in your learning, plus some useful troubleshooting and other information. prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line. a deeper understanding of modern javascript features (such as classes, modules, etc), will be extremely beneficial, as ember makes heavy use of them. objective: to provide further resource links and troubleshooting information. further resources ember.js guides tutorial: super rentals ember.js api documentation ember.js discord...
...n { data: json }; } } see more information on specifying the route's model here. why can't i just use javascript? this is the most common question ember folks hear from people who have previous experience with react. while it is technically possible to use jsx, or any other form of dom creation, there has yet to be anything as robust as ember's templating system. the intentional minimalism forces certain decisions, and allows for more consistent code, while keeping the template more structural rather than having them filled with bespoke logic. see also: reactiveconf 2017: secrets of the glimmer vm what is the state of the mut helper? mut was not covered in this tutorial and is really baggage from a transitional time when ember was moving from two-way bound data to the mo...
... a component. controllers are (as of january 2020), the only way to manage url query params. ideally, controllers should be fairly light in their responsibilities, delegating to components and services where possible. what is the purpose of routes? a route represents part of the url when a user navigates from place to place in the app. a route has only a couple responsibilities: load the minimally required data to render the route (or view-sub-tree). gate access to the route and redirect if needed. handle loading and error states from the minimally required data. a route only has 3 lifecycle hooks, all of which are optional: beforemodel — gate access to the route. model — where data is loaded. aftermodel — verify access. last, a route has the ability to handle c...
Componentizing our React app - Learn web development
h. before we can make it do things, we need to break it apart into manageable, descriptive components. react doesn’t have any hard rules for what is and isn’t a component – that’s up to you! in this article we will show you a sensible way to break our app up into components. prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. objective: to show a sensible way of breaking our todo list app into components. defining our first component defining a component can seem tricky until you have some practice, but the gist is: if it represents an obvious "chunk" of your app, it's probably a component if it gets reused often, it's probably a component. that second bullet is especially...
....tasks. you can console.log() it to check, if you’d like. note: all_caps constant names have no special meaning in javascript; they’re a convention that tells other developers "this data will never change after being defined here”. rendering with iteration to render our array of objects, we have to turn each one into a <todo /> component. javascript gives us an array method for transforming data into something else: array.prototype.map(). above the return statement of app(), make a new const called tasklist and use map() to transform it. let's start by turning our tasks array into something simple: the name of each task: const tasklist = props.tasks.map(task => task.name); let’s try replacing all the children of the <ul> with tasklist: <ul role="list" classname="todo-list...
...gely! componentizing the rest of the app now that we've got our most important component sorted out, we can turn the rest of our app into components. remembering that components are either obvious pieces of ui, or reused pieces of ui, or both, we can make two more components: <form/> <filterbutton/> since we know we need both, we can batch some of the file creation work together with a terminal command. run this command in your terminal, taking care that you're in the root directory of your app: touch src/components/form.js src/components/filterbutton.js the <form /> open components/form.js and do the following: import react at the top of the file, like we did in todo.js. make yourself a new form() component with the same basic structure as todo(), and export that component. c...
React interactivity: Events and state - Learn web development
g our app from a completely static ui to one that actually allows us to interact and change things. in this article we'll do this, digging into events and state along the way, and ending up with an app in which we can successfully add and delete tasks, and toggle tasks as completed. prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. objective: to learn about handling events and state in react, and use those to start making the case study app interactive. handling events if you've only written vanilla javascript before now, you might be used to having a separate javascript file, where you query for some dom nodes and attach listeners to them. for example: const btn = document.querysele...
...in order to give our component some state. to use a react hook, we need to import it from the react module. in form.js, change your very first line so that it reads like this: import react, { usestate } from "react"; this allows us to import the usestate() function by itself, and utilize it anywhere in this file. usestate() creates a piece of state for a component, and its only parameter determines the initial value of that state. it returns two things: the state, and a function that can be used to update the state later. this is a lot to take in at once, so let's try it out. we're going to make ourselves a name state, and a function for updating the name state. write the following above your handlesubmit() function, inside form(): const [name, setname] = usestate('use hooks!'); what'...
...react will give you a warning in your devtools console — "warning: encountered two children with the same key..." we need to fix this. making unique identifiers is a hard problem – one for which the javascript community has written some helpful libraries. we’ll use nanoid because it's tiny, and it works. 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. first of all, include the following import line at the top of app.js: import { nanoid } from "nanoid"; now let's update addtask() so that each task id becomes a prefix todo- plus...
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
into components. in this article we will add the app's final features and further componentize our app. we will learn how to deal with reactivity issues related to updating objects and arrays. to avoid common pitfalls, we'll have to dig a little deeper into svelte's reactivity system. we'll also look at solving some accessibility focus issues, and more besides. prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line. you'll need a terminal with node + npm installed to compile and build your app. objective: learn some advanced svelte techniques involving solving reactivity issues, keyboard accessibility problems to do with component lifecycle, and...
...alculations and optimize execution. they make little to no attempt to understand what our javascript code is doing. svelte doesn't use a virtual dom representation. instead, it parses and analyzes our code, creates a dependency tree, and then generates the required javascript to update only the parts of the dom that need to be updated. this approach usually generates optimal javascript code with minimal overhead, but it also has its limitations. sometimes svelte cannot detect changes to variables being watched. remember that to tell svelte that a variable has changed, you have to assign it a new value. a simple rule of thumb is that the name of the updated variable must appear on the left hand side of the assignment. for example, in the following piece of code: const foo = obj.foo foo.bar...
...we'll create a function called focus() that gives focus to the <h2> heading. for that we'll need a headingel variable to hold the reference to the dom node and we'll have to bind it to the <h2> element using bind:this={headingel}. our focus method will just run headingel.focus(). update the contents of todosstatus.svelte like so: <script> export let tod...
Working with Svelte stores - Learn web development
discussed some advanced techniques for dealing with reactivity, working with dom nodes, and exposing component functionality. in this article we will show another way to handle state management in svelte — stores. stores are global global data repositories that hold values. components can subscribe to stores and receive notifications when their values change. prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line. you'll need a terminal with node + npm installed to compile and build your app. objective: learn how to use svelte stores using stores we will create an alert component that shows notifications on screen, which can receive mes...
...e a good option. if you’ve already worked with redux or vuex, then you'll be familiar with how this kind of store works. svelte stores offer similar features for state management. a store is simply an object with a subscribe() method that allows interested parties to be notified whenever the store value changes, and an optional set() method that allows you to set new values for the store. this minimal api is known as the store contract. svelte provides functions for creating readable, writable, and derived stores in the svelte/store module. svelte also provides a very intuitive way to integrate stores into its reactivity system using the reactive $store syntax. if you create your own stores honoring the store contract, you get this reactivity syntactic sugar for free. creating the alert...
...rage content once more. you will get something like this: svelte stores provide a very simple and lightweight, but extremely powerful, way to handle complex app state from a global data store in a reactive way. and because svelte compiles our code, it can provide the $store auto-subscription syntax that allows us to work with stores in the same way as local variables. because stores has a minimal api, it's very simple to create our custom stores to abstract away the inner workings of the store itself. bonus track: transitions let's change the subject now, and do something fun and different — let's add an animation to our alerts. svelte provides a whole module to define transitions and animations so we can make our user interfaces more appealing. a transition is applied with the t...
Dynamic behavior in Svelte: working with variables and props - Learn web development
previous overview: client-side javascript frameworks next now that we have our markup and styles ready we can start developing the required features for our svelte to-do list app. 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. prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line. you'll need a terminal with node + npm installed to compile and build your app. objective: learn and put into practice some basic svelte concepts, like creating components, passing data using props, render javascript expressions into ou...
...ion. let's start by showing a status message. find the <h2> heading with an id of list-heading and replace the hardcoded number of active and completed tasks with dynamic expressions: <h2 id="list-heading">{completedtodos} out of {totaltodos} items completed</h2> go to the app, and you should see the "2 out of 3 items completed" message as before, but this time the information is coming from the todos array. to prove it, go to that array, and try changing some of the todo object's completed property values, and even add a new todo object. observe how the numbers in the message are updated appropriately. dynamically generating the todos from the data at the moment, our displayed todo items are all static. we want to iterate over each item in our todos array and render...
...={() => removetodo(todo)} > delete <span class="visually-hidden">{todo.name}</span> </button> a very common mistake with handlers in svelte is to pass the result of executing a function as a handler, instead of passing the function. for example, if you specify on:click={removetodo(todo)}, it will execute removetodo(todo) and the result will be passed as a handler, which is not what we had in mind. in this case you have to specify on:click={() => removetodo(todo)} as the handler. if removetodo() received no params, you could use on:event={removetodo}, but not on:event={removetodo()}. this is not some special svelte syntax — here we are just using regular javascript arrow functions. again, this is good progress — at this point, we can now delete tasks. when a todo item's delete ...
Vue conditional rendering: editing existing todos - Learn web development
do this, we will take advantage of vue's conditional rendering capabilities — namely v-if and v-else — to allow us to toggle between the existing todo item view, and an edit view where you can update todo item labels. we'll also look at adding functionality to delete todo items. prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. vue components are written as a combination of javascript objects that manage the app's data and an html-based template syntax that maps to the underlying dom structure. for installation, and to use some of the more advanced features of vue (like single file components or render functions), you'll need a terminal with node + npm installed. objective: to learn ...
...this is a useful way to help reinforce everything you've learned so fa...
...we haven’t actually handled updating the todoitems array back in app.vue. to fix that, we need to listen for the item-edited event, and update the list accordingly. we'll also want to handle the delete event so that we can delete todo items. add the following new methods to your app.vue's component object, below the existing methods inside the methods property: deletetodo(todoid) { const itemindex = this.todoitems.findindex(item => item.id === todoid); this.todoitems.splice(itemindex, 1); }, edittodo(todoid, newlabel) { const todotoedit = this.todoitems.find(item => item.id === todoid); todotoedit.label = newlabel; } next, we'll add the event listeners for the item-deleted and item-edited events: for item-deleted, you'll need to pass the item.id to the method. for item-edited...
Handling common accessibility problems - Learn web development
or chrome axe for firefox these add an accessibility tab to the browser developer tools. for example, we installed the firefox version, then used it to audit our bad-table.html example. we got the following results: axe is also installable using npm, and can be integrated with task runners like grunt and gulp, automation frameworks like selenium and cucumber, unit testing frameworks like jasmin, and more besides (again, see the main axe page for details). screenreaders it is definitely worth testing with a screenreader to get used to how severely visually impaired people use the web. there are a number of screenreaders available: some are paid-for commercial products, like jaws (windows) and window eyes (windows). some are free products, like nvda (windows), chromevox (chrome, win...
...fferent items in the current rotor list. esc (when inside rotor) exit rotor. ctrl (when vo is speaking) pause/resume speech. vo + z restart the last bit of speech. vo + d go into the mac's dock, so you can select apps to run inside it. this seems like a lot of commands, but it isn't so bad when you get used to it, and vo regularly gives you reminders of what commands to use in certain places. have a play with vo now; you can then go on to play with some of our examples in the screenreader testing section. nvda nvda is windows-only, and you'll need to install it. download it from nvaccess.org. you can choose whether to make a donation or download it for free; you'll also need to give them your e-mail address before you can download it...
...all. note that nvda seems to behave slightly stragely when you've only got a single table on a page; you could try webaim's table test page instead. have a look at the wai-aria live regions example we saw earlier, and note how the screen reader will keep reading out the constantly updating section as it updates. user testing as mentioned above, you can't rely on automated tools alone for determining accessibility problems on your site. it is recommended that when you draw up your testing plan, you should include some accessibility user groups if at all possible (see our user testing section earlier on in the course for some more context). try to get some screenreader users involved, some keyboard-only users, some non-hearing users, and perhaps other groups too, as suits your requirements.
Creating a spell check dictionary add-on
ype>64</em:type> <em:unpack>true</em:unpack> <em:name>name</em:name> <!-- other install.rdf metadata such as em:localized, em:description, em:creator, em:developer, em:translator, em:contributor or em:homepageurl --> <!-- firefox --> <em:targetapplication> <description> <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> <em:minversion>18.0a1</em:minversion> <em:maxversion>46.0</em:maxversion> </description> </em:targetapplication> <!-- thunderbird --> <em:targetapplication> <description> <em:id>{3550f703-e582-4d05-9a08-453d09bdfdc6}</em:id> <em:minversion>18.0a1</em:minversion> <em:maxversion>22.0</em:maxversion> </description> </em:targetapp...
...em:targetapplication> <description> <em:id>{3550f703-e582-4d05-9a08-453d09bdfdc6}</em:id> <em:minversion>18.0a1</em:minversion> <em:maxversion>22.0</em:maxversion> </description> </em:targetapplication> <!-- seamonkey --> <em:targetapplication> <description> <em:id>{92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a}</em:id> <em:minversion>2.15a1</em:minversion> <em:maxversion>2.49</em:maxversion> </description> </em:targetapplication> </description> </rdf> there are some rules about how you should adapt the install.rdf file: if you are creating a new dictionary add-on, we recommend that the em:id consists of your locale code followed by @dictionaries.addons.mozilla.org, but if there is more than...
... new version number must be greater than the old one. don't change em:type or em:unpack, and don't add a em:bootstrap element. type = 64 indicates that the add-on is in the restartless format, and unpack is required for hunspell to read the dictionary. although the restartless format for dictionary add-ons were introduced in gecko 10, dictionary updates only works starting from gecko 18. the em:minversion should therefore be the same as in the example above (or greater). if you set em:minversion to a lower value, gecko 10-17 will not be able to update your dictionary add-on once the restartless dictionary is installed (bug 782118), and gecko 10-16 may warn the user that your dictionary is not compatible, when users try to update to a newer version of firefox/thunderbird (bug 782115). updat...
Creating Sandboxed HTTP Connections
ral notifications, including the two cookie ones. the addobserver method is used to add an observer for a certain topic and takes in three agruments: an object than implements nsiobserver the topic to listen for. for cookies, the two topics are: http-on-modify-request - happens after the cookie data has been loaded into the request, but before the request is sent. http-on-examine-response - happens after the response is received, but before the cookies are processed whether to hold a weak reference to the observer argument. use false. in order to avoid memory leaks, the observer needs to be removed at one point. the removeobserver method takes in the listener object and the topic and removes it from the notification list. as with the above stream listener, a...
...ach time a redirect happens). // create an nsiobserver implementor var listener = { observe : function(asubject, atopic, adata) { // make sure it is our connection first. if (asubject == gchannel) { var httpchannel = asubject.queryinterface(components.interfaces.nsihttpchannel); if (atopic == "http-on-modify-request") { // ... } else if (atopic == "http-on-examine-response") { // ... } } }, queryinterface : function(aiid) { if (aiid.equals(components.interfaces.nsisupports) || aiid.equals(components.interfaces.nsiobserver)) return this; throw components.results.ns_nointerface; } }; // get the observer service and register for the two coookie topics. var observerservice = components.classes["@mozilla.org/obs...
...ow components.results.ns_nointerface; } }; // get the observer service and register for the two coookie topics. var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); observerservice.addobserver(listener, "http-on-modify-request", false); observerservice.addobserver(listener, "http-on-examine-response", false); the final piece is to manipulate the cookies. 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 a...
HTTP logging
note: the web console also offers the ability to peek at http transactions within firefox. http logging generally provides more detailed logging. using about:networking this is available starting with firefox 52. this is the best and easiest way to do http logging. ...
...r containing the specified log file, and gather all the log files. you will see several files that look like: log.txt-main.1806, log.txt-child.1954, log.txt-child.1970, etc. this is because firefox now uses multiple processes, and each process gets its own log file. for many bugs, the "log.txt-main" file is the only thing you need to upload as a file attachment to your bugzilla bug (this is assuming you're logging to help a mozilla developer). other bugs may require all the logs to be uploaded--ask the developer if you're not sure. pat yourself on the back--a job well done! thanks for helping us debug firefox. logging http activity by manually setting environment variables sometimes the about:networking approach won't work, for instance if your bug occurs during startup, or you're run...
..._file=/tmp/log.txt cd /path/to/firefox ./firefox reproduce the problem you're debugging. when the problem has been reproduced, exit firefox and look for the generated log files, which you can find at /tmp/log.txt. mac os x these instructions show how to log http traffic in firefox on mac os x. quit firefox is if it's currently running, by using the quit option in the file menu. keep in mind that simply closing all windows does not quit firefox on mac os x (this is standard practice for mac applications). run the terminal application, which is located in the utilities subfolder in your startup disk's applications folder. copy and paste the following commands into the terminal window, hitting the return key after each line. export moz_log=timestamp,rotate:200,nshttp:5,cache2:5,ns...
Simple Thunderbird build
ogram files (x86)\windows kits\10\include\10.0.nnnnn.0\shared, where nnnnn is the highest number present on the system. note that the downloaded outlook 2010 mapi header files contain 18 fies, of which only 17 are needed. do not copy mapi.h, it is already in c:\program files (x86)\windows kits\10\include\10.0.17134.0\um\mapi.h. as of april 2019, 10.0.17134.0 is needed to compile thunderbird. assuming standard installation locations, copy these 17 files to c:\program files (x86)\windows kits\10\include\10.0.17134.0\shared. 18/10/2010 16:11 7,334 mapiaux.h 02/06/2009 17:02 7,938 mapicode.h 02/06/2009 17:02 22,960 mapidbg.h 02/06/2009 17:02 84,644 mapidefs.h 02/06/2009 17:02 27,840 mapiform.h 02/06/2009 17:02 11,880 mapi...
...anifest as problems setting up the virtualenv for running tests (failure to install pip or virtualenv because of os access denied errors, where access is denied not because of permission problems, but because the paths being accessed have been truncated, and so do not exist). having the source deep in a filesystem hierarchy can also cause problems with pymake builds on windows. if you run into seemingly arbitrary problems in building and the source is deeply nested, try moving it closer to the root of your machine and re-building. get the latest mozilla source code from mozilla's mozilla-central mercurial code repository, and check it out into a local directory source/ (or however you want to call it). then, get the latest thunderbird source code from mozilla's comm-central mercurial code re...
...ld see green bs on https://treeherder.mozilla.org/#/jobs?repo=comm-central to start the build, cd into the source directory, and run: ./mach build mach is our command-line tool to streamline common developer tasks. see the mach article for more. building can take a significant amount of time, depending on your system, os, and chosen build options. linux builds on a fast box may take under 15 minutes, but windows builds on a slow box may take several hours. tips for making builds faster. the executable will be at the location listed under running below. running to run your build, you can use ./mach run there are various command line parameters you can add, e.g. to specify a profile. various temporary files, libraries, and the thunderbird executable will be found in your object direc...
Contributing to the Mozilla code base
ibuting that getting set up to work on firefox and finding a bug that's a good fit for your skills can be a challenge. we're always looking for ways to improve this process: making mozilla more open, accessible, and easier to participate with. if you're having any trouble following this documentation, or hit a barrier you can't get around, please contact mike hoye at mhoye@mozilla.com. we're determined to solve hurdles for new contributors. what skills do i need? mozilla is a large project and we are thrilled to have contributors with very diverse skills below is a table with our currently available projects to contribute to, along with the skills needs and links to their documentation. project skills documentation/onboarding firefox browser (core layers) c++ ...
... step 1: find something to work on bugs listed as 'assigned' are not usually a good place to start unless you're sur...
... mozilla hubs javascript and/or html/css, vr contribute to mozilla hubs servo rust contribute to servo there are even many ways to contribute to the mozilla mission without programming. if getting involved in design, support, translation, testing, or other types of contributions sparks your interest please see community webiste. perhaps you do not know programming yet, but you want to start learning? there are plenty of resources available on the mdn web docs! step 1: find something to work on bugs listed as 'assigned' are not usually a good place to start unless you're sure you have something worthy to contribute. someone else is already working on it! even with no assignee, it is polite to check if someone has recently commented that they're looking a...
Index
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. 3 building firefox with rust code build documentation, gecko, build, rust in may 2015 the rust programming language reached its 1.0 stability milestone, and various experiments with writing parts of gecko in rust began. rust code first shipped in august 2016 with the release of firefox 48. it became a requirement for building gecko in february 2017 with firefox 54. 8 experimental features in firefox experimental, firefox, preferences, features this page lists features that are in...
...upport site. 168 performance best practices for firefox front-end engineers best practices, developing firefox, developing mozilla, firefox, front-end, mozilla, performance this guide will help firefox developers working on front-end code produce code which is as performant as possible—not just on its own, but in terms of its impact on other parts of firefox. always keep in mind the side effects your changes may have, from blocking other tasks to interfering with other user interface elements. 169 privacy privacy, security this document lists privacy-related documentation. 170 storage access policy: block cookies from trackers privacy, storage access policy, tracking protection firefox includes a new storage access policy that b...
...licy: block cookies from trackers privacy, storage access policy, tracking protection firefox includes a new storage access policy that blocks cookies and other site data from third-party tracking resources. this new policy is designed as an alternative to the current policies, which have been available in firefox for many years. the new policy protects against cross-site tracking while minimizing the site breakage associated with traditional cookie blocking. this article explains how the new policy works and how you can test it. 171 tracking protection privacy, private browsing, blocking, tracking starting in version 42, firefox desktop and firefox for android include built-in tracking protection. in private browsing windows (tabs, in firefox for android), fire...
MozBeforePaint
this new property indicates the time, in milliseconds since epoch, at which all animations started in the specified window during the current refresh interval should be considered to have started running. with that value in hand, you can then schedule all your subsequent animation frames. ...
...this new property indicates the time, in milliseconds since epoch, at which all animations started in the specified window during the current refresh interval should be considered to have started running. with that value in hand, you can then schedule all your subsequent animation frames. ...
... this example performs a simple animation, moving a box a short distance after a short period of time. <!doctype html> <html> <body> <div id="d" style="width:100px; height:100px; background:lime; position:relative;"></div> <script> var d = document.getelementbyid("d"); var start = window.mozanimationstarttime; function step(event) { var progress = event.timestamp - start; d.style.left = math.min(progress/10, 200) + "px"; if (progress < 2000) { window.mozrequestanimationframe(); } else { window.removeeventlistener("mozbeforepaint", step, false); } } window.addeventlistener("mozbeforepaint", step, false); window.mozrequestanimationframe(); </script> </body> </html> as you can see, each time the mozbeforepaint event fires, our step() method is called. this computes the curre...
Embedding the editor
owser via nsiwebbrowser, but instead having an editable document. the composer chrome (toolbars etc) may be implemented by the embedder using native widgets, or using some amount of xul. that chrome needs to be configurable - dockable floating toolbars, toolbar shared between composer widgets, or 1 per widget. this type of embedding requires that the composer code is agnostic to where its ui is coming from; communication between the core editor and the ui needs to go through one or more interfaces that insulate the editor from its host application. (the current nseditorshell makes assumptions about the hosting xul document, which need to be broken.) composer embedded in a web page (<htmlarea>) ie 5 supports the <htmlarea> element; if mozilla is to support something similar, editor needs to be...
...er embedded in a native application, there is a requirement here that the composer ui be configurable, such that it can be displayed either as a toolbar at the top of the <htmlarea>, a floating palette, or a top-level toolbar. current problems the current composer architecture was created while other parts of mozilla were still under development, and as a result it suffers from a number of shortcomings, and anachronisms. this section describes its major faults. editor incorrectly rooted the editor in a composer window is current owned by the nseditorshell, which in turn is created, owned and destroyed by the nseditorboxobject. the box object is a layout structure that is owned by content nodes, and survives frame destruction/recreation. the box object also has a reference to the docshell for ...
.... fix existing js and c++ code which explicitly addresses elements in the xul document to go through nsieditoruserinterface. steps to embedding this section attempts to lay out an implementation plan, with the aim of keeping everything working as the various steps are taken. some of these tasks can be done concurrently. ...
Script security
erview of the script security architecture in gecko. like any web browser, gecko can load javascript from untrusted and potentially hostile web pages and run it on the user's computer. the security model for web content is based on the same-origin policy, in which code gets full access to objects from its origin but highly restricted access to objects from a different origin. the rules for determining whether an object is same-origin with another, and what access is allowed cross-origin, are now mostly standardized across browsers. gecko has an additional problem, though: while its core is written in c++, the front-end code is written in javascript. this javascript code, which is commonly referred to as chrome code, runs with system privileges. if the code is compromised, the attacker can ...
...e if the caller has lower privileges than the target object, then the caller gets an opaque wrapper. an opaque wrapper denies all access to the target 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. security checks to determine the security relation between two compartments, gecko uses two concepts: security principals and the act of subsuming. to establish the security relationship between two compartments a and b, gecko asks: does the security principal for compartment a subsume the security principal for compartment b, and vice versa? subsumes a subsumes b a has all of the privileges of b, and possibl...
...rincipals. (this is what is used when html5 and other specs say "origin is a globally unique identifier".) principal relationships the diagram below summarizes the relationships between the different principals. the arrow connecting principals a and b means "a subsumes b". (a is the start of the arrow, and b is the end.) computing a wrapper the following diagram shows the factors that determine the kind of wrapper that compartment a would get when trying to access an object in compartment b. ...
How to get a stacktrace with WinDbg
rosoft.com/download/symbols .symfix+ c:\symbols .reload /f now wait for the symbols to download. this may take some time depending on your connection speed; the total size of the mozilla and microsoft symbols download is around 1.4gb. windbg will show "busy" at the bottom of the application window until the download is complete. once the download is complete, you need to configure windbg to examine child processes, ignore a specific event caused by flash player, and record a log of loaded modules. you will also want to open a log file to save data you collect. to do this, enter these four commands, pressing enter after each one. .logopen /t c:\temp\firefox-debug.log .childdbg 1 .tlist sxn gp lm if you see firefox.exe listed in the output from .tlist more than once, then you are already ...
..., to get the stacktrace, crash/hang analysis and log of loaded modules. (again, press enter after each command.) ~* kp !analyze -v -f lm after these steps are completed, find the file c:\temp\firefox-debug-(today's date).txt on your hard drive. to provide the information to the development community, submit this file with a support request or attach it to a related bug on bugzilla. producing a minidump sometimes the stacktrace alone is not enough information for a developer to figure out what went wrong. a developer may ask you for a "minidump" or a "full memory dump", which are files containing more information about the process. you can easily produce minidumps from windbg and provide them to developers. faq q: i am running windows 7 (32-bit or 64-bit) and i see an exception in the wi...
...eak+0x2c eb ntdll!ldrpdodebuggerbreak+0x30 0x90 eb ntdll!ldrpdodebuggerbreak+0x2c 0x90 make sure you enter them one at a time and press enter after each one. if you use the 64-bit version of windows, you need to replace "ntdll" in these commands with "ntdll32". q: the first four frames of my stack trace look like this: 0012fe20 7c90e89a ntdll!kifastsystemcallret 0012fe24 7c81cd96 ntdll!zwterminateprocess+0xc 0012ff20 7c81cdee kernel32!_exitprocess+0x62 0012ff34 6000179e kernel32!exitprocess+0x14 this looks wrong to me?! a: you ran the application without the "debug child processes also" check box being checked. you need to detach the debugger and open the application again, this time with the check box being checked. q: windbg tells me that it is unable to verify checksum for firef...
IME handling guide
which notification should be sent to widget and/or ime. then, mozilla::imecontentobserver::imenotificationsender tries to send the pending notifications when it might become safe to do that. currently, it's tried: after a native event is dispatched from presshell::handleeventinternal() at changing focus from a windowless plugin when new focused editor receives dom "focus" event the 3rd timing may not be safe actually, but it causes a lot of oranges of automated tests. see also notifications to ime section for the detail of sending notifications. currently, widgetquerycontentevent is handled via imecontentobserver because if it has a cache of selection, it can set reply of equeryselectedtext event only with the cache. that is much faster than using contenteventhandler. e10s suppor...
...10, the notified range is from 1 to 10. if all merged text changes were caused by composition, imenotification::mtextchangedata::mcausedonlybycomposition is set to true. this is useful if native ime handler wants to ignore all text changes which are expected by native ime. if at least one text change of the merged text changes was caused by current composition, imenotification::mtextchangedata::mincludingchangesduringcomposition is set to true. this is useful if native ime handler wants to ignore delayed text change notifications. if at least one text change of the merged text changes was caused when there was no composition, imenotification::mtextchangedata::mincludingchangeswithoutcomposition is set to true. notify_ime_of_selection_change when selection (or caret position) is changed i...
...occurs on linux even in non-e10s mode if the native ime is ibus. the callers of notifyime(request_tocommit_composition) may expect that composition string is committed immediately for their next job. for such a case, textcomposition::requesttocommit() synthesizes dom composition events and a dom text event for emulating to commit composition synchronously. additionally, textcomposition ignores comming events which are dispatched by widget when the widget receives native ime events. in this case, using the last composition string as commit string. however, if the last composition string is only an ideographic space (fullwidth space), the composition string may be a placeholder of some old chinese ime on windows. in this case, although, we should not commit the placeholder character becaus...
AsyncShutdown.jsm
must be done before the end of phase profilebeforechange return promise; }, function info() { let status = ... // collect any information that may be useful for debugging shutdown issues with this blocker return status; } }); in this example, at some point during phase profilebeforechange, function condition will be called. phase profilebeforechange is guaranteed to not terminate until promise is either resolved or rejected. if, for some reason, promise is never resolved/rejected, firefox will crash during shutdown to avoid blocking system shutdown, preventing the user from restarting firefox or burning through a battery. in this case, a crash report is produced, with information on all the shutdown blockers that have not been resolved, and all the additional debug inf...
...of the blocker. used for debugging/error reporting. please make sure that the name respects the following model: "some service: some action in progress" - for instance "os.file: flushing all pending i/o". condition a condition blocking the completion of the phase. generally, this is a function returning a promise. this function is evaluated during the phase and the phase is guaranteed to not terminate until the resulting promise is either resolved or rejected. if condition is not a function but another value v, it behaves as if it were a function returning v. info optionally, a function returning information about the current state of the blocker as an object. used for providing more details when logging errors or crashing. removeblocker () remove the blocker for a condition. if severa...
...eforechange will not complete until promise // is resolved or rejected }); asyncshutdown.profilebeforechange.addblocker("module: trivial callback", function condition() { // ... // execute this code during profilebeforechange // no specific guarantee about completion of profilebeforechange }); if the promise returned by condition is not resolved/rejected within one minute, the process will crash to avoid blocking system shutdown, preventing the user from restarting firefox or burning through battery. this is by design. it is the caller's responsibility to ensure that the promise is eventually resolved/rejected. properties attribute type description profilebeforechange read only phase the profile is about to be unm...
Download
t available. this property may be populated or changed while the download is in progress, using the mime type provided by the server. currentbytes read only number number of bytes currently transferred. this value starts at zero, and may be updated regardless of the value of hasprogress. note: you shouldn't rely on this property being equal to totalbytes to determine whether the download is completed. you should use the individual state properties instead, since this value may not be updated after the last piece of data is transferred. error read only downloaderror when the download fails, this is set to a downloaderror instance indicating the cause of the failure. if the download has been completed successfully or has been canceled, thi...
... this can be set to a function that is called after other properties change. warning: this property cannot be used if the download is part of a downloadlist. progress read only number progress percent, from 0 to 100. intermediate values are reported only if hasprogress is true. note: you shouldn't rely on this property being equal to 100 to determine whether the download is completed. you should use the individual state properties (for example, the succeeded property) instead. saver read only downloadsaver saver object associated with this download. source read only downloadsource source of this download. starttime read only date indicates the start time of the download. when the download s...
...ynchronous. until the cancellation process finishes, temporary files or part files may still exist even if they are expected to be deleted. in case the download completes successfully before the cancellation request could be processed, this method has no effect, and it returns a resolved promise. you should check the properties of the download at the time the returned promise is resolved to determine if the download was canceled. calling this method when the download has been completed successfully, failed, or has been canceled has no effect, and the method returns a resolved promise. this behavior is designed for the case where the call to cancel happens asynchronously, and is consistent with the case where the cancellation request could not be processed in time. promise cancel(); param...
Following the Android Toasts Tutorial from a JNI Perspective
and ;. because we don't want to keep typing string signatures everywhere, we can end up with typos and hard to trace back errors, we use the sig object. we see sig.toast.substr(1, sig.toast.length - 2) was written, this can be replaced with 'android/widget/toast'. the third argument is an object of our declares. declare constructors in our toast example, we do not have any constructors. determine static-ness of methods declare them there are two types of methods, chainable and static. if it is static, this means that it can be called directly from the class. if it is not static, then it cannot be used on an instance of that class. how is it determined if a method is static or not? the documentation tells us. for example, in our case we have a method maketext and show, looking that up o...
...we look up the documentation for our field, which is length_short, and we see it is static. so we will not need a group in the third argument of loadclass for fields, we will only need static_fields. fields do not accept arguments, so the "method format" is not used, we simply tell the sig the type of t...
...we cannot use the typical js-ctypes data types. google developer :: android apis - documentation for the android apis. the go-to resource for learning about the api when writing scripts for fennec. ...
Promise
e can be in one of three states: pending, when the final value is not available yet. this is the only state that may transition to one of the other two states. fulfilled, when and if the final value becomes available. a fulfillment value becomes permanently associated with the promise. this may be any value, including undefined. rejected, if an error prevented the final value from being determined. a rejection reason becomes permanently associated with the promise. this may be any value, including undefined, though it is generally an error object, like in exception handling. note: you should always handle, forward, or report errors (rejection reasons). if you see the message "a promise chain failed to handle a rejection", there is likely something to be fixed in the code. see handlin...
... promise returned by the then method with which the callback was registered, that is actually a different promise for each invocation of the method. ...
...in case this parameter is not a function (usually left undefined), the new promise returned by the then method is rejected with the same reason as the original promise. ...
Promise.jsm
e is not suggested for new code. 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. ...
...source://gre/modules/commonjs/sdk/core/promise.js"); // gecko 21 to 24 this implementation also includes helper functions that are specific to the add-on sdk. while you may still import this module from the above paths, the recommended way for loading it is through the add-on sdk loader. introduction for an introduction to promises, you may start from the add-on sdk documentation, keeping in mind that only the core subset is implemented in this module. a promise is an object representing a value that may not be available yet. internally, a promise can be in one of three states: pending, when the final value is not available yet. this is the only state that may transition to one of the other two states. fulfilled, when and if the final value becomes available. a fulfillment value bec...
...e can be in one of three states: pending, when the final value is not available yet. this is the only state that may transition to one of the other two states. fulfilled, when and if the final value becomes available. a fulfillment value becomes permanently associated with the promise. this may be any value, including undefined. rejected, if an error prevented the final value from being determined. a rejection reason becomes permanently associated with the promise. this may be any value, including undefined, though it is generally an error object, like in exception handling. a reference to an existing promise may be received by different means, for example as the return value of a call into an asynchronous api. in this case, the state of the promise can be observed but not directly con...
Bootstrapping a new locale
localizer-documentation/ . to learn how to bootstrap a new locale for mozilla projects, please see those documents. in mozilla, we use the the mercurial version control system (hg) to help manage our localizations. when a localization team is registered and your hg repository is set up for a locale, you can then clone the existing mozilla release branch (i.e. where active development of the upcoming release of firefox occurs) and then begin the necessary work for translation. hg allows localizers to work locally on their machines and then "push" changes to their official mozilla repository. installing mercurial depending on your operating system, you will need to install the correct version of hg on your machine. this document will give you the basic information on how to do that. inst...
...are-locales this will download and install the utility. clone the source code the next step is to download a copy of the source code to your local system, using mercurial. you will need to "hg clone" the existing release branch for mozilla so you have all the files locally for you to begin localization. make sure to have the directory where you intend to work as the current path on your terminal. (you should "cd" to the directory before beginning.) in the terminal, type the following command: $ hg clone http://hg.mozilla.org/releases/mozilla-x.x.x/ where "x.x.x" is the existing release branch version. for instance, for firefox 3.6, we use mozilla-1.9.2. refer to l10n:branches for the list of all branches. if you are interested in localizing thunderbird 3, seamonkey 2 or other mo...
... directory to the new working directory so you are in the ~/[your working directory]/[ab-cd]/ path and can start localizing. ...
QA phase
if you're localizing mozilla websites, your work will display soon after you've committed it without needing a language pack. ...
...u'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. note: remember all of those pre-requisite tools we asked you to install in the initial setup? here's where you'll need almost all of them. if you haven't installed them yet, now is the time to do it. ...
...tionally, you will need to copy and translate the toolkit/defines.inc file directly from en-us before you can build. this is due to a bug in the build logic. please either follow the above structure closely or adjust the commands below according to your custom setup. to copy this file to the appropriate directory, do the following: navigate to your working directory from your command-line terminal (i.e., where you created the folder structure described above). enter the following commands: mkdir -p l10n-central/x-testing/toolkit/ cp mozilla-aurora/toolkit/locales/defines.inc l10n-central/x-testing/toolkit/defines.inc tah-dah! copied! finally, you will need a file called .mozconfig to proceed with manual builds. this file contains the necessary build instructions. to create and co...
SVN for Localizers
o a file. note that path/to/output is meant to indicate the directory on your computer where you wish to store the diff file. you can also run svn status to check the list of modified files (they'll display a m before the name) you're about to commit. once you're satisfied with changes, commit them to the appropriate mozilla svn repository by entering the following command: svn commit -m "minor modifications for firefox [version #] beta page for [your locale]" the svn commit command will commit your changes directly to the mozilla svn repositories. since you are writing to the repository here, you will be asked for your ldap login credentials. the -m parameter followed by some text within double quotes (") will be pushed along with your changes. within the double quotes you should ...
...the repository here, you will be asked for your ldap login credentials. the -m parameter followed by some text within double quotes (") will be pushed along with your changes. within the double quotes you should briefly describe your changes so that everyone can see what you contributed. you can also double check your changes using the viewvc interface. after you commit your changes, wait 15 minutes and check the staging website for your locale. your recent changes should now be visible online. you will have the chance to see how the localized website will look when it's pushed to prod (i.e., a website that regular visitors will see). when localizing websites, l10n-drivers will always add needed files to your repository or update your files with new strings in english. it's very impo...
...en and you need to start over. go back to the root of your working directory and execute this command: svn revert * this is a really helpful command because it reverts all of your changes to your working directory's last updated state. this is a huge blessing if you have been updating frequently. it's a nightmare if you haven't because it throws away all of your recent hard work. keep this in mind because if you did a lot of work and you made some errors in just one file, maybe it would be wiser to simply correct those errors instead of reverting your working directory and losing all your work. note: sometimes you'll find references to commands in abbreviated form (svn ci = svn commit, svn up = svn update, svn co = svn checkout, etc.) commit doesn't work, what's wrong? make you sur...
Setting up the infrastructure
requirements: php with gettext support, apache and some unix experience. create a new branch for l10n (optional if starting a new project). create a locale directory in your website (usually something like docroot/locale). ...
...messages.mo files. by default the script looks for gettext calls in *thtml or *.php files, so you may need to adjust that to your code. compile-mo.sh will only compile all locales' messages.po files to message.mo files. this is useful when a localizer submits a new version of the messages.po file. on the staging server you can also choose to set up a cronjob that will run compile-mo.sh every n minutes. this way the localizers will be able to preview their changes almost in real-time. stats-po.sh will give you a bird's-eye view on the statistics of translated, fuzzy and missing strings for each locale. create en-us locale (locale/lc_messages/) in the locale folder. create an empty filed named messages.po in the locale/lc_messages folder. create new locales by repeating steps 4 an...
...lowing the web content localizability guidelines. review your code following the web applications localizability guidelines. run extract-po.sh. restart apache to reload gettext files (necessary for any text changes). merge the l10n branch back to main trunk (if the l10n branch was created in step 1). copy files over to svn. set up the staging server. set up a cronjob to svn up every n minutes. set up a cronjob to run compile-mo.sh every m minutes. qa with new locale. fix any layout issues. ...
Fonts for Mozilla's MathML engine
talled starting with os x lion and should ensure relatively good mathml rendering. enhancement requests have been submitted to apple to ship opentype math fonts in the default installation. if you have a developer account, these are problems 16841023 and 17021145. linux install the latin modern math, stix or xits fonts, which are generally available from your package manager. ...
...d to follow specific instructions so that your system is aware of the fonts. as a last resort, install the mathml fonts add-on. advanced setup arabic mathematical alphabetic symbols currently, very few fonts have appropriate glyphs for the arabic mathematical alphabetic symbols. if you are likely to need these characters, we recommend to install the xits or amiri fonts. installation without administrator privilege if you need to install fonts on a system without adminstrator privilege, the easiest option is to use math font the mathml-fonts add-on. 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. a better alternative on unix systems is to install the otf...
...ont with a math table and related open font format features. a list of such math fonts is provided below. you can use the advanced font preference menu to configure the default font for mathematics. alternatively, you can try the mathml-fontsettings add-on. ...
Mozilla Development Tools
or your platform. mozilla source code (mercurial and cvs) "trunk" development for gecko 1.9.1/firefox 3.5 and beyond uses the mercurial source code version control system. earlier releases and other products use the cvs version control system. ...
...d cvs) "trunk" development for gecko 1.9.1/firefox 3.5 and beyond uses the mercurial source code version control system. earlier releases and other products use the cvs version control system. if you are doing active development, checking out source code from one of these is preferable to downloading an archived snapshot, as you get up-to-the-minute changes. ...
...it is our home-grown web-based tool for watching the progress of the continuous builds that we run on multiple platforms. ...
tools/power/rapl
note: the power profiling overview is worth reading at this point if you haven't already. it may make parts of this document easier to understand. ...
... include the following. all measurements are in watts. the first line indicates the meaning of each column. the underscores in _pkg_, _gpu_ and _ram_ are present so that each column's name has five characters. the total power is the sum of the package power and the ram power. the package estimate is divided into three parts: cores, gpu, and "other". "other" is computed as the package power minus the cores power and gpu power. if the processor does not support gpu or ram estimates then " n/a " will be printed in the relevant column instead of a number, and it will contribute zero to the total. once sampling is finished — either because the user interrupted it, or because the requested number of samples has been taken — the following summary data is shown: 10 samples taken over a...
... instead of a number, and it will contribute zero to the total. once sampling is finished — either because the user interrupted it, or because the requested number of samples has been taken — the following summary data is shown: 10 samples taken over a period of 10.000 seconds distribution of 'total' values: mean = 8.85 w std dev = 3.50 w 0th percentile = 5.17 w (min) 5th percentile = 5.17 w 25th percentile = 5.17 w 50th percentile = 8.13 w 75th percentile = 11.16 w 95th percentile = 14.63 w 100th percentile = 14.63 w (max) the distribution data is omitted if there was zero or one samples taken. options -i --sample-interval. the length of each sample in milliseconds. defaults to 1000. a warning is given if you set it below 50 because that is lik...
L20n HTML Bindings
<head> … <script src="l20n.js"></script> </head> create manifest use a localization manifest to define available languages and their resource files. ...
...sten to: document.addeventlistener('documentlocalized', function() { // the dom has been localized and the user sees it in their language yourapp.init(); }); exposing context data you can expose important bits of data to the localization context in form of context data. ...
...> { "newnotifications": 3, "user": { "name": "jane", "gender": "feminine" } } </script> this data will be available context-wide to all localized strings. for instance, a string could use the information about the user's gender to provide two variants of the translation, like in the example below. see l20n by example to learn more about l20n's syntax. <invited[$user.gender] { feminine: "{{ $user.name }} has invited you to her circles.", masculine: "{{ $user.name }} has invited you to his circles.", *unknown: "{{ $user.name }} has invited you to their circles." }> based on the context data defined above, this will produce: jane has invited you to her circles. monolingual mode l20n can also operate in the so-called monolingual mode, when there is only one locale avail...
Localization Use Cases
being long and often unnaturally-sounding to the native speakers. about-browser=o brskalniku {{browserbrandshortname}} solution in l20n, this problem can be easily solved by defining multiple variants of the browserbrandshortname entity, to match different grammatical cases of the noun. in shared/branding/official/branding, we can define browserbrandshortname as: <browserbrandshortname{ nominative: "firefox", genitive: "firefoxa", dative: "firefoxu", accusative: "firefox", locative: "firefoxu", instrumental:"firefoxom" }> and in shared/branding/unofficial/branding, we can define browserbrandshortname as follows, to mean web browser: now, coming back to apps/browser/locales/browser, we can take advantage of the grammatical cases. slovenian uses the locative case with its...
...first, there is devicestoragehelper.showformatedsize (sic): function showformatedsize(element, l10nid, size)...
...y to imagine how developers might forget to pluralize some strings that in other languages might require pluralization (or other grammatical features that the framework supports). solution l20n isolates each language so that grammatical requirements of one don't affect others. this takes the responsibility away from the developers and puts it in the hands of localizers, at the same time transforming it from a burden into an opportunity. in l20n, the english string could be as simple as: <availablesize "{{ $size }} {{ $unit }} available"> on the other hand, the italian translation would make use of proper pluralization rules: <plural($n) { $n == 1 ? "one" : "other" }> <availablesize[plural($size)] { one: "{{ $size }} {{ $unit }} disponibile", other: "{{ $size }} {{ $un...
Nonblocking IO In NSPR
a thread is typically created to attend to one of the simultaneous i/o operations that may potentially block. in the nonblocking io model, a file descriptor may be marked as nonblocking. ...
...wudpsocket()</tt> is always created in blocking mode. 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. in nspr, blocking sockets on nt are associated with an i/o completion port. once associated with an i/o completion port, we can't disassociate the socket from the i/o completion port. i have seen some strange problems with using a nonblocking socket associated with an i/o completion port. so the first cons...
...ptread()</tt>, <tt>pr_read()</tt>, <tt>pr_write()</tt>, <tt>pr_writev()</tt>, <tt>pr_recv()</tt>, <tt>pr_send()</tt>, <tt>pr_recvfrom()</tt>, <tt>pr_sendto()</tt>, and <tt>pr_transmitfile(),</tt> and do not include <tt>pr_bind()</tt> and <tt>pr_listen()</tt>. in blocking mode, any of these potentially-blocking functions requires the use of the nt i/o completion port. so at that point we must determine whether to associate the socket with the i/o completion or not, and that decision cannot be changed later. there is a second constraint, due to the use of nt asynchronous i/o and the recycling of used sockets: the new socket returned by <tt>pr_accept()</tt> or <tt>pr_acceptread()</tt> inherits the blocking/nonblocking io mode of the listening socket and this cannot be changed. the socket return...
Date and Time
e. a time instant is represented by its position on the time line relative to the origin, called the epoch. nspr defines the epoch to be midnight (00:00:00) 1 january 1970 utc (coordinated universal time). in this form, time is just a point on the time line. there is no notion of time zone. clock/calendar time, used for human interfaces, represents time in the familiar year, month, day, hour, minute, second components. in this form, the time zone information is important. for example, without specifying the time zone, the time 8:00am 1 may 1998 is ambiguous. the nspr data type for clock/calendar time, called an exploded time, has the time zone information in it, so that its corresponding point in absolute time is uniquely specified. note that absolute and clock times are not normally us...
...ond components. in this form, the time zone information is important. for example, without specifying the time zone, the time 8:00am 1 may 1998 is ambiguous. the nspr data type for clock/calendar time, called an exploded time, has the time zone information in it, so that its corresponding point in absolute time is uniquely specified. note that absolute and clock times are not normally used in timing operations. for functions that deal with the measurement of elapsed time and with timeouts, see interval timing. macros for time unit conversion types and constants time parameter callback functions functions macros for time unit conversion macros for converting between seconds, milliseconds, microseconds, and nanoseconds. pr_msec_per_sec pr_usec_per_sec pr_nsec_per_sec pr_usec_pe...
... between seconds, milliseconds, microseconds, and nanoseconds. pr_msec_per_sec pr_usec_per_sec pr_nsec_per_sec pr_usec_per_msec pr_nsec_per_msec types and constants types and constants defined for nspr dates and times are: prtime prtimeparameters prexplodedtime time parameter callback functions in some geographic locations, use of daylight saving time (dst) and the rule for determining the dates on which dst starts and ends have changed a few times. therefore, a callback function is used to determine time zone information. you can define your own time parameter callback functions, which must conform to the definition prtimeparamfn. two often-used callback functions of this type are provided by nspr: prtimeparamfn pr_localtimeparameters and pr_gmtparameters functions ...
NSPR Error Handling
error type prerrorcode error functions pr_seterror pr_seterrortext pr_geterror pr_getoserror pr_geterrortextlength pr_geterrortext error codes error codes defined in prerror.h: pr_out_of_memory_error insufficient memory to perform request. pr_bad_descriptor_error the file descriptor used as an argument in the preceding function is invalid. ...
...lt_error one of the arguments of the preceding function specified an invalid memory address. pr_invalid_method_error the preceding function is invalid for the type of file descriptor used. pr_illegal_access_error one of the arguments of the preceding function specified an invalid memory address. pr_unknown_error some unknown error has occurred. pr_pending_interrupt_error the operation terminated because another thread has interrupted it with pr_interrupt. pr_not_implemented_error the preceding function has not been implemented. pr_io_error the preceding i/o function encountered some sort of an error, perhaps an invalid device. pr_io_timeout_error the i/o operation has not completed in the time specified for the preceding function. pr_io_pending_error an i/o operation has been...
...platform. pr_protocol_not_supported_error the host operating system does not support the protocol requested. pr_remote_file_error access to the remote file has been severed. pr_buffer_overflow_error the value retrieved is too large to be stored in the buffer provided. pr_connect_reset_error the (tcp) connection has been reset by the peer. pr_range_error unused. pr_deadlock_error performing the requested operation would have caused a deadlock. the deadlock was avoided. pr_file_is_locked_error an attempt to acquire a lock on a file has failed because the file is already locked. pr_file_too_big_error completing the write or seek operation would have resulted in a file larger than the system could handle. pr_no_device_space_error the device for storing the file is full. pr_pipe...
PRExplodedTime
it also has a microsecond component, as well as the day of week and the day of year. ...
...it also has a microsecond component, as well as the day of week and the day of year. in addition, prexplodedtime includes a prtimeparameters structure representing the local time zone information, so that the time point is non-ambiguously specified. ...
...sential members of prexplodedtime are: tm_year: absolute year, ad (by "absolute," we mean if the year is 2000, this field's value is 2000). tm_month: number of months past tm_year. the range is [0, 11]. 0 is january and 11 is december. tm_mday: the day of month. the range is [1, 31]. note that it starts from 1 as opposed to 0. tm_hour: number of hours past tm_mday. the range is [0, 23]. tm_min: number of minutes past tm_hour. the range is [0, 59]. tm_sec: number of seconds past tm_min. the range is [0, 61]. the values 60 and 61 are for accommodating up to two leap seconds. tm_usec: number of microseconds past tm_sec. the range is [0, 999999]. tm_params: a prtimeparameters structure representing the local time zone information. the nonessential members of prexplodedtime are: tm_...
PRThreadState
threads created with a pr_unjoinable_thread state cannot be used as arguments to pr_jointhread. ...
...threads created with a pr_unjoinable_thread state cannot be used as arguments to pr_jointhread. ...
...time it is created to the time it returns from its root function. what happens when it returns from its root function depends on the thread state passed to pr_createthread when the thread was created. if a thread is created as a joinable thread, it continues to exist after returning from its root function until another thread joins it. the join process permits strict synchronization of thread termination and therefore promotes effective resource management. if a thread is created as an unjoinable (also called detached) thread, it terminates and cleans up after itself after returning from its root function. this results in some ambiguity after the thread's root function has returned and before the thread has finished terminating itself. ...
PR_EnumerateHostEnt
to begin an enumeration, this argument is set to zero. to continue an enumeration (thereby getting successive addresses from the host entry structure), the value should be set to the function's last returned value. ...
...to begin an enumeration, this argument is set to zero. to continue an enumeration (thereby getting successive addresses from the host entry structure), the value should be set to the function's last returned value. ...
...ort number to be assigned as part of the prnetaddr structure. this parameter is not checked for validity. address on input, a pointer to a prnetaddr structure. on output, this structure is filled in by the runtime if the result of the call is greater than 0. returns the function returns one of the following values: if successful, the function returns the value you should specify in the enumindex parameter for the next call of the enumerator. if the function returns 0, the enumeration is ended. if unsuccessful, the function returns -1. you can retrieve the reason for the failure by calling pr_geterror. description pr_enumeratehostent is a stateless enumerator. the principle input, the prhostent structure, is not modified. ...
PR_JoinThread
the function is synchronous in that it blocks the calling thread until the target thread is in a joinable state. ...
...lowing parameter: thread a valid identifier for the thread that is to be joined. returns the function returns one of the following values: if successful, pr_success if unsuccessful--for example, if no joinable thread can be found that corresponds to the specified target thread, or if the target thread is unjoinable--pr_failure. description pr_jointhread is used to synchronize the termination of a thread. the function is synchronous in that it blocks the calling thread until the target thread is in a joinable state. pr_jointhread returns to the caller only after the target thread returns from its root function. pr_jointhread must not be called until after pr_createthread has returned. if pr_jointhread is not called on the same thread as pr_createthread, then it is the caller's ...
...hread returns from its root function. pr_jointhread must not be called until after pr_createthread has returned. if pr_jointhread is not called on the same thread as pr_createthread, then it is the caller's responsibility to ensure that pr_createthread has completed. several threads cannot wait for the same thread to complete. one of the calling threads operates successfully, and the others terminate with the error pr_failure. the calling thread is not blocked if the target thread has already terminated. pr_jointhread is interruptable. ...
NSS 3.19.2 release notes
. nss 3.19.2 requires nspr 4.10.8 or newer. nss 3.19.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_19_2_rtm/src/ new in nss 3.19.2 new functionality no new functionality is introduced in this release. notable changes in nss 3.19.2 bug 1172128 - in nss 3.19.1, the minimum key sizes that the freebl cryptographic implementation (part of the softoken cryptographic module used by default by nss) was willing to generate or use was increased - for rsa keys, to 512 bits, and for dh keys, 1023 bits. this was done as part of a security fix for bug 1138554 / cve-2015-4000. applications that requested or attempted to use keys smaller then the minimum size would fail. how...
...consumers of nss are strongly encouraged to migrate to stronger cryptographic strengths as soon as possible. ...
...nintentionally broke existing nss applications that need to generate or use such keys, via apis such as seckey_creatersaprivatekey or seckey_createdhprivatekey. in nss 3.19.2, this change in freebl behaviour has been reverted. the fix for bug 1138554 has been moved to libssl, and will now only affect the minimum keystrengths used in ssl/tls. note: future versions of nss may increase the minimum keysizes required by the freebl module. consumers of nss are strongly encouraged to migrate to stronger cryptographic strengths as soon as possible. bugs fixed in nss 3.19.2 this bugzilla query returns all the bugs fixed in nss 3.19.2: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.19.2 compatibilit...
NSS 3.35 release notes
distribution information the hg tag is nss_3_35_rtm. nss 3.35 requires nspr 4.18, or newer. nss 3.35 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_35_rtm/src/ new in nss 3.35 new functionality tls 1.3 support has been updated to draft -23. this includes a large number of changes since 3.34, which supported only draft -18. see below for details. new types in sslt.h sslhandshaketype - the type of a tls handshake message. ...
...formatsql added formally verified implementations of non-vectorized chacha20 and non-vectorized poly1305 64-bit. for stronger security, when creating encrypted pkcs#7 or pkcs#12 data, the iteration count for the password based encryption algorithm has been increased to one million iterations. note that debug builds will use a lower count, for better performance in test environments. as a reminder, debug builds should not be used for production purposes. nss 3.30 had introduced a regression, preventing nss from reading some aes encrypted data, produced by older versions of nss. nss 3.35 fixes this regression and restores the ability to read affected data. the following ca certificates were removed: ou = security communication ev rootca1 sha-256 fingerprint: a2:2d:ba:68...
...pted when nss is being used as a server. keyupdate can be triggered by the experimental ssl_keyupdate() function. tls servers can screen new tls 1.3 connections, as they are made using the experimental ssl_helloretryrequestcallback function. this function allows for callbacks to be installed, which are called when a server receives a new tls clienthello. the application is then able to examine application-chosen content from the session tickets, or helloretryrequest cookie, and decide whether to proceed with the connection. for an initial clienthello, an application can control whether nss sends a helloretryrequest, and include application-chosen content in the cookie. new experimental apis below is a list of experimental functions, which might not be available in future rele...
NSS 3.45 release notes
the nss team would like to recognize first-time contributors: bastien abadie christopher patton jeremie courreges-anglas marcus burghardt michael shigorin tomas mraz distribution information the hg tag is nss_3_45_rtm. nss 3.45 requires nspr 4.21 or newer. nss 3.45 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_45_rtm/src/ other releases are available in nss releases. ...
...certificates, secfailure is returned and *results will be null. notable changes in nss 3.45 bug 1540403 - implement delegated credentials (draft-ietf-tls-subcerts) this adds a new experimental function: ssl_delegatecredential note: in 3.45, selfserv does not yet support delegated credentials. see bug 1548360. note: in 3.45 the sslchannelinfo is left unmodified, while an upcoming change in 3.46 will set sslchannelinfo.authkeybits to that of the delegated credential for better policy enforcement. see bug 1563078. bug 1550579 - replace arm32 curve25519 implementation with one from fiat-crypto bug 1551129 - support static linking on windows bug 1552262 - expose a function pk11_findrawcertswithsubject for finding certificates with a given subject on a given slot bug...
...shed 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 instead 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=fi...
NSS 3.47 release notes
introduction the nss team has released network security services (nss) 3.47 on 18 october 2019, which is a minor release. the nss team would like to recognize first-time contributors: christian weisgerber deian stefan jenine distribution information the hg tag is nss_3_47_rtm. nss 3.47 requires nspr 4.23 or newer. nss 3.47 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_47_rtm/src/ other releases are available in nss releases. ...
...contributors: christian weisgerber deian stefan jenine distribution information the hg tag is nss_3_47_rtm. nss 3.47 requires nspr 4.23 or newer. nss 3.47 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_47_rtm/src/ other releases are available in nss releases. upcoming changes to default tls configuration the next nss team plans to make two changes to the default tls configuration in nss 3.48, which will be released in early december: tls 1.3 will be the default maximum tls version. see bug 1573118 for details. tls extended master secret will be enabled by default, where possible. see bug 1575411 for details. notable changes in nss 3.47 bug 1152625...
... confusing error when trying to export non-existent cert with pk12util bug 1578626 - [cid 1453375] ub: decrement nullptr. bug 1578751 - ensure a consistent style for pk11_find_certs_unittest.cc bug 1570501 - add cmac to freebl and pkcs #11 libraries bug 657379 - nss uses the wrong oid for signaturealgorithm field of signerinfo in cms for dsa and ecdsa bug 1576664 - remove -mms-bitfields from mingw nss build. bug 1577038 - add pk11_getcertsfromprivatekey to return all certificates with public keys matching a particular private key this bugzilla query returns all the bugs fixed in nss 3.47: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.47 compatibility nss 3.47 shared libraries are backward com...
NSS 3.48 release notes
the nss team would like to recognize first-time contributors: craig disselkoen giulio benetti lauri kasanen tom prince distribution information the hg tag is nss_3_48_rtm. nss 3.48 requires nspr 4.24 or newer. nss 3.48 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_48_rtm/src/ other releases are available in nss releases. notable changes in nss 3.48 tls 1.3 is the default maximum tls version. ...
...,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. applications may set environment variable nss_min_mp_pbe_iteration_count to request a higher iteration count than the library's default, or nss_max_mp_pbe_iteration_count to request a lower iteration count for test environments. see bug 1562671 for details. certificate authority changes the following ca certificates were added: bug 1591178 - entrust root certification authority - g4 cert sha-256 fingerprint: db3517d1f6732a2...
...ibrary's default, or nss_max_mp_pbe_iteration_count to request a lower iteration count for test environments. see bug 1562671 for details. certificate authority changes the following ca certificates were added: bug 1591178 - entrust root certification authority - g4 cert sha-256 fingerprint: db3517d1f6732a2d5ab97c533ec70779ee3270a62fb4ac4238372460e6f01e88 upcoming changes in nss 3.49 the legacy dbm database, libnssdbm, will no longer be built by default. see bug 1594933 for details. bugs fixed in nss 3.48 bug 1600775 - require nspr 4.24 for nss 3.48 bug 1593401 - fix race condition in self-encrypt functions bug 1599545 - fix assertion and add test for early key update bug 1597799 - fix a crash in nssckfwobject_getattributesize bug 1591178 - ad...
NSS PKCS11 Functions
o in most application ui's. you should make sure tokendescription is unique. slotdescription the slotdescription value for this token returned in the ck_slot_info structure with an internationalize string (utf8). this value will be truncated at 64 bytes (no null, partialutf8 characters dropped). this name will not change after thedatabase is closed. it should have some number to make this unique. minpwlen then minimum password length for this token. flags a comma separated list of flag values, parsed case-insensitive. valid flags are: readonly - databases should be opened read only. nocertdb - don't try to open a certificate database. nokeydb - don't try to open a key database. forceopen - don't fail to initialize the token if thedatabases could not be opened. passwordrequired - zero length ...
...uccessful, returns null. many tokens keep track of the number of attempts to enter a password and do not allow further attempts after a certain point. therefore, if the retry argument is pr_true, indicating that the password was tried and is wrong, the callback function should return null to indicate that it is unsuccessful, rather than attempting to return the same password again. failing to terminate when the retry argument is pr_true can result in an endless loop. several functions in the nss libraries use the password callback function to obtain the password before performing operations that involve the protected information. the third parameter to the password callback function is application-defined and can be used for any purpose. for example, mozilla uses the parameter to pass inform...
...otected information. the third parameter to the password callback function is application-defined and can be used for any purpose. for example, mozilla uses the parameter to pass information about which window is associated with the modal dialog box requesting the password from the user. when nss ssl libraries call the password callback function, the value they pass in the third parameter is determined by ssl_setpkcs11pinarg. see also for examples of password callback functions, see the samples in the samples directory. ...
PKCS11 Implement
th guidelines for implementors of cryptographic modules who want their products to work with mozilla client software: how nss calls pkcs #11 functions. function-specific information organized in the same categories as the pkcs #11 specification. functions for different kinds of tokens. summarizes the support nss expects from different kinds of tokens. installation. installing modules and informing the user of changes in the cryptographic modules settings. semantics unique to nss. miscellaneous nss semantics that affect module implementation. future versions of netscape server products will also support of pkcs #11 version 2.0. how nss calls pkcs #11 functions this section is organized according to the categories used in pkcs #11: cryptographic token interface standard, version 2.0. to u...
... is null. these are not standard pkcs #11 semantics; they are intended for nss's internal use only. true true the device has been initialized and requires authentication. the nss checks whether the user is logged on, and if not prompts the user for a pin. c_getmechanismlist the nss calls c_getmechanismlist fairly frequently to identify the mechanisms supported by a token. c_getmechanisminfo the nss currently doesn't call c_getmechanisminfo. this function may be called in the future, so you should implement it anyway. c_inittoken the nss never calls c_inittoken. c_initpin the nss calls c_initpin only in the key generation case, as noted in this document under c_gettokeninfo, when cfk_login_required = true and cfk_user_pin_initialized = false. c_setpin called only in the k...
... a token has been removed and then the same or another token is inserted, c_getsessioninfo should return ckr_session_handle_invalid. c_login the nss calls c_login on a token's initial session whenever ckf_login_required is true and the user state indicates that the user isn't logged in. c_logout the nss calls c_logout on a token's initial session when the password is timed out when performing any kind of private key operation if "ask always" is turned on when changing a password when the user logs out object management c_createobject the nss calls c_createobject when loading new private keys and new certificates into a token. typically, nss uses c_createobject for creating a new private key if pkcs #12 is operating or if your writable token doesn't support c_generatekeypair. c...
Rhino optimization
also, you must use this optimization level if your code uses continuation objects. if the optimization package is not available, then optimization acts as if it is always -1. 0 no optimizations are performed. ...
...also, you must use this optimization level if your code uses continuation objects. if the optimization package is not available, then optimization acts as if it is always -1. 0 no optimizations are performed. ...
...o, you must use this optimization level if your code uses continuation objects. if the optimization package is not available, then optimization acts as if it is always -1. 0 no optimizations are performed. the bytecode compiler runs fastest in this mode, but the generated byte code is less efficient. 1-9 all optimizations are performed. simple data and type flow analysis is performed to determine which javascript variables can be allocated to java vm registers, and which variables are used only as numbers. local common sub-expressions are collapsed (currently this only happens for property lookup, but in the future more expressions may be optimized). all local variables and parameters are allocated to java vm registers. function call targets are speculatively pre-cached (based on the nam...
Rebranding SpiderMonkey (1.8.5)
for example the default brand for spidermonkey 1.8.5 is 'mozjs185'. mkdir build-$brand-release cd build-$brand-release configure this build of spidermonkey with the desired options. for example: ../configure --enable-ctypes --with-system-nspr note: your desired configuration may be different. the only required part in this step is the ../configure command. ...
...e fact that these files are automatically generated and very little constant data can be depended upon. it also allows these instructions to apply to a wide range platforms without introducing more software dependencies. save the file and exit the editor. 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. your rebranded library has been succesfully built and installed to libdir as specified in ./config/autoconf.mk. a pkgconfig file has also been installed for your library at libdir/pkgconfig/$brand.pc. you may wis...
...ou may wish to manually edit this file. it describes your library package. the script file js-config has not been modified either and still points to mozjs185. if this is not desirable, you can issue the following command on unix systems: sed -i "s/mozjs185/$brand/" /usr/bin/js-config which performs a simple text replacement of mozjs185 with your branding on the js-config script. you may need administrative rights to run the above command. ...
JS_AlreadyHasOwnProperty
this article covers features introduced in spidermonkey 1.8 determine whether a property is already physically present on a jsobject. syntax boo js_alreadyhasownproperty(jscontext *cx, js::handleobject obj, const char *name, bool *foundp); boo js_alreadyhasownucproperty(jscontext *cx, js::handleobject obj, const char16_t *name, size_t namelen, bool *foundp); boo js_alreadyhasownpropertybyid(jscontext *cx, js::handleobject obj, js::handleid id, bool *foundp); // added in spidermonkey 1.8.1 boo js_alreadyhasownelement(jscontext *cx, js::handleobject obj, uint32_t index, bool *foundp); name type description cx jscontext * pointer to a js context. req...
... the object to be searched. name or id const char * or const char16_t *or js::handleid (in js_alreadyhasownproperty, alreadyhasownucproperty, and js_alreadyhasownpropertybyid) the name of the property to search for. ...
...by design, this search may not find a property that other property lookup functions, such as js_lookupproperty, would find. ...
JS_ConvertArguments
o a jsnative or jsfastnative callback, not an array created by application code. in certain error cases, js_convertarguments calls js_argv_callee(argv), which accesses memory outside the range [argv .. argv+argc). js_convertarguments may modify argv in place by replacing an argument with the converted value. (the purpose is to ensure gc safety.) format const char * null-terminated string describing the types of the out parameters and how to convert the values in argv. ... void * out parameters. pointers to variables into which to store the converted values. there must be one pointer for each parameter described in format. variables for optional parameters must already be initialized, because if an optional parameter is not in argv, js_convertar...
...es with a single function call. it saves you from having to write separate tests and elaborate if...else statements in your function code to retrieve and translate multiple js values for use with your own functions. cx is the context for the call. argc indicates the number of js values you are passing in for conversion. argv is a pointer to the array of js values to convert. format is a null-terminated c string. each element of the array indicates the c type into which to convert the next available js value. format can contain one or more instances of the following characters, as appropriate: character c type description b bool boolean c uint16_t ecma uint16_t, unicode character i int32_t ecma int32_t j int32_t ecma...
... this conversion is dangerous and almost entirely useless, because the resulting jsfunction is not a real function object and therefore cannot be safely passed to any other jsapi function. that includes js_callfunction...
JS_DefinePropertyWithTinyId
es request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * object for which to create the new property. name const char * or const jschar * name for the property to create. namelen size_t (only in js_defineucpropertywithtinyid) the length of name in characters; or (size_t) -1 to indicate that name is null-terminated. tinyid int8 8-bit id to aid in sharing getter and setter callbacks among properties. value jsval initial stored value for the new property. getter jspropertyop getproperty method for retrieving the current property value. setter jspropertyop setproperty method for specifying a new property value. attrs unsigned int pr...
...class.addproperty, .delproperty, .getproperty, and .setproperty. tiny ids only affect the ids passed to these hooks; the javascript engine does not use them as property names internally. tiny ids are helpful for getters and setters that are shared by several different properties. those getters and setters can use switch (jsval_to_int(id)), instead of checking the value of id as a string, to determine which property is being accessed. however, tiny ids can cause confusion when used with jsclass callbacks. for example, if a property named "color" is defined with tiny id 10, then the javascript expressions obj[10] and obj.color will both result in int_to_jsval(10) being passed to jsclass.getproperty as the id parameter. per-property getters and setters do not suffer from this confusion: in the...
... id 10, then the javascript expressions obj[10] and obj.color will both result in int_to_jsval(10) being passed to jsclass.getproperty as the id parameter. per-property getters and setters do not suffer from this confusion: in the above example, obj.color would cause the javascript engine to call the getter for the color property, but obj[10] wouldn't. traditionally, negative tiny ids are used to minimize the potential confusion, but it is best to specify a non-null getter and setter when defining a property with a tiny id. on success, js_definepropertywithtinyid and js_defineucpropertywithtinyid return js_true. if the property already exists or cannot be created, they return js_false. see also bug 975069 ...
JS_ObjectIsRegExp
if so, js_objectisregexp returns true. otherwise it returns false. ...
...if so, js_objectisregexp returns true. otherwise it returns false. ...
...if so, js_objectisregexp returns true. otherwise it returns false. ...
JS_PushArguments
conversions. cx also affects the interpretation of format, if js_addargumentformatter has been called. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. markp void ** out parameter. on success, *markp receives the internally allocated stack mark which should be passed to js_poparguments. format const char * null-terminated string holding a list of format types to convert the following arguments to. ... various (in js_pusharguments) a variable number of arguments to be converted to jsvals. there must be one argument for each argument described in format. ap va_list (in js_pushargumentsva) the list of arguments to be converted to jsvals. there must be one argument for each argument d...
...ts to. ... various (in js_pusharguments) a variable number of arguments to be converted to jsvals. there must be one argument for each argument described in format. ap va_list (in js_pushargumentsva) the list of arguments to be converted to jsvals. there must be one argument for each argument described in format. the type va_list is a standard feature of the c programming language. it is defined in <stdarg.h>. description js_pusharguments provides a convenient way to translate a series of native c/c++ values to jsvals with a single function call. cx is the context for the call. markp points to a void * to hold the internally allocated stack frame pointer to pass back to js_poparguments. format is a sequential character array, where each element of the array...
...any asterisks (*) in format are ignored. this function also takes in consideration any additional custom types defined in cx using js_addargumentformatter. for example, if format is "biob", then there must be four arguments after format. their types must be jsbool, jsdouble, jsobject *, and jsbool. if succes...
JS_TypeOfValue
the return value is always one of jstype_void, jstype_object, jstype_function, jstype_string, jstype_number, or jstype_boolean. ...
...the return value is always one of jstype_void, jstype_object, jstype_function, jstype_string, jstype_number, or jstype_boolean. ...
...of a js value. syntax jstype js_typeofvalue(jscontext *cx, js::handle<js::value> v); name type description cx jscontext * the context in which to perform the type check. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. v js::handle&lt;js::value&gt; the value to examine. description js_typeofvalue examines a specified js value, v, and returns its js data type. the return value is always one of jstype_void, jstype_object, jstype_function, jstype_string, jstype_number, or jstype_boolean. see also mxr id search for js_typeofvalue js_convertvalue js_gettypename js_valuetoboolean js_valuetofunction js_valuetoint32 js_valuetonumber js_valuetoobject js_valuetostring ...
SpiderMonkey 1.8.7
ne of the configuration options to enable nspr (e.g. --with-system-nspr). xxx all sections below need updating garbage collection spidermonkey 1.8.5 introduces a conservative stack-scanning garbage collector. unlike the exact garbage collector, the new garbage collector will scan the c stack and registers in your embedding, looking for bits that it can treat as potential gc roots. the approach eliminates the need for the js_enterlocalrootscope api, and in many cases the need to explicitly root gc things or use the "root as you go" approach popular with earlier spidermonkey releases. since this is a conservative collector, it will often find "garbage" addresses which can trigger warnings from certain code analysis tools. if you are running valgrind on your embedding, be sure to build spiderm...
... releases. since this is a conservative collector, it will often find "garbage" addresses which can trigger warnings from certain code analysis tools. if you are running valgrind on your embedding, be sure to build spidermonkey with the --enable-valgrind option to suppress superflous error messages triggered by the garbage collector. this also means that objects will be finalized in a non-deterministic order in spidermonkey 1.8.5. this is not a bug, and, any embedding which depends upon deterministic finalization is fatally flawed. typed rooting api the rooting api has been changed from an error-prone void ** interface to an interface which accepts pointers to specific types. js_addroot has been replaced by js_addobjectroot, js_addvalueroot and js_addstringroot; similar changes were made ...
...tions in the javascript shell, mostly useful for testing spidermonkey. the scatter function has been removed, and a shell worker class (similar to html dom workers) has been added. known issues mac os x 10.5 (leopard) and xcode 3.2 spidermonkey will not build with certain builds of apple's gcc 4.2 c++ compiler. to check what version you are running, issue the command /usr/bin/g++-4.2 -v from a terminal window. the following builds are known to not work: i686-apple-darwin9-g++-4.2.1 (gcc) 4.2.1 (apple inc. build 5574) to work around this issue, either upgrade your xcode or use an alternate version of gcc, such as the one that shipped with leopard. to select an alternate c++ compiler, invoke configure thus: cxx=/usr/bin/g++-4.0 /path/configure --my-configuration-options js-config the new con...
SpiderMonkey 1.8
nown significant regression from 1.7. in js_threadsafe builds, some objects are not safe to be shared among threads. this includes iterators and generators (bug 349263) and arrays (bug 417501). in short, applications that share objects among threads in such a way that two threads could access an array, iterator, or generator object at the same time should not use spidermonkey 1.8. there is a minor known bug in the new javascript 1.8 functionality. when javascript 1.8 support is enabled, the parser accepts some incorrect programs by inserting a semicolon where it should instead throw a syntaxerror (bug 384758). this bug will be fixed in 1.8.1. migrating to spidermonkey 1.8 spidermonkey 1.8 is not binary-compatible with previous releases. it is source-compatible with spidermonkey 1...
...if you would like to contribute and maintain a project file, please feel free to contact the spidermonkey team via email, bugzilla, or irc.) alternatively, you can install mozillabuild and run the command make -f makefile.ref in the js/src directory. spidermonkey 1.8 does not include the new tracemonkey jit or the configure-based build system, both of which are (a) pretty darn awesome and (b) coming in spidermonkey 1.8.1. on to the fun stuff. new javascript language features javascript 1.8 adds array.reduce() and reduceright(), expression closures, and generator expressions. there is also one obscure non-backwards-compatible change. for details, see new in javascript 1.8. new jsapi features it has been a couple years since spidermonkey 1.7 was released, and many improvements have been ...
...urity features should heed the warning in its api documentation. new macros js_fs, js_fn, and js_fs_end are recommended for populating jsfunctionspec arrays. js_newobjectwithgivenproto is exactly like js_newobject except that it doesn't use a default prototype object if you pass null. instead the object is created with no prototype. js_alreadyhasownproperty and friends are new functions for examining an object without triggering resolve hooks. it was possible to configure spidermonkey 1.7 to treat c/c++ char strings as utf-8 by compiling with a non-default compiler option. in spidermonkey 1.8, it is no longer necessary to make a special build to get this behavior. applications can turn on utf-8 at run time by calling js_setcstringsareutf8. js_encodestring is a new variation on js_getstri...
TPS Tests
ictly speaking, restmail isn't required, but it will allow tps to automatically do account confirmation steps for you. even if you opt not to use restmail, do not use your personal firefox account, as tps will delete and replace the data in it many times, not to mention the first run is very likely to fail, since it expects a clean start). note: be prepared not to use your computer for 15 or so minutes after starting a full run of tps, as it will open and close a fairly large number of firefox windows. steps get the source code clone mozilla-central (choose your flavor): hg clone hg.mozilla.org/mozilla-central or git clone github.com/mozilla/gecko-dev cd into the tps folder cd testing/tps create the environment i suggest the path t...
...ses the phase blocks are where the action happens! they tell tps what to do. each phase block contains the name of a phase, and a list of actions. tps iterates through the phase blocks in alphanumeric order, and for each phase, it does the following: launches firefox with the profile from the phases object that corresponds to this test phase. performs the specified actions in sequence. determines if the phase passed or failed; if it passed, it continues to the next phase block and repeats the process. a phase is defined by calling the phase function with the name of the phase and a list of actions to perform: phase('phase1', [ [bookmarks.add, bookmarks_initial], [passwords.add, passwords_initial], [history.add, history_initial], [sync, sync_wipe_server], ]); each action is ...
...oquitapplication() calls in services/sync/tps/extensions/tps/modules/tps.jsm (remember to undo this later!). you will have to manually quit the browser at each phase, but you will be able to inspect the browser state manually. using this technique in conjunction with aboutsync is helpful. (note that the python testrunner will generally still kill firefox after a tps test runs for 5 or so minutes, so it's often helpful to kill the python testrunner outright, and then use aboutsync in a different instance of the browser). a tps failure may not point directly to the problem. for example, most errors involving bookmarks look like "places item not found in expected index", which could mean a number of issues. the other engines are similarly unhelpful, and will likely fail if t...
Handling Mozilla Security Bugs
ccess control restrictions will no longer be in effect. full information about security bugs will be restricted to a known group of people, using the bugzilla access control restrictions described above. however, that group can and will be expanded as necessary and appropriate. as noted above, information about security bugs can be held confidential for some period of time; there is no pre-determined lmit on how long that time period might be. however, this is offset by the fact that the person reporting a bug has visibility into the activities (if any) being taken to address the bug, and has the power to open the bug report for public scrutiny. the remaining sections of this document describe in more detail how these general policies have been implemented in practice. organizational str...
...ften singled out as security-relevant or who have security-relevant bugs assigned to them), and security qa people who are the qa contacts for those bugs. exploit hunters with a good track record of finding significant mozilla security vulnerabilities. representatives of the various companies and groups actively distributing mozilla-based products. super-reviewers and drivers. the bugzilla administrators will technically be in the mozilla security bug group as well, mainly because they already have visibility into all bugzilla data hosted through mozilla.org. the mozilla security bug group will have a private mailing list, security-group@mozilla.org, to which everyone in the security bug group will be subscribed. this list will act as a forum for discussing group policy and the addition...
... be significantly larger than the core group of module owners and peers, and that it may grow further over time. new members can be added to the mozilla security bug group as follows: new people can apply to join the security bug group, or may be recruited by existing members. applicants for membership must have someone currently in the security bug group who is willing to vouch for them and nominate them for membership. nomination is done by the "voucher" sending e-mail to the security bug group private mailing list. the applicant's nomination for membership will then be considered for a period of a few days, during which members of the security bug group can speak out in favor of or against the applicant. at the end of this period, the security module owner will decide to accept the ap...
Signing Mozilla apps for Mac OS X
types of accounts only allow for the "agent" role to create developer ids. contact the person who created your group apple developer account if you get stuck here. the codesign tool apple provides a tool called codesign; this command-line application is used to add a signature to an application bundle. the man page for codesign is available online, or you can simply type "man codesign" in a terminal window. the main options of note are: -s your-signing-identity lets you specify the signing certificate you want to sign the application with your-signing-identity is the name of your certificate. --keychain /path/to/keychain lets you specify which keychain contains the signing certificate specified by your-signing-identity, rather than allowing the codesign to search the keychain list. t...
... of the codesign tool's output. --deep for v2 signing, sign all nested executables with the same settings. note that you cannot specify an identifier requirement if you do this, or otherwise you need to sign the outer application again with the identifier requirement. --requirement 'designated requirement' adds additional requirements for verifying the signature and application metadata. ...
...you'll of course need to change the signing id, keychain, bundle path, and requirements. ...
History Service Design
common action usually executed on user interaction) could end up locking the ui till the database i/o to save data is complete. for this reason visits and favicons are added lazily on a timer. in future this will probably change in favour of storage asynchronous statements, so that the inserts will be queued-up by mozstorage itself in a separate thread. sql queries are built with performance in mind, and constantly tested against large databases. database indexes are quite important, and a good query can make the difference between minutes or seconds. many queries are especially optimized, for example limited history queries, often used to build menus, allowing for good performances even in presence of a really large history. storing pages and visits pages (intended as uris) are stored in...
...e is assigned to a history result object, that can be furtherly modified setting for example a sorting mode. only the first level of a node is usually filled, internal nodes or queries will populate themselves when opened. an implementer working on a ui can then associate a viewer with the result, so that it will be notified when the result tree changes. queries can act on a variety of datas, coming from all dependant services, so it is possible to query history, bookmarks or both, also with values coming from other services like tags, annotations. result nodes can be simple uri nodes with page attributes or complete visit attributes, or can be containers (folders, other queries, dynamic containers and so on). see querying places for deeper knowledge on the actual implementation. expirati...
...tain moments, but in future will most likely be moved to async queries, to be executed on a separate thread. actually pages and visits are expired: on page added (lazily) on idle on shutdown expiration of pages happens when a page is no more referenced, so there are no more visits, nor bookmarks associated with it. visits are expired based on user preferences, there is an hard limit on the minimum number of days that should be retained, visits in that range won't never expire. visits inside a slushy limit (> than the hard limit) will be removed only if we are over a maximum number of pages we can retain, for performance issues. finally expiration can be forced by the user himself to clean up the full history or slices of it (last hour, last day, ...). see places expiration for more i...
Using the Places annotation service
database. creating the annotation service the annotation contract id is @mozilla.org/browser/annotation-service;1 var annotationservice = components.classes["@mozilla.org/browser/annotation-service;1"] .getservice(components.interfaces.nsiannotationservice); note that the annotation service is not thread-safe. you should only use it from the main thread. naming your annotations for your annotation name, you should use the format <namespace>/<name>. for example, "my_extension/page_state". the annotation service does not currently enforce the annotation name format, but this may change in the future. also, we may add functions to get all of "your" annotations matching a given namespace. you should not use any characters in your annotation names that ar...
...on to perform all of these operations: setpageannotation(auri, aname, avalue, aflags, aexpiration); setitemannotation(aitemid, aname, avalue, aflags, aexpiration); these annotations all take similar parameters: uri or itemid: this is the nsiuri of the page to annotate, or for items in the places database, the id of the item. name: this is the name of the annotation. see the section on naming above. value: the value of the annotation. flags: currently unused. should be 0. expiration: the expiration time for the annotation (see "lifetime of annotations" below). var ioservice = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uri = ioservice.newuri("http://www.mozilla.org/", null, null); annotat...
...ationint64(aitemid, aname); getitemannotationdouble(aitemid, aname); getitemannotationbinary(aitemid, aname, adata, adatalen, amimetype); from javascript: getpageannotation(auri, aname); getitemannotation(aitemid, aname); these functions will return/throw ns_error_not_available if the annotation requested does not exist. you can use the annotations service's hasannotation method to determine in advance if the page has the requested annotation. however, it is more efficient to just try to do the operation and catch the exception; the extra check requires an additional database lookup (which has higher overhead). but then again you won't know if the exception meant that the annotation did not exist or something else is broken. the getter functions return only the value of the annotat...
Using the Places history service
sic function for adding pages to history that is called by the docshell as you browse. the redirect flag is deprecated. see adddocumentredirect below. nsiglobalhistory3.adddocumentredirect: this is called by the docshell when a redirect occurs. it replaces the old redirect flag on adduri. it gives the old and new channels to the history service so that the source page of the redirect can be determined. nsibrowserhistory.addpagewithdetails: called by history importing code. new code should use nsinavhistoryservice.setpagedetails. nsinavhistoryservice.addvisit: this is an advanced function that allows the caller to set the exact referring visit, the time, the session, etc. it is designed for people writing synchronizing or backup services that need access to all the flags. under normal brows...
....getgeckoflags: retrieves information previously set using setgeckoflags. it is not yet implemented in the places history system. nsibrowserhistory.lastpagevisited: contains the uri of the last page visited. this is used when the preference is set that causes the last page in new windows. nsibrowserhistory.count: the number of pages in history. this is used by the "clear history" button to determine if there are any pages in history. because actually counting all the pages in history is expensive,navhistory will always return the value 0 or 1. 0 is returned when there is no history, 1 is returned when there are one or more pages in history.deprecated, use hashistoryentries instead. nsinavhistoryservice.hashistoryentries: exactly the same as nsibrowserhistory.count, except with a better nam...
...expensive,navhistory will always return the value 0 or 1. 0 is returned when there is no history, 1 is returned when there are one or more pages in history.deprecated, use hashistoryentries instead. nsinavhistoryservice.hashistoryentries: exactly the same as nsibrowserhistory.count, except with a better name and actually returning a boolean. preferred over "count". nsinavhistory.canadduri: determines whether the given uri will be stored by the history system. many types of uris, such as "chrome:" uris, are not stored when adduri is called. this function allows you to determine whether it will be or not. advanced querying see querying places for more detailed examples on how to used the advanced querying functionality of navhistory. nsinavhistoryservice.getnewquery: returns a new q...
Using the Places livemark service
uri("http://example.com/"), uri("http://example.com/rss.xml"), -1); the parameters here are the same as for nsilivemarkservice.createlivemark(), except for the insertion of a new parameter at the beginning, which is the nsinavbookmarksservice to use when creating the livemark. ...
...xample.com/rss.xml"), -1); the parameters here are the same as for nsilivemarkservice.createlivemark(), except for the insertion of a new parameter at the beginning, which is the nsinavbookmarksservice to use when creating the livemark. determine whether a folder is a livemark you can use the nsilivemarkservice.islivemark() method to determine whether or not a given folder is a livemark container: if (livemarkservice.islivemark(folderid)) { // it's a livemark } else { // it's not a livemark } accessing the container's site uri the nsilivemarkservice.getsiteuri() method lets you obtain the nsiuri of the website associated with a livemark container. var siteuri = livemarkservice.getsiteuri(newlvmkid); //newlvmkid = s...
...its feed uri (since the contents are likely to be different given a different feed). livemarkservice.setfeeduri(newlvmkid, uri("http://foo.example.com/rss.xml")); //newlvmkid = see "create a new livemark" for more detail. update behavior five seconds after the browser starts up, the livemark service's update timer is started. the update timer fires immediately, and then every 15 minutes thereafter. when the update timer fires, it iterates over the list of livemarks, and will refresh a livemark *only* if it's expired. the expiration time for a livemark is determined by using information provided by the server when the feed was requested, specifically nsicacheentryinfo.expirationtime. if no information was provided by the server, the default expiration time is 1 hour. users ca...
Accessing the Windows Registry Using XPCOM
wsregkey interface, in this case root_key_local_machine, which corresponds to hkey_local_machine in the windows registry. also notice that the path to the key has backslashes escaped, a necessity in javascript and c++ string constants. the desired access rights are specified using a named constant from the interface, in this example access_read. this can be very important when dealing with non-administrator accounts with restricted privileges. the value is read using readstringvalue(). you have to specify what type of data you expect to read, which we will expand on later. finally, note that you should close the key when you are done to avoid wasting system resources. opening registry keys before doing anything with a registry key you must first open the key you are interested in. the exa...
...wrk.close(); monitoring registry keys if you would like to know whether a registry key has changed since you last checked it, you can use the startwatching(), stopwatching(), and haschanged() methods. you must call startwatching() for the key to be monitored. the method takes one parameter, a boolean indicating whether child keys should be watched. after that, you can call haschanged() to determine whether or not you need to reread the value. calling haschanged() automatically resets the watch, so you can be sure that if it returns true there are changes. this example demonstrates a trivial registry value cache for one key: var cache = {}; function readregistryvaluenocache(wrk, value) { switch (wrk.getvaluetype(value)) { case wrk.type_string: return wrk.readstringvalue(value)...
...ts.interfaces.nsiwindowsregistry); var id = wss.getregistryentry(wss.hklm, "software\\microsoft\\windows\\currentversion", "productid"); backwards compatibility if you need to support firefox 1.0 and other older browser versions, you should check to see which interfaces are available. ...
Setting up the Gecko SDK
s alt-f7). most of the changes you make in the following steps apply to all configurations of the project (both debug and optimized), so select "all configurations" from the settings for dropdown menu: on the c/c++ tab, select the preprocessor category. ...
...is window is where you add the include paths to the gecko sdk as well as two preprocessor defines: xpcom_glue mozilla_strict_api at a minimum, you must include the nspr, the embedstring and string include directories, and the xpcom include subdirectory. if your component will use other parts of the sdk (e.g., necko), you will have to add these include directories to this field as well. 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. as described in the section exceptions in xpcom, exception handling isn't supported across interface boundaries, so setting this ...
...tensions directory. %applicationdata%\mozilla\firefox\profiles\x.extensions\extensions\bob@george.com. then copy the .xpt file to the c:\program files (x86)\mozilla firefox\components directory. next run the regxpcom to registister the component in firefox (this writes to the 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. i used xpcomviewer, to make sure the class and the interfac...
Using XPCOM Utilities to Make Things Easier
linear sequences of characters. in c++, the string literal "xpcom", for example, consists of 6 consecutive bytes, where `x' is at byte offset zero and a null character is at byte offset 5. other kinds of strings like "wide" strings use two bytes to represent each character, and are often used to deal with unicode strings. the string classes in xpcom are not just limited to representing a null terminated sequence of characters, however. they are fairly complex because they support the gecko layout engine and other subsystems that manage large chunks of data. additionally, in some versions of mozilla the string classes support sequences of characters broken up into multiple fragments (fragments which may or may not be null terminated)[nulls-in-strings]. all string classes in xpcom derive from...
...to keep this string data around past the lifetime of the string object, you must make a copy. string size the examples above illustrate the use of the single byte string class, nsembedcstring. the double byte version, nsembedstring, has the same functionality but the constructor takes nsastring and the .get() method returns the type prunichar*. note that prunichar is a two byte value. in the coming chapters, you'll see examples that use this version in the weblock component. smart pointers all of the interfaces that you've seen so far are reference counted. leaking a reference by not releasing an object, as the code below demonstrates, can be a major problem. { nsisupports* value = nsnull; object->method(&value); if (!value) return; // ... if (ns_failed(error)) return; ...
...g an object, as the code below demonstrates, can be a major problem. { nsisupports* value = nsnull; object->method(&value); if (!value) return; // ... if (ns_failed(error)) return; // <------------ leaks |value| //... ns_release(value); // release our reference } a method returns an nsisupports interface pointer that has been reference counted before it is returned (assuming it wasn't nsnull). if you handle an error condition by returning prematurely, whatever value points at will leak-it will never be deleted. this is a trivial fix in this example, but in real code, this can easily happen in goto constructs, or in deep nesting with early returns. having more than one interface pointer that needs to be released when a block goes out of scope begs for a tool that ca...
Detailed XPCOM hashtable guide
time: o(1): lookup time is a simple constant o(1): lookup time is mostly-constant, but the constant time can be larger than an array lookup sorting: sorted: stored sorted; iterated over in a sorted fashion. unsorted: stored unsorted; cannot be iterated over in a sorted manner. inserting/removing: o(n): adding and removing items from a large array can be time-consuming o(1): adding and removing items from hashtables is a quick operation wasted space: none: arrays are packed structures, so there is no wasted space. some: hashtables are not packed structures; depending on the implementation, there may be significant wasted memory. in their implementation, hashtables take the key and apply a mathematical hash function to randomize the key...
...entry class can be entirely inline. for examples of entry classes, see the declarations at xpcom/glue/nshashkeys.h. the template parameter is the entry class. you must use the init() function to initalize the table properly. at this point, use the functions putentry/getentry/removeentry to alter the hashtable. the iterator class will do iteration, but beware that the iteration will occur in a seemingly-random order (no sorting). nsthashtables can be allocated on the stack, as class members, or on the heap. entry pointers can and do change when items are added to or removed from the hashtable. do not keep long-lasting pointers to entries. because of this, nsthashtable is not inherently thread-safe. if you use a hashtable in a multi-thread environment, you must provide locking as appropri...
...) nsacstring nsid& nsidhashkey::hashkey() writing a good hash function is well beyond the scope of this document, and has been discussed extensively in computer-science circles for many years. there are many different types of hash functions. mozilla has tuned a good general-purpose hash algorithm for strings and nsid. original document information author(s): benjamin smedberg <benjamin@smedbergs.us> ...
Components.isSuccessCode
an xpcom return code indicates success if its high-order bit is 0, and it indicates failure if its high-order bit is 1. note: a non-zero xpcom return code (that is, not ns_ok) does not necessarily indicate failure. ...
...an xpcom return code indicates success if its high-order bit is 0, and it indicates failure if its high-order bit is 1. note: a non-zero xpcom return code (that is, not ns_ok) does not necessarily indicate failure. ...
...ay be essential. for example, if you ask a component or service to asynchronously perform some task, you must usually pass in an object which will be notified when the task is completed. if the task is sufficiently complex that it can fail, the notification will include a status code indicating the success or failure of the operation (see, for example, nsirequestobserver.onstoprequest()). to determine the success or failure of the complex task, you would call components.issuccesscode() upon the status code included in the notification. 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: nsiasyncstreamc...
Components.utils
exportfunction() export a javascript function from a more-privileged to a less-privileged scope, allowing it to be called in the less-privileged scope. forcegc() forces a garbage collection cycle. forcecc() forces a cycle collection cycle. forceshrinkinggc() forces a shrinking garbage collection cycle. getcomponentsforscope() this seemingly-paradoxical api allows privileged code to explicitly give unprivileged code a reference to its own components object (whereas it's normally hidden away on a scope chain visible only to xbl methods). see also specialpowers.getcomponents. getglobalforobject() returns the global object with which a given object is associated (through its prototype chain at birth, for example). ...
...weak reference for the object passed in. import() loads a js module into the current script, without sharing a scope. importglobalproperties() specify a list of constructors to import into the scope. isxraywrapper() test whether a given object is an xray or not. unload() unloads a js module loaded with import(). isdeadwrapper() determines whether this object is backed by a deadobjectproxy. lookupmethod() looks up a native (i.e. declared in the interface) method or property of an xpcom object. serves the same purpose as xpcnativewrapper. makeobjectpropsnormal() ensures that all functions come from the specified object's scope, and aren't cross-compartment wrappers. may only be called from javascript code. ...
...ject is backed by a deadobjectproxy. lookupmethod() looks up a native (i.e. declared in the interface) method or property of an xpcom object. serves the same purpose as xpcnativewrapper. makeobjectpropsnormal() ensures that all functions come from the specified object's scope, and aren't cross-compartment wrappers. may only be called from javascript code. nondeterministicgetweakmapkeys() return the keys in a weak map. this operation is non-deterministic because it is affected by the scheduling of the garbage collector and the cycle collector. this should only be used to write tests of the interaction of the gc and cc with weak maps. obsolete since gecko 45 the function was moved to threadsafechromeutils nukesandbox() r...
Language bindings
the scriptable methods on the nsicomponentmanager interface can be called directly on this object.components.resu...
...(c++) xpcom objects hanging off javascript objects though. in many cases a javascript application will have internal knowledge of javascript objects referencing large (trees of) xpcom objects and know when they are no longer reachable. in this case it can be important to be able to force a garbage collection cycle from javascript. components.utils.getglobalforobjectthis method is used to determine the global object with which an object is associated. this is the global object in place at the time the object was created, which is to say the global object used when executing the script that created the object.components.utils.getweakreferencethis method was introduced in firefox 3 and is used for obtaining a weak reference for an object. to obtain the object reference, you have to call get(...
...ut this language binding and how to use it.pyxpcompyxpcom allows for communication between python and xpcom, such that a python application can access xpcom objects, and xpcom can access any python class that implements an xpcom interface. pyxpcom is actively used in activestate komodo products, for example.rbxpcomrbxpcom (ruby cross-platform com) provides bindings between the popular ruby programming language and xpcom. you can find additional information using the resource links below.xpconnectxpconnect is a bridge between javascript and xpcom. with xpconnect, you can use xpcom components from javascript code, and interact with javascript objects from within xpcom components. xpconnect is part of firefox and is actively used in xul applications. ...
nsDependentCSubstring
y of string characters. it is the client code's responsibility to ensure that the external buffer remains valid for a long as the string is alive. ...
...riting() - source nswritingiterator<char>& endwriting(nswritingiterator<char>&) - source parameters nswritingiterator<char>& iter char*& endwriting(char*&) - source parameters char*& iter data char* data() const - source accessors length pruint32 length() const - source isempty prbool isempty() const - source isvoid prbool isvoid() const - source isterminated prbool isterminated() const - source charat char charat(pruint32) const - source parameters pruint32 i operator[] char operator[](pruint32) const - source parameters pruint32 i first char first() const - source last char last() const - source countchar pruint32 countchar(char) const - source parameters char <anonymous> findchar print32 find...
...ascii prbool equalsascii(const char*, pruint32) const - source an efficient comparison with ascii that can be used even for wide strings. call this version when you know the length of 'data'. parameters char* data pruint32 len prbool equalsascii(const char*) const - source an efficient comparison with ascii that can be used even for wide strings. call this version when 'data' is null-terminated. parameters char* data equalsliteral(const char prbool equalsliteral(const char (&)[n]) const - source equalsliteral(char prbool equalsliteral(char (&)[n]) const - source lowercaseequalsascii prbool lowercaseequalsascii(const char*, pruint32) const - source parameters char* data pruint32 len prbool lowercaseequalsascii(const char*) const - source parameters char...
nsDependentSubstring
y of string characters. it is the client code's responsibility to ensure that the external buffer remains valid for a long as the string is alive. ...
...dwriting(nswritingiterator<short unsigned int>&) - source parameters nswritingiterator<short unsigned int>& iter prunichar*& endwriting(prunichar*&) - source parameters prunichar*& iter data prunichar* data() const - source accessors length pruint32 length() const - source isempty prbool isempty() const - source isvoid prbool isvoid() const - source isterminated prbool isterminated() const - source charat prunichar charat(pruint32) const - source parameters pruint32 i operator[] prunichar operator[](pruint32) const - source parameters pruint32 i first prunichar first() const - source last prunichar last() const - source countchar pruint32 countchar(prunichar) const - source parameters prunichar <anonymous...
...ascii prbool equalsascii(const char*, pruint32) const - source an efficient comparison with ascii that can be used even for wide strings. call this version when you know the length of 'data'. parameters char* data pruint32 len prbool equalsascii(const char*) const - source an efficient comparison with ascii that can be used even for wide strings. call this version when 'data' is null-terminated. parameters char* data equalsliteral(const char prbool equalsliteral(const char (&)[n]) const - source equalsliteral(char prbool equalsliteral(char (&)[n]) const - source lowercaseequalsascii prbool lowercaseequalsascii(const char*, pruint32) const - source parameters char* data pruint32 len prbool lowercaseequalsascii(const char*) const - source parameters char...
IAccessibleTable
or the index of the first column if the child spans multiple columns. return value e_invalidarg if bad [in] passed, [out] value is 0. s_ok. iscolumnselected() returns a boolean value indicating whether the specified column is completely selected. [propget] hresult iscolumnselected( [in] long column, [out] boolean isselected ); parameters column 0 based index of the column for which to determine whether it is selected. isselected returns true if the specified column is selected completely and false otherwise. return value e_invalidarg if bad [in] passed, [out] value is false. s_ok. isrowselected() returns a boolean value indicating whether the specified row is completely selected. [propget] hresult isrowselected( [in] long row, [out] boolean isselected ); parameters row 0 based i...
...ed returns true if the specified column is selected completely and false otherwise. return value e_invalidarg if bad [in] passed, [out] value is false. s_ok. isrowselected() returns a boolean value indicating whether the specified row is completely selected. [propget] hresult isrowselected( [in] long row, [out] boolean isselected ); parameters row 0 based index of the row for which to determine whether it is selected. isselected returns true if the specified row is selected completely and false otherwise. return value e_invalidarg if bad [in] passed, [out] value is false. s_ok. isselected() returns a boolean value indicating whether the specified cell is selected. [propget] hresult isselected( [in] long row, [in] long column, [out] boolean isselected ); parameters row 0 based ...
...eturns true if the specified row is selected completely and false otherwise. return value e_invalidarg if bad [in] passed, [out] value is false. s_ok. isselected() returns a boolean value indicating whether the specified cell is selected. [propget] hresult isselected( [in] long row, [in] long column, [out] boolean isselected ); parameters row 0 based index of the row for the cell to determine whether it is selected. column 0 based index of the column for the cell to determine whether it is selected. isselected returns true if the specified cell is selected and false otherwise. return value e_invalidarg if bad [in] passed, [out] value is false. s_ok. modelchange() returns the type and extents describing how a table changed. provided for use by the ia2_event_table_model_changed event ...
mozIAsyncHistory
acallback an object implementing the mozivisitedstatuscallback.isvisited() method. if there's no ...
...laceinfo, [optional] in mozivisitinfocallback acallback); methods getplacesinfo() starts an asynchronous request to determine whether or not a given uri has been visited; you must implement a callback to receive the result of the request. void getplacesinfo( in jsval aplaceidentifiers, in mozivisitinfocallback acallback ); parameters aplaceidentifiers the uri for which to determine the visited status. acallback an object implementing the mozivisitedstatuscallback.isvisited() method. if there's no information available for a given place, acallback is called with a stub place info object, containing just the provided data (guid or uri). ...
...lback ); parameters aplaceidentifiers the uri for which to determine the visited status. acallback an object implementing the mozivisitedstatuscallback.isvisited() method. if there's no information available for a given place, acallback is called with a stub place info object, containing just the provided data (guid or uri). isurivisited() starts an asynchronous request to determine whether or not a given uri has been visited; you must implement a callback to receive the result of the request. void isurivisited( in nsiuri auri, in mozivisitedstatuscallback acallback ); parameters auri the places for which to retrieve information, identified by either a single place guid, a single uri, or a js array of uris and/or guids. acallback an object implementing...
mozIStorageConnection
storage/public/mozistorageconnection.idlscriptable this interface represents a database connection attached to a specific file or an in-memory database. it is the primary interface for interacting with a database, including creating prepared statements, executing sql, and examining database errors. 1.0 68 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) for a general overview on how to use this interface, see storage. method overview void asyncclose([optional] in mozistoragecompletioncallback acallback); void begintransaction(); void begintransactionas(in print32 transactiontype); mozistoragestatement clone([optional] in boolean areadonly); ...
...istoragestatement. anumstatements the number of statements in astatements. acallback optional a mozistoragestatementcallback object to receive progress, error, and completion notifications. return value a mozistoragependingstatement object that can be used to cancel the statements' execution. executesimplesql() executes an sql expression that has no bound parameters. warning: performing synchronous io on the main thread can cause serious performance problems. as a result, this method of modifying the database is strongly discouraged! void executesimplesql( in autf8string asqlstatement ); parameters asqlstatement the sql statement to execute. indexexists() this method determines whether or not the given index exists. boolean indexexists( in autf8string ainde...
...r setprogresshandler( in print32 agranularity, in mozistorageprogresshandler ahandler ); parameters agranularity the number of sql virtual machine steps between progress handler callbacks. ahandler the mozistorageprogresshandler instance that is being registered. return value returns the previous registered handler, or null if none was previously registered. tableexists() determines if there exists a table with the given name. boolean tableexists( in autf8string atablename ); parameters atablename the sql table whose existence should be checked. return value returns true if the table exists, false otherwise. see also storage mozstorage introduction and how-to article mozistoragestatement create and execute sql statements on a sqlite database. mozistora...
nsIAccessibleRole
nts a row of cells within a table. also, see role_table. role_cell 29 represents a cell within a table. it is used for html:td, xul:tree cell and xul:listcell. also, see role_table. role_link 30 represents a link to something else. this object might look like text or a graphic, but it acts like a button. it is used for xul:label@class="text-link", html:a, html:area, xforms:trigger@appearance="minimal". role_helpballoon 31 displays a help topic in the form of a tooltip or help balloon. role_character 32 represents a cartoon-like graphic object, such as microsoft office assistant, which is displayed to provide help to users of an application. role_list 33 represents a list box, allowing the user to select one or more items. it is used for xul:listbox, html:select@size, role="list". se...
...f an operation in progress. it is used for xul:progressmeter, role="progressbar". role_dial 49 represents a dial or knob whose purpose is to allow a user to set a value. role_hotkeyfield 50 represents a hot-key field that allows the user to enter a combination or sequence of keystrokes. role_slider 51 represents a slider, which allows the user to adjust a setting in given increments between minimum and maximum values. it is used by xul:scale, role="slider", xforms:range. role_spinbutton 52 represents a spin box, which is a control that allows the user to increment or decrement the value displayed in a separate "buddy" control associated with the spin box. it is used for xul:spinbuttons. role_diagram 53 represents a graphical image used to diagram data. it is used for svg:svg. role...
...a specialized panel that presents two other panels at the same time. between the two panels is a divider the user can manipulate to make one panel larger and the other panel smaller. role_table_column_header 88 the header for a column of a table. role_table_row_header 89 the header for a row of a table. role_tear_off_menu_item 90 a menu item used to tear off and reattach its menu. role_terminal 91 represents an accessible terminal. role_text_container 92 collection of objects that constitute a logical text entity. role_toggle_button 93 a toggle button. a specialized push button that can be checked or unchecked, but does not provide a separate indicator for the current state. role_tree_table 94 representas a control that is capable of expanding and collapsing rows as well as show...
nsIContentPrefService
or accessing and manipulating preferences in ways that are caller-specific or for which there is not yet a generic method, although generic functionality useful to multiple callers should generally be added to this unfrozen interface. also useful for testing the database creation and migration code. read only. grouper nsicontenturigrouper the component that the service uses to determine the groups to which uris belong. by default, this is the "hostname grouper," which groups uris by full hostname (in otherwords, by site). read only. methods addobserver() adds an observer that monitors a preference for changes. void addobserver( in astring aname, in nsicontentprefobserver aobserver ); parameters aname the name of the preference to observe. you may specify nul...
...fsbyname() returns the values of all preferences with the specified name. nsipropertybag2 getprefsbyname( in astring aname ); parameters aname the name for which all values are to be returned. return value the result is an nsipropertybag2 containing the preferences and their values. exceptions thrown ns_error_illegal_value if aname is null or an empty string. haspref() determines whether or not a preference exists. note: prior to gecko 2.0, the site could only be specified by nsiuri. now a string can be used as well. boolean haspref( in nsivariant agroup, in astring aname ); parameters agroup the group for which to see if a preference exists; this may be specified as either a uri or as a string. in either case, the group consists of all sites matching t...
... agroup the group for which to see if a preference exists; this may be specified as either a uri or as a string. in either case, the group consists of all sites matching the hostname portion of the specified uri. specify null to check for the preference in the global preference space; those preferences apply to all sites. aname the name of the preference whose existence is to be determined. return value true if the preference exists; otherwise false. exceptions thrown ns_error_illegal_value if agroup is not a string, nsiuri, or null. or if aname is null or an empty string removegroupedprefs() remove all grouped prefs. useful for removing references to the sites the user has visited when the user clears their private data. void removegroupedprefs(); removeobserver() re...
nsIDOMChromeWindow
dom/interfaces/base/nsidomchromewindow.idlscriptable this interface is implemented on the window object in chrome. inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void beginwindowmove(in nsidomevent mousedownevent); void getattention(); void getattentionwithcyclecount(in long acyclecount); void maximize(); void minimize(); void notifydefaultbuttonloaded(in nsidomelement defaultbutton); void restore(); void setcursor(in domstring cursor); attributes attribute type description browserdomwindow nsibrowserdomwindow the related nsibrowserdomwindow instance which provides access to yet another layer of utility functions by chrome script. it will be null for domwindows not corresponding to browsers.
... functions by chrome script. it will be null for domwindows not corresponding to browsers. messagemanager nsichromeframemessagemanager read only. title domstring obsolete since gecko 1.9.1 windowstate unsigned short returns current window state, the value is one of state_* constants. read only. constants constant value description state_maximized 1 the window is maximized. state_minimized 2 the window is minimized. state_normal 3 the window is normal. state_fullscreen 4 the window is in full screen mode. methods beginwindowmove() on some operating systems, we must allow the window manager to handle window dragging. this method tells the window manager to start dragging the window. this method will fail unless called while the left mouse button is held down, callers m...
...es to animate the window per system conventions. void getattentionwithcyclecount( in long acyclecount ); parameters acyclecount the maximum number of times to animate the window per system conventions. if set to -1, cycles indefinitely until window is brought into the foreground. this behavior is same as getattention method. maximize() maximizes the window. void maximize(); parameters none. minimize() minimizes the window. void minimize(); parameters none. notifydefaultbuttonloaded() when a document has been loaded, the document can notify the default button of the document to the window by using this method. when this method is called on windows, gecko moves the mouse cursor to center of the button if the auto cursor snap setting is enabled on the system. however, when the window isn'...
nsIDragSession
widget/public/nsidragsession.idlscriptable provides support for interacting with an ongoing drag session during a drag and drop operation. inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void getdata( in nsitransferable atransferable, in unsigned long aitemindex ); boolean isdataflavorsupported( in string adataflavor ); attributes attribute type description candrop boolean set the current state of the drag, whether it can be dropped or not. usually the target "frame" sets this so the native system can render the correct feedback. datatransfer nsidomdatatransfer the data transfer object for the current drag operation. dragaction ...
...long get the number of items that were dropped. read only. onlychromedrop boolean indicates if the drop event should be dispatched only to chrome. this allows chrome to handle a drag that was refused by content. sourcedocument nsidomdocument the document where the drag was started, which will be null if the drag originated outside the application. useful for determining if a drop originated in the same document. read only. sourcenode nsidomnode the dom node that was originally dragged to start the session, which will be null if the drag originated outside the application. read only. targetsize nssize sets the current width and height of the drag target area. it will contain the current size of the frame that the drag is currently...
... targetsize nssize sets the current width and height of the drag target area. it will contain the current size of the frame that the drag is currently in. native code only! methods getdata() gets data from a drag and drop operation. can be called while the drag is in process or after the drop has completed. void getdata( in nsitransferable atransferable, in unsigned long aitemindex ); parameters atransferable the transferable for the data to be put into. aitemindex which of multiple drag items, zero-based. must be less than numdropitems. isdataflavorsupported() checks to see if any of the native data on the clipboard matches a given data flavor. if numdropitems is greater than one, there is no indication as to which of the items matches the data flavor. boole...
nsIDroppedLinkHandler
boolean candroplink( in nsidomdragevent aevent, in prbool aallowsamedocument ); parameters aevent a dragenter or dragover event. aallowsamedocument if false, drops are only allowed if the document of the source of the drag is different from the destination. this check includes any parent, sibling and child frames in the same content tree. if ...
...cument if false, drops are only allowed if the document of the source of the drag is different from the destination. this check includes any parent, sibling and child frames in the same content tree. if true, the source is not checked. return value true if the link being dragged can be dropped. exceptions thrown missing exception missing description droplink() given a drop event, determines the link being dragged. if a uri is returned the caller can, for instance, load it. if null is returned, there is no valid link to be dropped. astring droplink( in nsidomdragevent aevent, out astring aname, [optional] in boolean adisallowinherit ); parameters aevent a drop event. aname the link title if it exists, or an empty string otherwise. return value a uri, or null if th...
...xceptions thrown ns_error_dom_security_err error will be thrown and the event canceled if the receiving target should not load the uri for security reasons. this will occur if the source of the drag initiated a link for dragging that it itself cannot access. this prevents a source document from tricking the user into a dragging a chrome url for example. droplinks() given a drop event, determines the link being dragged. if non-empty links array is returned the caller can, for instance, load it. if empty links array is returned, there is no valid link to be dropped. void droplinks( in nsidomdragevent aevent, [optional] in boolean adisallowinherit, [optional] out unsigned long acount, [retval, array, size_is(acount)] out nsidroppedlinkitem alinks ); parameters aevent a drop...
nsIEffectiveTLDService
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) implemented by: @mozilla.org/network/effective-tld-service;1. ...
... 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) implemented by: @mozilla.org/network/effective-tld-service;1. ...
...rule. therefore, if you call getpublicsuffix("a.b.c.nonexistent"), you will get back "nonexistent" - this "tld" is not in the public suffix list, but the implicit "*" rule means that it is returned. this is the right answer for e.g. cookie setting and domain highlighting, but you should check whether it's the right answer for your application. it is not recommended to use this interface for determining whether a given string "is a domain name". 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. is "mail.intranet" actually a domain name? depends who you ask - for some people it is, others not. is "pretty.flowers" a domain name, according to getpublicsuffix()? depends on the age of the...
nsILocalFileMac
although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. init this object with an fsspec legacy method - leaving in place for now. void initwithfsspec( [const] in fsspecptr afilespec ); parameters afilespec the native file spec. ispackage() boolean ispackage(); parameters none. return value true if a directory is determined to be a package under mac os 9/x. launchwithdoc() launch the application that this file points to with a document. void launchwithdoc( in nsilocalfile adoctoload, in boolean alaunchinbackground ); parameters adoctoload must not be null. if no document, use nsilocalfile::launch. alaunchinbackground true if the application should not come to the front. opendocwithapp() open the document th...
...e::launch. alaunchinbackground true if the application should not come to the front. opendocwithapp() open the document that this file points to with the given application. void opendocwithapp( in nsilocalfile aapptoopenwith, in boolean alaunchinbackground ); parameters aapptoopenwith the application with which to open the document. if null, the creator code of the document is used to determine the application. alaunchinbackground true if the application should not come to the front. setfiletypeandcreatorfromextension() obsolete since gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) sets the file type and creator code from a file extension internet config is used to determine the mapping. void setfiletypeandcreatorfromextension( in string aextension...
...d creator code from a file extension internet config is used to determine the mapping. void setfiletypeandcreatorfromextension( in string aextension ); parameters aextension setfiletypeandcreatorfrommimetype() obsolete since gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) sets the file type and creator code from a mime type. internet config is used to determine the mapping. void setfiletypeandcreatorfrommimetype( in string amimetype ); parameters amimetype ...
nsILoginInfo
ring the username for the login. usernamefield astring the name attribute for the username input in a form. non-form logins should specify an empty string (""). methods clone() returns a clone of this login. nsilogininfo clone(); parameters none. return value an nsilogininfo containing a clone of the login on which this method was invoked. equals() tests to determine whether this login is exactly equal to another nsilogininfo object. boolean equals( in nsilogininfo alogininfo ); parameters alogininfo the login to which to compare for equality. return value true if the two logins are exactly equal or false if they're not. init() initializes a newly created nsilogininfo object. void init( in astring ahostname, in astring aformsubmiturl, in...
...ame field. aformsubmiturl the value to assign to the formsubmiturl field. ahttprealm the value to assign to the httprealm field. ausername the value to assign to the username field. apassword the value to assign to the password field. ausernamefield the value to assign to the usernamefield field. apasswordfield the value to assign to the passwordfield field. matches() tests to determine whether this login is loosely equivalent to another nsilogininfo object. the passwordfield and usernamefield values are ignored, and the password values may be optionally ignored. if one login's formsubmiturl is an empty string (but not null), it will be treated as a wildcard. a blank value indicates the login was stored before bug 360493 was fixed. boolean matches( in nsilogininfo alogininf...
...sword values may be optionally ignored. if one login's formsubmiturl is an empty string (but not null), it will be treated as a wildcard. a blank value indicates the login was stored before bug 360493 was fixed. boolean matches( in nsilogininfo alogininfo, in boolean ignorepassword ); parameters alogininfo the login to which to compare for equality. ignorepassword if true, do not examine the password value when matching. return value true if the two logins are equivilant or false if they're not. see also nsiloginmanager using nsiloginmanager ...
nsIMsgAccountManagerExtension
ce is used to add a new panel to thunderbird's account manager. an account manager extension is a xpcom compontent implementing this interface. the interface is basically a manifest and defines the properties of the new panel. a panel consists of a xul file with a page element as root element and the property file containing the localized name. note: the account manager relies on a very strong naming scheme to load and unload a panel. an account manager extension with a "name" attribute of "devmo" and the "chromepackagename" attribute set to "extension@example.org" means, that the account manager expects to find a xul file in "chrome://extension@example.org/content/am-devmo.xul" and a property file in "chrome://extension@example.org/locale/am-devmo.properties" containing a property named "pr...
... the category manager at start up. simply add a new entry with the contact id of the component to the "mailnews-accountmanager-extensions" category. //github.com/realityripple/uxp/blob/master/mailnews/base/public/nsimsgaccountmanager.idlscriptable please add a summary to this article. last changed in gecko ??? inherits from: nsisupports method overview boolean showpanel(in nsimsgincomingserver server); attributes attribute type description name acstring name of the account manager extension. it has to be unique and defines the file name of the property file and the xul page as well as the name of the localized string contained in the property file. this attribute is readonly! chromepackagename acstring chrome package, where the files for the new panel are located. this...
...calized string contained in the property file. this attribute is readonly! chromepackagename acstring chrome package, where the files for the new panel are located. this is usually guid of the id of the addons which adds the new panel. this attribute is readonly! methods showpanel() before displaying a panel in the account manager this method is triggered. boolean showpanel( in nsimsgincomingserver server ); parameters server the account for which the panel should be displayed. return value a true indicates, that the account manager can display the panel for the given account, while false prevents the panel to be loaded. see also nsimsgaccountmanager building an account manager extension ...
nsINavHistoryService
(in nsinavhistorybatchcallback acallback, in nsisupports aclosure); void importhistory(in nsifile file); astring getcharsetforuri(in nsiuri auri); astring setcharsetforuri(in nsiuri auri, in astring acharset); attributes attribute type description hashistoryentries boolean true if there is any history. this can be used in ui to determine whether the "clear history" button should be enabled or not. 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). this is pretty fast. historydisabled boolean true if history is disabled. currently, history is disabled if the browser.history_expire_days pref is "0". constants transition ...
...ly added to history, since the page isn't added until it actually starts loading. the typed flag affects the url bar autocomplete. this will cause the transition type of the next visit of the url to be marked as "typed." void markpageastyped( in nsiuri auri ); parameters auri the page that is to be marked as typed by the user. markpageasfollowedlink() designates the specified url as coming from a link explicitly followed by the user (for example by clicking on it). void markpageasfollowedlink( in nsiuri auri ); parameters auri the url that is to be marked as explicitly followed by the user. canadduri() this method checks if the given uri would be added to the history or not. many types of uris, such as "chrome:" uris, are not stored when adduri is called. this function...
...itly followed by the user (for example by clicking on it). void markpageasfollowedlink( in nsiuri auri ); parameters auri the url that is to be marked as explicitly followed by the user. canadduri() this method checks if the given uri would be added to the history or not. many types of uris, such as "chrome:" uris, are not stored when adduri is called. this function allows you to determine whether it will be or not. you don't have to worry about calling this, addpagetosession/adduri will always check before actually adding the page. this function is public because some components may want to check if this page would go in the history (that is for annotations). boolean canadduri( in nsiuri auri ); parameters auri the uri that needs to be added to the history system. ret...
nsIPrincipal
ad only. uri nsiuri the codebase uri to which this principal pertains. this is generally the document uri. read only. note: this wasn't accessible by scripts prior to gecko 2.0. constants principal capability constants these values indicate the capabilities of a principal. the order is significant; if an operation is performed on a set of capabilities, the minimum is computed. constant value description enable_denied 1 enable_unknown 2 enable_with_user_permission 3 enable_granted 4 methods native code only!canenablecapability short canenablecapability( in string capability ); parameters capability missing description return value missing description ex...
...this principal. principals are equal if they are the same object, they have the same origin, or they have the same certificate id. a principal always subsumes itself. note: prior to gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1), this was not available to scripts. the system principal subsumes itself and all other principals. a null principal (corresponding to an unknown, hence assumed minimally privileged, security context) is not equal to any other principal (including other null principals), and therefore does not subsume anything but itself. both codebase and certificate principals are subsumed by the system principal, but no codebase or certificate principal yet subsumes() any other codebase or certificate principal. this may change in a future release; note that nsiprincipal ...
...oth codebase and certificate principals are subsumed by the system principal, but no codebase or certificate principal yet subsumes() any other codebase or certificate principal. this may change in a future release; note that nsiprincipal is unfrozen, not slated to be frozen. xxxbz except see bug 147145! note: for the future: perhaps we should consider a certificate principal for a given uri subsuming a codebase principal for the same uri? not sure what the immediate benefit would be, but i think the setup could make some code (e.g. maybedowngradetocodebase) clearer. boolean subsumes( in nsiprincipal other ); parameters other missing description return value true if this principal subsumes the specified principal; otherwise false. ...
nsIResumableChannel
inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void asyncopenat(in nsistreamlistener listener, in nsisupports ctxt, in unsigned long startpos, in nsiresumableentityid entityid); obsolete since gecko 1.8 void resumeat(in unsigned long long startpos, in acstring entityid); attributes attribute type description entityid acstring the entity id for this uri. ...
...( in nsistreamlistener listener, in nsisupports ctxt, in unsigned long startpos, in nsiresumableentityid entityid ); parameters listener as for asyncopen. ctxt as for asyncopen. startpos the starting offset, in bytes, to use to download. entityid information about the file, to match before obtaining the file. pass an empty string to use anything. resumeat() prepare this channel for resuming. the request will not start until asyncopen or open is called. calling resumeat after open or asyncopen has been called has undefined behaviour. during onstartrequest, this channel will have a status of ns_error_not_resumable if the file cannot be resumed, for example because the server doesn't support this. this error may occur even if startpos is 0, so that the front end can warn the user. sim...
...no ondataavailable will be called, and onstoprequest will immediately follow with the same status code. void resumeat( in unsigned long long startpos, in acstring entityid ); parameters startpos the starting offset, in bytes, to use to download. entityid information about the file, to match before obtaining the file. pass an empty string to use anything. see also implementing download resuming ...
nsITraceableChannel
netwerk/base/public/nsitraceablechannel.idlscriptable this interface is used to allow intercepting of http traffic. it is implemented by nsihttpchannel. 1.0 66 introduced gecko 1.9.0.4 inherits from: nsisupports last changed in gecko 1.9.0.4 the typical way to use this interface is as follows: register for the "http-on-examine-response" notification to track all http responses; skip redirects (responsestatus = 3xx on nsihttpchannel), since otherwise you may end up with two listeners registered for a channel; qi the channel passed as the "subject" to your observer to nsitraceablechannel, and replace the default nsistreamlistener (that passes the data to the original requester - e.g. to xmlhttprequest or to the browser tab that made the request) with your own implementati...
...holds chunks as they come, onstoprequest we join these junks to get the full source this.responsebody; // we'll set this to the this.responsestatuscode; this.deferreddone = { promise: null, resolve: null, reject: null }; this.deferreddone.promise = new promise(function(resolve, reject) { this.resolve = resolve; this.reject = reject; }.bind(this.deferreddone)); object.free...
...y response done:', newlistener.responsebody); }, function(areason) { // promise was rejected, right now i didnt set up rejection, but i should listen to on abort or bade status code then reject maybe } ).catch( function(acatch) { console.error('something went wrong, a typo by dev probably:', acatch); } ); } }; services.obs.addobserver(httpresponseobserver, 'http-on-examine-response', false); // services.obs.removeobserver(httpresponseobserver, 'http-on-examine-response'); // call this when you dont want to listen anymore ...
nsITreeSelection
eeselection.idlscriptable this interface is used by the tree widget to get information about what is selected. ...
...s attribute type description count long the number of rows currently selected in this tree. read only. currentcolumn nsitreecolumn the current column. currentindex long the current item (the one with focus). note: this property indicates only the index of the row with tree cursor around it. this is not a reliable method of determining the selected row, as the selection may include multiple rows, or the focused row may not even be selected. 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. a view can use this to temporarily suppress the selection while manipulating all of the indices, ...
...ndex of the change. count number of rows changed. clearrange() clears the range. void clearrange( in long startindex, in long endindex ); parameters startindex index to clearing at. endindex index to stop clearing at. clearselection() clears the selection. void clearselection(); parameters none. getrangeat() returns two objects whose value properties represent the minimum and maximum indices of the given selection range. see the tree selection tutorial. void getrangeat( in long i, out long min, out long max ); parameters i index of range to get (0 <= i < getrangecount()) min index of first object in range. max index of last object in this range. for single selections, min == max. getrangecount() returns a count of ...
nsIURI
netwerk/base/public/nsiuri.idlscriptable this is an interface for an uniform resource identifier with internationalization support, offering attributes that allow setting and querying the basic components of a uri, and methods for performing basic operations on uris. inherits from: nsisupports last changed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) see the following rfcs for details: rfc3490: internationalizing domain names in applications (idna) rfc3986: uniform resource identifier (uri): generic syntax rfc3987: internationalized resource identifiers subclasses of nsiuri, such as nsiurl, impose further structure on the uri. to create an nsiuri object, you should use nsiioservice.newuri(), like this: function makeuri(aurl, aorigincharset, abaseuri) {...
... the charset of the document from which this uri originated. an empty value implies utf-8. if this value is something other than utf-8 then the uri components (for example spec, prepath, username, and so on) are all fully url-escaped. otherwise, the uri components may contain unescaped multibyte utf-8 characters. read only. password autf8string the optional password, assuming the prehost consists of "username:password". exceptions thrown ns_error_failure if password is not applicable to the uri scheme (e.g. about:blank) note: some characters may be escaped. path autf8string the path, typically including at least a leading '/' (but may also be empty, depending on the protocol). note: some characters may be esc...
...her than just the parsed string, the behavior of this information when setting the spec attribute is undefined. note: some characters may be escaped. specignoringref autf8string returns a string representation of the uri without the ref (part after the #) portion. note: some characters may be escaped. username autf8string the optional username, assuming the prehost consists of "username:password". exceptions thrown ns_error_failure if username is not applicable to the uri scheme (e.g. about:blank) note: some characters may be escaped. userpass autf8string the "username:password" (or username only if the value doesn't contain a ':'). exceptions thrown ns_error_failure if user...
nsIUTF8ConverterService
iptable please add a summary to this article. inherits from: nsisupports last changed in gecko 1.7 method overview autf8string convertstringtoutf8(in acstring astring, in string acharset, in boolean askipcheck); autf8string converturispectoutf8(in acstring aspec, in string acharset); methods convertstringtoutf8() ensure that astring is encoded in utf-8. ...
...set this to pr_true only if you suspect that astring can be mistaken for ascii / utf-8 but is actually not in ascii / utf-8 so that astring has to go through the conversion. skipping asciiness/utf8ness check. ...
...e decoder to substitute invalid input sequences by replacement characters. return value the converted string in utf-8. exceptions thrown ns_error_uconv_noconv when there is no decoder for acharset or error code of nsiunicodedecoder in case of conversion failure. converturispectoutf8() ensure that aspec (after url-unescaping it) is encoded in utf-8. if not, convert it to utf-8, assuming it's encoded in acharset, and return the result. make sure that all characters outside us-ascii in your input spec are url-escaped if your spec is not in utf-8 (before url-escaping) because the presence of non-ascii characters is blindly regarded as an indication that your input spec is in unescaped utf-8 and it will be returned without further processing. no valid spec going around in mozilla c...
XPCOM Interface Reference
ntrolelementnsidomxulselectcontrolelementnsidomxulselectcontrolitemelementnsidatasignatureverifiernsidebugnsidebug2nsidevicemotionnsidevicemotiondatansidevicemotionlistenernsidialogcreatornsidialogparamblocknsidictionarynsidirindexnsidirindexlistenernsidirindexparsernsidirectoryenumeratornsidirectoryiteratornsidirectoryservicensidirectoryserviceprovidernsidirectoryserviceprovider2nsidiskcachestreaminternalnsidispatchsupportnsidocshellnsidocumentloadernsidownloadnsidownloadhistorynsidownloadmanagernsidownloadmanageruinsidownloadobservernsidownloadprogresslistenernsidownloadernsidragdrophandlernsidragservicensidragsessionnsidroppedlinkhandlernsidroppedlinkitemnsidynamiccontainernsieditornsieditorboxobjectnsieditordocshellnsieditorimesupportnsieditorloggingnsieditormailsupportnsieditorobserverns...
...ssengernsimicrosummarynsimicrosummarygeneratornsimicrosummaryobservernsimicrosummaryservicensimicrosummarysetnsimimeconverternsimimeheadersnsimodulensimsgaccountnsimsgaccountmanagerextensionnsimsgcompfieldsnsimsgcustomcolumnhandlernsimsgdbhdrnsimsgdbviewnsimsgdbviewcommandupdaternsimsgdatabasensimsgfilternsimsgfiltercustomactionnsimsgfilterlistnsimsgfoldernsimsgheaderparsernsimsgidentitynsimsgincomingservernsimsgmessageservicensimsgprotocolinfonsimsgruleactionnsimsgsearchcustomtermnsimsgsearchnotifynsimsgsearchscopetermnsimsgsearchsessionnsimsgsearchtermnsimsgsearchvaluensimsgsendlaternsimsgthreadnsimsgwindownsimsgwindowcommandsnsimutablearraynsinavbookmarkobservernsinavbookmarksservicensinavhistorybatchcallbacknsinavhistorycontainerresultnodensinavhistoryfullvisitresultnodensinavhistoryobser...
...tputstreamcallbacknsiparentalcontrolsservicensiparserutilsnsipasswordnsipasswordmanagernsipermissionnsipermissionmanagernsipipensiplacesimportexportservicensiplacesviewnsipluginhostnsiprefbranch2nsipreflocalizedstringnsiprefservicensiprincipalnsiprinterenumeratornsiprintingpromptnsiprivatebrowsingservicensiprocessnsiprocess2nsiprocessscriptloadernsiprofilensiprofilelocknsiprofileunlockernsiprogramminglanguagensiprogresseventsinknsipromptnsipromptservicensipropertiesnsipropertynsipropertybagnsipropertybag2nsipropertyelementnsiprotocolhandlernsiprotocolproxycallbacknsiprotocolproxyfilternsiprotocolproxyservicensiproxyinfonsipushmessagensipushservicensipushsubscriptionnsiradiointerfacelayernsirandomgeneratornsirequestnsirequestobservernsiresumablechannelnsirunnablensishentrynsishistorynsishistor...
NS_CStringContainerInit2
datalength = pr_uint32_max, pruint32 aflags = 0 ); parameters acontainer [in] the nscstringcontainer instance to initialize. adata [in] an array of characters used to initialize the string object. this parameter may be null. adatalength [in] an optional parameter that specifies the length of the array pointed to by adata. pass pr_uint32_max to indicate that adata's length may be determined by scanning the string for a terminating null. if adata is null, then this parameter is ignored. aflags [in] a bit-field that modifies how the string object is initialized. if this value is zero, then the array referenced by adata (if any) will be copied. flag values are defined below. flag values the aflags parameter is a bit-wise combination of the following values: ns_cstring_contain...
...iner_init_adopt data passed into ns_cstringcontainerinit2 is not copied. instead, the string takes ownership over the data pointer. the caller must have allocated the data array using the xpcom memory allocator. this flag should not be combined with ns_cstring_container_init_depend. ns_cstring_container_init_substring data passed into ns_cstringcontainerinit2 is a substring that is not null-terminated. return values the ns_cstringcontainerinit function returns ns_ok if successful. otherwise, it returns an error code. remarks after a nscstringcontainer object has been initialized via ns_cstringcontainerinit2, it may be used as an ordinary nsacstring object. when the string object is no longer needed, it should be passed to ns_cstringcontainerfinish to free any extra memory that the st...
...s_cstringcontainerfinish to free any extra memory that the string object may have allocated. it is generally better to use one of the helper classes, such as nscstring, instead of coding directly to ns_cstringcontainerinit2 because those classes take care of cleaning up the string object when it goes out of scope. when ns_cstringcontainerinit2 is told to copy adata, the copy it creates is null-terminated. this is significant as it allows the programmer to be certain that ns_cstringgetdata will return a null-terminated character array. the ns_cstringcontainerinit function is equivalent to calling ns_cstringcontainerinit with adata=nsnull and aflags=0. history this function was finalized for mozilla 1.8. see bug 264274 for details. see also ns_cstringcontainerinit, ns_cstringcontainerfini...
Storage
corrupt a database sqlite is very good about maintaining database integrity, but there are a few things you can do that can lead to database corruption. you can find out more by reading sqlite's documentation on this. ...
...due to bug 626193, locked databases get unlocked when you call this. thread safety mozistorageservice and mozistorageconnection are thread safe. ...
...ay of sql values, such as a result row. mozistoragefunction create a new sqlite function. mozistorageaggregatefunction create a new sqlite aggregate function. mozistorageprogresshandler monitor progress during the execution of a statement. mozistoragestatementwrapper storage statement wrapper mozistorageservice storage service storage:performance how to get your database connection performing well. storage inspector extension makes it easy to view any sqlite database files in the current profile. sqlite syntax query language understood by sqlite sqlite database browser is a capable free tool available for many platforms. it can be handy for examining existing databases and testing sql statements. sqlite manager extension helps manage sqlite database files on your computer. ...
Getting Started Guide
kim this short section. if this is unfamiliar material, you're not ready for nscomptrs yet. a good place to learn about the basic rules and reasoning behind com is in essential com by don box. don box gets into more of the details, traps, and pitfalls of com in effective com. you should also have a reasonable knowledge of c++. probably the three most helpful books on this topic are the c++ programming language by bjarne stroustrup, effective c++, and more effective c++ by scott meyers. all xpcom objects are allocated on the heap. clients don't get to know much about the implementation of any such object. they reference it only through a pointer to an `interface', i.e., the static type of the pointer is a pointer to an abstract base class, the actual object pointed to is a class derived from ...
...e. as described above, and unless you tell it otherwise, an nscomptr addrefs when you assign in to it. it does nothing when you assign out of it. where should i use nscomptrs? you should use an nscomptr any place you use an interface pointer as an owning reference, i.e., where you call addref and release on it. you should use nscomptr as a member variable, where it will simplify setters, and eliminate constructors, destructors, and assignment operators. you should use nscomptr on the stack, where it makes calling queryinterface almost pleasant, and eliminates the complex logic that falls out of error handling. where shouldn't i use nscomptrs? don't use nscomptrs where you don't need an owning reference. see some com ownership guidelines. nscomptr is designed to be used with xpcom interfac...
... compare this to the most frequent leaks caused by returning a raw pointer you have already addrefed: // don't return raw pointers; that incites leaks... nsifoo* createfoo(); // returns an |addref|ed pointer // ... nscomptr<nsifoo> myfoo = createfoo(); // oops: leak; nscomptr<nsifoo> myfoo( dont_addref(createfoo()) ); // since |createfoo| already |addref|s its result, we must remind // our |nscomptr| not to. it's easy to forget. prevent it in advance // by not returning pointers as function results, or else by returning // an |already_addrefed<t>| as above. void f( nscomptr<t> ) don't pass an nscomptr by value this practice is wasteful, but not otherwise harmful. there is no need to addref parameters, as they are guaranteed to live as long as the fun...
xptcall FAQ
ting any xpcom interface. both of these facilities are required by xpconnect. these facilities are also used by xpcom/proxy. it may also be used by other subsystems in the future. the xptcall approach was chosen over an approach that would have required generating stub code for calling and implementing all interfaces. though the chosen approach requires some core platform specific code, it has minimal footprint and is extendable to work with any valid xpcom interface without requiring additional per platform compiled code to be distributed. what does xptcall really do? the core invoke function has the declaration: xptc_public_api(nsresult) xptc_invokebyindex(nsisupports* that, pruint32 methodindex, pruint32 paramcount, nsxptc...
... any valid xpcom interface without requiring additional per platform compiled code to be distributed. what does xptcall really do? the core invoke function has the declaration: xptc_public_api(nsresult) xptc_invokebyindex(nsisupports* that, pruint32 methodindex, pruint32 paramcount, nsxptcvariant* params); nsxptcvariant is a discriminated union of the types that can be passed as parameters to the target function (including void* to represent arbitrary pointer types). given the correct set of parameters, this function can call any method on any xpcom interface. xpconnect uses information from typelib files to reflect arbitrary xpcom interfaces into javascript and to make calls from javascript to xpcom using xptc_invokebyindex.
...the full vtbl full of methods for any given valid xpcom interface (including ancestor methods). there are a few ways to do this. we could run the compiler at runtime and dynamically build and load stubs. or, we could write a bunch of platform specific code to build interface specific vtbls and method stubs. the method i choose was to use a single large vtbl with a lot of small generic stubs. this minimizes the platform specific code as much as possible. again, you just can't write code in c to do all this. the varargs stuff goes part way, but is just not enough. if anyone has credible ideas about how to get the required functionality in a cross platform way and/or without resorting to assembly code i'd love to hear about it. is xptcall a platform requirement for mozilla? yes. mozilla will ...
Thunderbird Configuration Files
how to find your profile folder, which is where thunderbird saves all your settings on your hard drive. on windows vista/xp/2000, the path is usually %appdata%\thunderbird\profiles\xxxxxxxx.default\, where xxxxxxxx is a random string of 8 characters. just browse to c:\documents and settings\[user name]\application data\thunderbird\profiles\ on windows xp/2000 or c:\users\[user name]\appdata\roaming\thunderbird\profiles\ on windows vista, and the rest should be obvious. on windows 95/98/me, the path is usually c:\windows\application data\thunderbird\profiles\xxxxxxxx.default\ on linux, the path is usually ~/.thunderbird/xxxxxxxx.default/ on mac os x, the path is usually ~/library/thunderbird/profiles/xxxxxxxx.default/ %appdata% is a shorthand for the application data path on windows 20...
...sually ~/library/thunderbird/profiles/xxxxxxxx.default/ %appdata% is a shorthand for the application data path on windows 2000/xp/vista. to use it, click start > run... (use the search box on vista), enter %appdata% and press enter. you will be taken to the "real" folder, which is normally c:\documents and settings\[user name]\application data on windows xp/2000, c:\users\[user name]\appdata\roaming on windows vista. thunderbird is capable of handling more than one user and thus, more than one profile. the path examples above refers to the default profile that is automatically created when you start thunderbird for the first time. you can manage any number of profiles by using the profile manager. userchrome.css this file sets the display rules for various elements in the thunderbird use...
...ns for known file types option. now, go to your profile folder and select file > new > text document. the default name new text document.txt should be displayed. change the name to user.js (click yes on the file type warning that appears). linux users: use your own preferred method to create user.js in the profile folder. if you don't already have one, consider running the following code in a terminal. $ cd $profile # where $profile is your profile folder $ touch user.js # create the empty javascript file alternatively, open a files window (if you're on ubuntu. this will depend on which distribution you use), navigate to the profile folder, and right-click in some empty space on the right pane, then select new document > empty document. the default name untitled document should appear,...
ctypes.open
s.jsm"); var cr = components.classes['@mozilla.org/chrome/chrome-registry;1'].getservice(components.interfaces.nsichromeregistry); var chromeuri_mylib = services.io.newuri('chrome://youraddon/content/mysubfolder/mycfunctionsforunix.so', 'utf-8', null); var localfile_mylib = cr.convertchromeurl(chromeuri_mylib); var jarpath_mylib = localfile_mylib.spec; // "jar:file:///c:/users/vayeate/appdata/roaming/mozilla/firefox/profiles/aecgxse.unnamed%20profile%201/extensions/youraddon@jetpack.xpi!/mysubfolder/mycfunctionsforunix.so" var filepath_mylib = localfilemylib.path; // "file:///c:/users/vayeate/appdata/roaming/mozilla/firefox/profiles/aecgxse.unnamed%20profile%201/extensions/youraddon@jetpack.xpi!/mysubfolder/mycfunctionsforunix.so" if your add-on is a bootstrap add-on, then you don't need t...
... // if addon is unpacked, this will be the addon folder. ...
... var lib = ctypes.open(filepath_mylib); var add_with_c ...
Debugger.Object - Firefox Developer Tools
object, and place its own properties on a debugger.object instance to store metadata about particular debuggee objects. javascript code in different compartments can have different views of the same object. for example, in firefox, code in privileged compartments sees content dom element objects without redefinitions or extensions made to that object's properties by content code. (in firefox terminology, privileged code sees the element through an "xray wrapper".) to ensure that debugger code sees each object just as the debuggee would, each debugger.object instance presents its referent as it would be seen from a particular compartment. this "viewing compartment" is chosen to match the way the debugger came across the referent. as a consequence, a single debugger instance may actually have...
...ce is live, the referent remains live. this means that garbage collection has no visible effect on debugger.object instances. accessor properties of the debugger.object prototype a debugger.object instance inherits the following accessor properties from its prototype: proto the referent's prototype (as a new debugger.object instance), or null if it has no prototype. class a string naming the ecmascript [[class]] of the referent. callable true if the referent is a callable object (such as a function or a function proxy); false otherwise. name the name of the referent, if it is a named function. if the referent is an anonymous function, or not a function at all, this is undefined. this accessor returns whatever name appeared after the function keyword in the source c...
... defineproperty(name,attributes) define a property on the referent namedname, as described by the property descriptordescriptor. any value, get, and set properties ofattributes must be debuggee values. (this functi...
Memory - Firefox Developer Tools
then provides a number of views of the heap that can show you which objects account for memory usage and exactly where in your code you are allocating memory. ...
...deleting snapshots saving and loading snapshots recording call stacks analyzing snapshots the tree map view is new in firefox 48, and the dominators view is new in firefox 46. once you've taken a snapshot, there are three main views the memory tool provides: the tree map view shows memory usage as a treemap. the aggregate view shows memory usage as a table of allocated types. the dominators view shows the "retained size" of objects: that is, the size of objects plus the size of other objects that they keep alive through references. ...
...views the memory tool provides: the tree map view shows memory usage as a treemap. the aggregate view shows memory usage as a table of allocated types. the dominators view shows the "retained size" of objects: that is, the size of objects plus the size of other objects that they keep alive through references. if you've opted to record allocation stacks for the snapshot, the aggregate and dominators views can show you exactly where in your code allocations are happening. concepts dominators example pages examples used in the memory tool documentation. monster example dom allocation example ...
Responsive Design Mode - Firefox Developer Tools
ed: when this option is enabled, the page isreloaded whenever the user agent is changed. reloading on these changes can be helpful because certain page behaviors would otherwise not be applied. for example, many pages check for touch support on load and only add event handlers if it is supported, or only enable certain features on certain browsers. however, if you are not interested in examining such features (maybe you are just checking the overall layout at different sizes), these reloads can waste time and possibly result in the loss of productive work, so it is useful to be able to control these reloads. now when you change such settings for the first time, you are given a warning message that tells you these reloads are no longer automatic, and informed about how you can make th...
...etwork 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. in responsive design mode, you can instruct the browser to emulate, very approximately, the characteristics of various different types of networks. ...
...ent types of networks. the characteristics emulated are: download speed upload speed minimum latency the table below lists the numbers associated with each network type, but please do not rely on this feature for exact performance measurements; it's intended to give an approximate idea of the user experience in different conditions. ...
AnalyserNode - Web APIs
rpretation "speakers" inheritance this interface inherits from the following parent interfaces: <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/eventtarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a><polyline points="111,25 121,20 121,30 111,25" stroke="#d4dde4...
...e" alignment-baseline="middle">analysernode</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor analysernode() creates a new instance of an analysernode object. properties inherits properties from its parent, audionode. ...
...ies from its parent, audionode. analysernode.fftsize is an unsigned long value representing the size of the fft (fast fourier transform) to be used to determine the frequency domain. analysernode.frequencybincount read only is an unsigned long value half that of the fft size. this generally equates to the number of data values you will have to play with for the visualization. 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 conver...
Animation.startTime - Web APIs
ne when its target keyframeeffect is scheduled to begin playback. an animation’s start time is initially unresolved (meaning that it's null because it has no value). syntax var animationstartedwhen = animation.starttime; animation.starttime = newstarttime; value a floating-point number representing the current time in milliseconds, or null if no time is set. ...
...et. you can read this value to determine what the start time is currently set at, and you can change this value to make the animation start at a different time. examples in the running on web animations api example, the we can sync all new animated cats by giving them all the same starttime as the original running cat: var catrunning = document.getelementbyid ("withwaapi").animate(keyframes, timing); /* a function that makes new cats. */ function addcat(){ var newcat = document.createelement("div"); newcat.classlist.add("cat"); return newcat; } /* this is the function that adds a cat to the waapi column */ function animatenewcatwithwaapi() { // make a new cat var newcat = addcat(); // animate said cat with the waapi's "animate" function var newanimationplayer = newcat.anim...
...n that makes new cats. */ function addcat(){ var newcat = document.createelement("div"); newcat.classlist.add("cat"); return newcat; } /* this is the function that adds a cat to the waapi column */ function animatenewcatwithwaapi() { // make a new cat var newcat = addcat(); // animate said cat with the waapi's "animate" function var newanimationplayer = newcat.animate(keyframes, timing); // set the animation's start time to be the same as the original .cat#withwaapi newanimationplayer.starttime = catrunning.starttime; // add the cat to the pile. waapicats.appendchild(newcat); } reduced time precision to offer protection against timing attacks and fingerprinting, the precision of animation.starttime might get rounded depending on browser settings. in firefox, the ...
Attr - Web APIs
Web › API › Attr
bute()), but certain functions (e.g., element.getattributenode()) or means of iterating return attr types. ...
...()), but certain functions (e.g., element.getattributenode()) or means of iterating return attr types. ...
... an empty nodelist. firstchild obsolete since gecko 14 this property now always returns null. isid read only indicates whether the attribute is an "id attribute". an "id attribute" being an attribute which value is expected to be unique across a dom document. in html dom, "id" is the only id attribute, but xml documents could define others. whether or not an attribute is unique is often determined by a dtd or other schema description. lastchild obsolete since gecko 14 this property now always returns null. nextsibling this property now always returns null. nodename use attr.name instead. nodetype this property now always returns 2 (attribute_node). nodevalue use attr.value instead. ownerdocument you shouldn't have been using this in the first place, so you probably don't care...
CSSPrimitiveValue - Web APIs
an instance of this interface might be obtained from the getpropertycssvalue() method of the cssstyledeclaration interface. a cssprimitivevalue object only occurs in a context of a css property. ...
... the range 0-255, a color percentage value can be converted to a number (see also the rgbcolor interface). ...
... range 0-255, a color percentage value can be converted to a number (see also the rgbcolor interface). ...
CanvasRenderingContext2D - Web APIs
reference drawing rectangles there are three methods that immediately draw rectangles to the canvas. canvasrenderingcontext2d.clearrect() sets all pixels in the rectangle defined by starting point (x, y) and size (width, height) to transparent black, erasing any previously drawn content. canvasrenderingcontext2d.fillrect() draws a filled rectangle at (x, y) position whose size is determined by width and height. 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. drawing text the following methods draw text. see also the textmetrics object for text properties. canvasrenderingcontext2d.filltext() draws (fills) a given text at the given (x, y) position...
....arc() adds a circular arc to the current path. canvasrenderingcontext2d.arcto() adds an arc to the current path with the given control points and radius, connected to the previous point by a straight line. canvasrenderingcontext2d.ellipse() adds an elliptical arc to the current path. canvasrenderingcontext2d.rect() creates a path for a rectangle at position (x, y) with a size that is determined by width and height. drawing paths canvasrenderingcontext2d.fill() fills the current sub-paths with the current fill style. canvasrenderingcontext2d.stroke() strokes the current sub-paths with the current stroke style. canvasrenderingcontext2d.drawfocusifneeded() if a given element is focused, this method draws a focus ring around the current path. canvasrenderingcontext2d.scrollpath...
...ing stores, but removed from canvas specifications. canvasrenderingcontext2d.webkitputimagedatahd intended for hd backing stores, but removed from canvas specifications. gecko only prefixed apis canvasrenderingcontext2d.mozcurrenttransform sets or gets the current transformation matrix, see canvasrenderingcontext2d.currenttransform. canvasrenderingcontext2d.mozcurrenttransforminverse sets or gets the current inversed transformation matrix. canvasrenderingcontext2d.mozimagesmoothingenabled see canvasrenderingcontext2d.imagesmoothingenabled. canvasrenderingcontext2d.moztextstyle introduced in in gecko 1.9, deprecated in favor of the canvasrenderingcontext2d.font property. canvasrenderingcontext2d.mozdrawtext() this method was introduced in gecko 1.9 and i...
Manipulating video using canvas - Web APIs
"96"></canvas> <canvas id="c2" width="160" height="96"></canvas> </div> <script type="text/javascript" src="processor.js"></script> </body> </html> the key bits to take away from this are: this document establishes two canvas elements, with the ids c1 and c2. canvas c1 is used to display the current frame of the original video, while c2 is used to display the video after performing the chroma-keying effect; c2 is preloaded with the still image that will be used to replace the green background in the video. the javascript code is imported from a script named processor.js. the javascript code the javascript code in processor.js consists of three methods. initializing the chroma-key player the doload() method is called when the xhtml document initially loads. this meth...
...g effect on the current video frame. the last thing the callback does is call settimeout() to schedule itself to be called again as soon as possible. in the real world, you would probably schedule this to be done based on knowledge of the video's frame rate. manipulating the video frame data the computeframe() method, shown below, is responsible for actually fetching a frame of data and performing the chroma-keying effect. processor.computeframe = function computeframe() { this.ctx1.drawimage(this.video, 0, 0, this.width, this.height); let frame = this.ctx1.getimagedata(0, 0, this.width, this.height); let l = frame.data.length / 4; for (let i = 0; i < l; i++) { let r = frame.data[i * 4 + 0]; let g = frame.data[i * 4 + 1]; let b = frame.data[i * 4 + 2]...
...g the getimagedata() method on the first context. this provides raw 32-bit pixel image data we can then manipulate. line 4 computes the number of pixels in the image by dividing the total size of the frame's image data by four. the for loop that begins on line 6 scans through the frame's pixels, pulling out the red, green, and blue values for each pixel, and compares the values against predetermined numbers that are used to detect the green screen that will be replaced with the still background image imported from foo.png. every pixel in the frame's image data that is found that is within the parameters that are considered to be part of the green screen has its alpha value replaced with a zero, indicating that the pixel is entirely transparent. as a result, the final image has the entire...
DocumentFragment - Web APIs
the documentfragment interface represents a minimal document object that has no parent. it is used as a lightweight version of document that stores a segment of a document structure comprised of nodes just like a standard document. the key difference is due to the fact that the document fragment isn't part of the active document tree structure. changes made to the fragment don't affect the document (even on reflow) or incur any performance impact when changes are made. ...
...e fragment don't affect the document (even on reflow) or incur any performance impact when changes are made. ...
...agment don't affect the document (even on reflow) or incur any performance impact when changes are made. ...
How whitespace is handled by HTML, CSS, and in the DOM - Web APIs
our source code is full of these whitespace characters, and we only tend to get rid of it in a production build step to reduce code download sizes. html largely ignores whitespace? in the case of html, whitespace is largely ignored — whitespace in between words is treated as a single character, and whitespace at the start and end of elements and outside elements is ignored. ...
...ions the javascript code below defines several functions that make it easier to deal with whitespace in the dom: /** * throughout, whitespace is defined as one of the characters * "\t" tab \u0009 * "\n" lf \u000a * "\r" cr \u000d * " " spc \u0020 * * this does not use javascript's "\s" because that includes non-breaking * spaces (and also some other characters). */ /** * determine whether a node's text content is entirely whitespace. * * @param nod a node implementing the |characterdata| interface (i.e., * a |text|, |comment|, or |cdatasection| node * @return true if all of the text content of |nod| is whitespace, * otherwise false. */ function is_all_ws( nod ) { // use ecma-262 edition 3 string and regexp features return !(/[^\t\n\r...
...whitespace. * * @param nod a node implementing the |characterdata| interface (i.e., * a |text|, |comment|, or |cdatasection| node * @return true if all of the text content of |nod| is whitespace, * otherwise false. */ function is_all_ws( nod ) { // use ecma-262 edition 3 string and regexp features return !(/[^\t\n\r ]/.test(nod.textcontent)); } /** * determine if a node should be ignored by the iterator functions. * * @param nod an object implementing the dom1 |node| interface. * @return true if the node is: * 1) a |text| node that is all whitespace * 2) a |comment| node * and otherwise false. */ function is_ignorable( nod ) { return ( nod.nodetype == 8) || // a comment node ( (nod.node...
DoubleRange - Web APIs
if no match can be found that is within the given range, an error will occur. ...
...if no match can be found that is within the given range, an error will occur. ...
...if no match can be found that is within the given range, an error will occur. specifications specification status comment media capture and streamsthe definition of 'doublerange' in that specification. ...
Element.msZoomTo() - Web APIs
Web › API › Element › msZoomTo
loating-point. the scale factor (mscontentzoomfactor) to zoom to. if no value is specified, defaults to the current zoom level (no additional zoom occurs).this argument is ignored if the element is not zoomable. animate[in]: the type of animation to use. default: uses the default animation. none: no animation is used. ...
...lue is specified, defaults to the current zoom level (no additional zoom occurs).this argument is ignored if the element is not zoomable. animate[in]: the type of animation to use. default: uses the default animation. none: no animation is used. this method has no scrolling effect on non-scrollable elements and no zooming effect on non-zoomable elements (e.g., elements with "-ms-content-zooming: none"). ...
...ult: uses the default animation. none: no animation is used. this method has no scrolling effect on non-scrollable elements and no zooming effect on non-zoomable elements (e.g., elements with "-ms-content-zooming: none"). this method has no effect if called from a parent document to scroll or zoom content hosted in an iframe. return value this method does not return a value. ...
Using files from web applications - Web APIs
this: const inputelement = document.getelementbyid("input"); inputelement.addeventlistener("change", handlefiles, false); function handlefiles() { const filelist = this.files; /* now you can work with the file list */ } getting information about selected file(s) the filelist object provided by the dom lists all of the files selected by the user, each specified as a file object. you can determine how many files the user selected by checking the value of the file list's length attribute: const numfiles = filelist.length; individual file objects can be retrieved by simply accessing the list as an array: for (let i = 0, numfiles = filelist.length; i < numfiles; i++) { const file = filelist[i]; // ... } this loop iterates over all the files in the file list. there are three attribu...
... in the file list. there are three attributes provided by the file object that contain useful information about the file. name the file's name as a read-only string. this is just the file name, and does not include any path information. size the size of the file in bytes as a read-only 64-bit integer. type the mime type of the file as a read-only string or "" if the type couldn't be determined. example: showing file(s) size the following example shows a possible use of the size property: <!doctype html> <html> <head> <meta charset="utf-8"> <title>file(s) size</title> </head> <body> <form name="uploadform"> <div> <input id="uploadinput" type="file" name="myfiles" multiple> selected files: <span id="filenum">0</span>; total size: <span id="filesize">0</...
...or drop zone as discussed previously and have them call a function such as the handlefiles() function below. function handlefiles(files) { for (let i = 0; i < files.length; i++) { const file = files[i]; if (!file.type.startswith('image/')){ continue } const img = document.createelement("img"); img.classlist.add("obj"); img.file = file; preview.appendchild(img); // assuming that "preview" is the div output where the content will be displayed. const reader = new filereader(); reader.onload = (function(aimg) { return function(e) { aimg.src = e.target.result; }; })(img); reader.readasdataurl(file); } } here our loop handling the user-selected files looks at each file's type attribute to see if its mime type begins with the string "image/"). for each f...
Using the Gamepad API - Web APIs
amepadhandler(e, false); }, false); this previous example also demonstrates how the gamepad property can be held after the event has completed — a technique we will use for device state querying later. querying the gamepad object as you can see, the gamepad events discussed above include a gamepad property on the event object, which returns a gamepad object. we can use this in order to determine which gamepad (i.e., its id) had caused the event, since multiple gamepads might be connected at once. we can do much more with the gamepad object, including holding a reference to it and querying it to find out which buttons and axes are being pressed at any one time. doing so is often desirable for games or other interactive web pages that need to know the state of a gamepad now vs. the next t...
...id) had caused the event, since multiple gamepads might be connected at once. we can do much more with the gamepad object, including holding a reference to it and querying it to find out which buttons and axes are being pressed at any one time. doing so is often desirable for games or other interactive web pages that need to know the state of a gamepad now vs. the next time an event fires. 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. the navigator.getgamepads() method returns an array of all devices currently visible to the webpage, as gamepad objects (the first value is always null, so null will...
... an array representing the controls with axes present on the device (e.g. analog thumb sticks). each entry in the array is a floating point value in the range -1.0 - 1.0, representing the axis position from the lowest value (-1.0) to the highest value (1.0). timestamp: this returns a domhighrestimestamp representing the last time the data for this gamepad was updated, allowing developers to determine if the axes and button data have been updated from the hardware. the value must be relative to the navigationstart attribute of the performancetiming interface. values are monotonically increasing, meaning that they can be compared to determine the ordering of updates, as newer values will always be greater than or equal to older values. note that this property is not currently supported in fire...
HTMLElement - Web APIs
e elements directly implement this interface, while others implement it via an interface that inherits it. ...
...ements directly implement this interface, while others implement it via an interface that inherits it. ...
...ct representing the item value. htmlelement.lang is a domstring representing the language of an element's attributes, text, and element contents. htmlelement.nomodule is a boolean indicating whether an import script can be executed in user agents that support module scripts. htmlorforeignelement.nonce returns the cryptographic number used once that is used by content security policy to determine whether a given fetch will be allowed to proceed. htmlelement.offsetheight read only returns a double containing the height of an element, relative to the layout. htmlelement.offsetleft read only returns a double, the distance from this element's left border to its offsetparent's left border. htmlelement.offsetparent read only returns a element that is the element from which all offs...
HTMLImageElement - Web APIs
ement interface represents an html <img> element, providing the properties and methods used to manipulate image elements. ...
...t interface represents an html <img> element, providing the properties and methods used to manipulate image elements. ...
...-side image map. 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. the image must be contained within an <a> element; see the ismap page for details. htmlimageelement.loading a domstring providing a hint to the browser used to optimize loading the document by determining whether to load the image immediately (eager) or on an as-needed basis (lazy). htmlimageelement.naturalheight read only returns an integer value representing the intrinsic height of the image in css pixels, if it is available; else, it shows 0. this is the height the image would be if it were rendered at its natural full size. htmlimageelement.naturalwidth read only an integer value repr...
HTMLMeterElement - Web APIs
erface they also have available to them by inheritance) for manipulating the layout and presentation of <meter> elements. ...
...ce they also have available to them by inheritance) for manipulating the layout and presentation of <meter> elements. ...
... properties also inherits properties from its parent, htmlelement. htmlmeterelement.high a double representing the value of the high boundary, reflecting the high attribute. htmlmeterelement.low a double representing the value of the low boundary, reflecting the lowattribute. htmlmeterelement.max a double representing the maximum value, reflecting the max attribute. htmlmeterelement.min a double representing the minimum value, reflecting the min attribute. htmlmeterelement.optimum a double representing the optimum, reflecting the optimum attribute. htmlmeterelement.value a double representing the currrent value, reflecting the value attribute. htmlmeterelement.labelsread only a nodelist of <label> elements that are associated with the element. methods this interface d...
HTMLProgressElement - Web APIs
nterface it also has available to it by inheritance) for manipulating the layout and presentation of <progress> elements. ...
...face it also has available to it by inheritance) for manipulating the layout and presentation of <progress> elements. ...
...ies inherits properties from its parent, htmlelement. htmlprogresselement.max is a double value reflecting the content attribute of the same name, limited to numbers greater than zero. its default value is 1.0. htmlprogresselement.positionread only returns a double value returning the result of dividing the current value (value) by the maximum value (max); if the progress bar is an indeterminate progress bar, it returns -1. htmlprogresselement.value is a double value that reflects the current value; if the progress bar is an indeterminate progress bar, it returns 0. htmlprogresselement.labelsread only returns nodelist containing the list of <label> elements that are labels for this element. methods no specific method; inherits properties from its parent, htmlelement. specific...
HTMLSelectElement - Web APIs
lement. these elements also share all of the properties and methods of other html elements via the htmlelement interface. ...
...nt. these elements also share all of the properties and methods of other html elements via the htmlelement interface. ...
...message. use the empty string to indicate that the element does not have a custom validity error. 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 - Web APIs
multiple video sources in enough different formats that all the browsers you need to support are covered. ...
...iple video sources in enough different formats that all the browsers you need to support are covered. ...
...ackward. htmlvideoelement.mshorizontalmirror gets or sets whether a video element is flipped horizontally in the display. htmlvideoelement.msinsertvideoeffect() inserts the specified video effect into the media pipeline. htmlvideoelement.msislayoutoptimalforplayback read only indicates whether the video can be rendered more efficiently. htmlvideoelement.msisstereo3d read only determines whether the system considers the loaded video source to be stereo 3-d or not. value set to true indicates source is stereo 3d. htmlvideoelement.mszoom controls whether the video frame is trimmed to fit the video display. methods inherits methods from its parent, htmlmediaelement, and from its ancestor htmlelement. htmlvideoelement.getvideoplaybackquality() returns a videoplaybackqu...
HTML Drag and Drop API - Web APIs
dragleave ondragleave …a dragged item leaves a valid drop target. dragover ondragover …a dragged item is being dragged over a valid drop target, every few hundred milliseconds. dragstart ondragstart …the user starts dragging an item. (see starting a drag operation.) drop ondrop …an item is dropped on a valid drop target. (see performing a drop.) note: neither dragstart nor dragend events are fired when dragging a file into the browser from the os. interfaces the html drag and drop interfaces are dragevent, datatransfer, datatransferitem and datatransferitemlist. the dragevent interface has a constructor and one datatransfer property, which is a datatransfer object. datatransfer objects include the drag event's state,...
... for more information about handling the end...
...gover="dragover_handler(event)">drop zone</div> for more information, see: performing a drop drag end at the end of a drag operation, the dragend event fires at the source element — the element that was the target of the drag start. this event fires regardless of whether the drag completed or was canceled. the dragend event handler can check the value of the dropeffect property to determine if the drag operation succeeded or not. for more information about handling the end of a drag operation, see: finishing a drag interoperability as can be seen in the datatransferitem interface's browser compatibility table, drag-and-drop interoperability is relatively broad among desktop browsers (except the datatransferitem and datatransferitemlist interfaces have less support). this dat...
IDBDatabase - Web APIs
r transaction. thus, you cannot execute commands, access data, or open anything outside of a transaction. ...
...ansaction. thus, you cannot execute commands, access data, or open anything outside of a transaction. ...
... 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", "month", { unique: false }); objectstore.createindex("year", "year", { unique: false }); objectstore.createindex("notified", "notified", { unique: false }); note.innerhtml += '<li>object store created.</li>'; }; this next line opens up a transaction on the d...
IDBOpenDBRequest: upgradeneeded event - Web APIs
// open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenreq...
... // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgr...
...nrequest.onupgradeneeded = event => { const db = event.target.result; console.log(`upgrading to version ${db.version}`); // 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 }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; ...
IDBOpenDBRequest - Web APIs
eletedatabase), using specific event handler attributes. note: this feature is available in web workers. ...
...edatabase), using specific event handler attributes. note: this feature is available in web workers. ...
... var db = this.result; db.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; // 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 }); objectstore.createindex("day", "day", { unique: false }); objectstore.createindex("month", "month", { unique: false }); objectstore.createindex("year", "year", { unique: false }); objectstore.createindex("notified", "notified", { unique: false }); }; specifications specification status comment indexed database api 2.0the defin...
IDBRequest - Web APIs
t. when the state is still pending, any attempt to access the result or error raises an invalidstateerror exception. in plain words, all asynchronous methods return a request object. if the request has been completed successfully, the result is made available through the result property and an event indicating success is fired at the request (idbrequest.onsuccess). if an error occurs while performing the operation, the exception is made available through the result property and an error event is fired (idbrequest.onerror). the interface idbopendbrequest is derived from idbrequest. note: this feature is available in web workers. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow...
...he interface idbopendbrequest is derived from idbrequest. note: this feature is available in web workers. ...
...nterface idbopendbrequest is derived from idbrequest. note: this feature is available in web workers. ...
IDBTransaction - Web APIs
also use an idbtransaction object to abort transactions. note: this feature is available in web workers. ...
...o use an idbtransaction object to abort transactions. note: this feature is available in web workers. ...
... dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db // variable. ...
Browser storage limits and eviction criteria - Web APIs
there are a number of web technologies that store data of one kind or another on the client-side (i.e., on your local disk). the process by which the browser works out how much space to allocate to web data storage and what to delete when that limit is reached is not simple, and differs between browsers. this article describes how browsers determine what local content to purge and when in order to free up needed local storage space. note: the information below should be fairly accurate for most modern browsers, but browser specifics are called out where known. opera and chrome should behave the same in all cases. opera mini (still presto-based, server-side rendering) doesn't store any data on the client. what technologies use browser data storage? in firefox, the following technologies ...
......
... global limit. firefox.com has a separate maximum of 20%. the two limits react differently to limits being reached: the group limit is also called the "hard limit": it doesn't trigger origin eviction. the global limit is a "soft limit" since there's a chance that some space will be freed and the operation can continue. note: the group limit can't be more than the global limit, despite the minimum group limit mentioned above. if you had a really low memory situation where the global limit was, say, 8 mb, then the group limit would also be 8 mb. note: if the group limit is exceeded, or if origin eviction couldn't free enough space, the browser will throw a quotaexceedederror. note: in chrome the soft and hard storage quota limits has changed since m66. more information can be foun...
KeyframeEffectOptions - Web APIs
the keyframeeffectoptions dictionary, part of the web animations api, is used by element.animate(), keyframeeffectreadonly() and keyframeeffect() to describe timing properties for animation effects. these properties are all optional, although without setting a duration the animation will not play. simply put, these properties describe how the user agent should go about making the transition from keyframe to keyframe, and how to behave when the animation begins and ends. properties composite optional determines how values are combined between this animation and other, separate animations that do not specify their own specific composite operation. defaults to replace. add dictates an additive effect, where each successive iteration builds on the last. for instance with transform...
...ere each successive iteration builds on the last. for instance with transform, a translatex(-200px) would not override an earlier rotate(20deg) value but result in translatex(-200px) rotate(20deg). accumulate is similar but a little smarter: blur(2) and blur(5) become blur(7), not blur(2) blur(5). replace overwrites the previous value with the new one. iterationcomposite optional determines how values build from iteration to iteration in this animation. can be set to accumulate or replace (see above). defaults to replace. pseudoelement optional the selector of the pseudo-element to be targeted, if any. defaults to null. delay optional the number of milliseconds to delay the start of the animation. defaults to 0. direction optional whether the animation runs forwards (nor...
...tion optional whether the animation runs forwards (normal), backwards (reverse), switches direction after each iteration (alternate), or runs backwards and switches direction after each iteration (alternate-reverse). defaults to "normal". duration optional the number of milliseconds each iteration of the animation takes to complete. defaults to 0. although this is technically optional, keep in mind that your animation will not run if this value is 0. easing optional the rate of the animation's change over time. accepts the pre-defined values "linear", "ease", "ease-in", "ease-out", and "ease-in-out", or a custom "cubic-bezier" value like "cubic-bezier(0.42, 0, 0.58, 1)". defaults to "linear". enddelay optional the number of milliseconds to delay after the end of an animation. this is p...
MediaDevices.getUserMedia() - Web APIs
uest the camera and microphone capabilities it needs and wants, using additional constraints. the following expresses a preference for 1280x720 camera resolution: { audio: true, video: { width: 1280, height: 720 } } the browser will try to honour this, but may return other resolutions if an exact match is not available, or the user overrides it. to require a capability, use the keywords min, max, or exact (a.k.a. min == max). the following demands a minimum resolution of 1280x720: { audio: true, video: { width: { min: 1280 }, height: { min: 720 } } } if no camera exists with this resolution or higher, then the returned promise will be rejected with overconstrainederror, and the user will not be prompted. the reason for the difference in behaviour is that the keyw...
..., or exact (a.k.a. min == max). the following demands a minimum resolution of 1280x720: { audio: true, video: { width: { min: 1280 }, height: { min: 720 } } } if no camera exists with this resolution or higher, then the returned promise will be rejected with overconstrainederror, and the user will not be prompted. the reason for the difference in behaviour is that the keywords min, max, and exact are inherently mandatory. whereas plain values and a keyword called ideal are not. ...
... } } if no camera exists with this resolution or higher, then the returned promise will be rejected with overconstrainederror, and the user will not be prompted. the reason for the difference in behaviour is that the keywords min, max, and exact are inherently mandatory. whereas plain values and a keyword called ideal are not. here's a full example: { audio: true, video: { width: { min: 1024, ideal: 1280, max: 1920 }, height: { min: 576, ideal: 720, max: 1080 } } } an ideal value, when used, has gravity, which means that the browser will try to find the setting (and camera, if you have more than one), with the smallest fitness distance from the ideal values given. plain values are inherently ideal, which means that the first of our resolution examples above could have...
MediaSession.setActionHandler() - Web APIs
media session actions. callback a function to call when the specified action type is invoked. the callback receives no input parameters, and should not return a value. return value undefined. description to remove a previously-established action handler, call setactionhandler() again, specifying null as the callback. the action handler receives as input a single parameter: an object conforming to the mediasessionactiondetails dictionary, which provides both the action type (so the same function can handle multiple action types), as well as data needed in order to perform the action. media session actions a media session action's type is specified using a string from the mediasessionaction enumerated type. values each of the actions is a common media session control request. implem...
... halts playback entirely. examples adding action handlers this example implements seek forward and backward actions for an audio player by setting up the seekforward and seekbackward action handlers. let skiptime = 10; // time to skip in seconds navigator.mediasession.setactionhandler('seekforward', evt => { // user clicked "seek forward" media notification icon. audio.currenttime = math.min(audio.currenttime + skiptime, audio.duration); }); navigator.mediasession.setactionhandler('seekbackward', evt => { // user clicked "seek backward" media notification icon. audio.currenttime = math.max(audio.currenttime - skiptime, 0); }); supporting multiple actions in one handler function you can also, if you prefer, use a single function to handle multiple action types, ...
... specifications specification status comment media session standardthe definition of 'media session ac...
MediaStream Recording API - Web APIs
ecordedchunks, { type: "video/webm" }); var url = url.createobjecturl(blob); var a = document.createelement("a"); document.body.appendchild(a); a.style = "display: none"; a.href = url; a.download = "test.webm"; a.click(); window.url.revokeobjecturl(url); } // demo: to download after 9sec settimeout(event => { console.log("stopping"); mediarecorder.stop(); }, 9000); examining and controlling the recorder status you can also use the properties of the mediarecorder object to determine the state of the recording process, and its pause() and resume() methods to pause and resume recording of the source media. if you need or want to check to see if a specific mime type is supported, that's possible as well. just call mediarecorder.istypesupported(). examining potentia...
...object to determine the state of the recording process, and its pause() and resume() methods to pause and resume recording of the source media. if you need or want to check to see if a specific mime type is supported, that's possible as well. just call mediarecorder.istypesupported(). examining potential input sources if your goal is to record camera and/or microphone input, you may wish to examine the available input devices before beginning the process of constructing the mediarecorder. to do so, you'll need to call navigator.mediadevices.enumeratedevices() to get a list of the available media devices. you can then examine that list and identify the potential input sources, and even filter the list based on desired criteria. ...
... examine the available input devices before beginning the process of constructing the mediarecorder. to do so, you'll need to call navigator.mediadevices.enumeratedevices() to get a list of the available media devices. you can then examine that list and identify the potential input sources, and even filter the list based on desired criteria. in this code snippet, enumeratedevices() is used to examine the available input devices, locate those which are audio input devices, and create <option> elements that are then added to a <select> element representing an input source picker. navigator.mediadevices.enumeratedevices() .then(function(devices) { devices.foreach(function(device) { let menu = document.getelementbyid("inputdevices"); if (device.kind == "audioinput") { let item =...
Using the Media Capabilities API - Web APIs
the media capabilities api provides several key features to help you better decide how to handle media, but also to determine how well media is being handled, in real time. these features include: the ability to query the browser to determine its ability to encode or decode media given a specified set of encoding parameters. these parameters may include the codecs, resolutions, bit rates, frame rates, and other such details. with the media capabilities api, you can determine not just if the browser can support a given format, but whether or not it can do so efficiently and smoothly. in short, this api replaces—and improves upon—the mediasource method istypesupported() or the htmlmediaelement method canplaytype(). more and more finely-detailed information about the display's propertie...
...ideo configuration. the configuration requires the type of media being tested — e.g. a plain file or mediasource — and a videoconfiguration including values for the contenttype, width, height, bitrate, and framerate: the contenttype must be a string specifying a valid video mime type. the width and height are the horizontal and vertical dimensions of the video; these are also used to determine the aspect ratio. the bitrate is the number of bits used to encode one second of video. the framerate is the number of frames which are played per second of time when playing the video. const videoconfiguration = { type: "file", video: { contenttype: "video/webm;codecs=vp8", width: 800, height: 600, bitrate: 10000, framerate: 15 } }; had we been queryi...
...g tested — either record (for recording media, i.e. a mediarecorder object) or transmission (for media transmitted over electronic means like rtcpeerconnection) — plus either an audio or video configuration as described above. querying the browser about decoding abilities now that we've created a video decoding configuration we can pass it as a paramater of the decodinginfo() method to determine if a video matching this configuration would be decodable and if the playback would be smooth and power efficient. var promise = navigator.mediacapabilities.decodinginfo(videoconfiguration); the decodinginfo() and encodinginfo() methods both return promises. once the promises state is fulfilled, you can access the mediacapabilitiesinfo interface's supported, smooth, and powerefficient properti...
msPlayToPreferredSourceUri - Web APIs
the preferred media source. this enables the playto target device to stream the media content, which can be drm protected, from a different location, such as a cloud media server. this proprietary property is specific to internet explorer and microsoft edge. ...
... a forward slash ("/") is appended to the uri string when it is sent over the network to a playto device. this is done to conform to uri standards. ...
...ntent on the playto target device from a different location, such as a cloud media server. this enables web pages and microsoft store apps to play digital rights management (drm) protected content. the app specifies a preferred uniform resource identifier (uri). this uri can point to a cloud based media server allowing streaming directly from the cloud, which can be drm protected, instead of streaming content from the windows machine which must be unprotected content. a forward slash ("/") is appended to the uri string when it is sent over the network to a playto device. this is done to conform to uri standards. example <video src="http://www.contoso.com/videos/video.mp4" msplaytopreferredsourceuri="http://www.contoso.com/catalogid=1234" /> var video = document.createelement('...
Using the Notifications API - Web APIs
y letting the user control which apps/sites are allowed to display notifications. because of abuses of push notifications in the past, web browsers and developers have begun to implement strategies to help mitigate this problem. you should only request consent to display notifications in response to a user gesture (e.g. clicking a button). this is not only best practice — you should not be spamming users with notifications they didn't agree to — but going forward browsers will explicitly disallow notification permission requests not triggered in response to a user gesture. firefox is already doing this from version 72, for example, and safari has done it for some time. in addition, in chrome and firefox you cannot request notifications at all unless the site is a secure context (i.e. ht...
...ain block inside this snippet. inside here we explicitly set the notification.permission value (some old versions of chrome failed to do this automatically), and show or hide the button depending on what the user chose in the permission dialog. we don't want to show it if permission has already been granted, but if the user chose to deny permission, we want to give them the chance to change their mind later on. note: before version 37, chrome doesn't let you call notification.requestpermission() in the load event handler (see issue 274284). feature-detecting the requestpermission() promise above we said that we had to check whether the browser supports the promise version of notification.requestpermission(). we did this using the following: function checknotificationpromise() { try ...
...events can be tracked using the onclick, onclose, onerror, and onshow handlers. because notification also inherits from eventtarget, it's possible to use the addeventlistener() method on it. replacing existing notifications it is usually undesirable for a user to receive a lot of notifications in a short space of time — for example, what if a messenger application notified a user for each incoming message, and they were being sent a lot? to avoid spamming the user with too many notifications, it's possible to modify the pending notifications queue, replacing single or multiple pending notifications with a new one. to do this, it's possible to add a tag to any new notification. if a notification already has the same tag and has not been displayed yet, the new notification replaces that pr...
OfflineAudioContext - Web APIs
he device hardware; instead, it generates it, as fast as it can, and outputs the result to an audiobuffer. ...
...evice hardware; instead, it generates it, as fast as it can, and outputs the result to an audiobuffer. ...
... constructor offlineaudiocontext.offlineaudiocontext() creates a new offlineaudiocontext instance. properties also inherits properties from its parent interface, baseaudiocontext. offlineaudiocontext.length read only an integer representing the size of the buffer in sample-frames. event handlers offlineaudiocontext.oncomplete is an eventhandler called when processing is terminated, that is when the complete event (of type offlineaudiocompletionevent) is raised, after the event-based version of offlineaudiocontext.startrendering() is used. methods also inherits methods from its parent interface, baseaudiocontext. offlineaudiocontext.suspend() schedules a suspension of the time progression in the audio context at the specified time and returns a promise. offlinea...
performance.measure() - Web APIs
ce interfaces: (getentries(), getentriesbyname() or getentriesbytype()). the measure's performance entry will have the following property values: entrytype - set to "measure". name - set to the "name" given when the measure was created. starttime - set to the start mark timestamp. duration - set to a domhighrestimestamp that is the duration of the measure (typically, the end mark timestamp minus the start mark timestamp). note: this feature is available in web workers. syntax performance.measure(name); performance.measure(name, startmark); performance.measure(name, startmark, endmark); performance.measure(name, undefined, endmark); arguments name a domstring representing the name of the measure. startmark optional a domstring representing the name of the measure's starting ...
...ature is available in web workers. syntax performance.measure(name); performance.measure(name, startmark); performance.measure(name, startmark, endmark); performance.measure(name, undefined, endmark); arguments name a domstring representing the name of the measure. startmark optional a domstring representing the name of the measure's starting mark. may also be the name of a performancetiming property. if it is omitted, then the start time will be the navigation start time. endmark optional a domstring representing the name of the measure's ending mark. may also be the name of a performancetiming property. if it is omitted, then the current time is used. return value void example the following example shows how measure() is used to create a new measure performance entry i...
... undefined, markernameb); performance.measure("measure from the start of navigation to now"); // pull out all of the measurements. console.log(performance.getentriesbytype("measure")); // finally, clean up the entries. performance.clearmarks(); performance.clearmeasures(); }, 1000); }, 1000); specifications specification status comment user timing level 2the definition of 'measure()' in that specification. working draft clarifies measure() processing model. user timingthe definition of 'measure()' in that specification. recommendation basic definition. ...
PerformanceMark - Web APIs
ng performance.mark() to add a named domhighrestimestamp (the mark) to the browser's performance timeline. ...
...erformance.mark() to add a named domhighrestimestamp (the mark) to the browser's performance timeline. ...
...ceentry.entrytype returns "mark". performanceentry.name returns the name given to the mark when it was created via a call to performance.mark(). performanceentry.starttime returns the domhighrestimestamp when performance.mark() was called. performanceentry.duration returns "0". (a mark has no duration.) methods this interface has no methods. example see the example in using the user timing api. specifications specification status comment user timing level 2the definition of 'performancemark' in that specification. working draft user timingthe definition of 'performancemark' in that specification. recommendation basic definition. ...
PerformanceMeasure - Web APIs
to add a named domhighrestimestamp (the measure) between two marks to the browser's performance timeline. ...
...add a named domhighrestimestamp (the measure) between two marks to the browser's performance timeline. ...
...ry.entrytype returns "measure". performanceentry.name returns the name given to the measure when it was created via a call to performance.measure(). performanceentry.starttime returns a timestamp given to the measure when performance.measure() was called. performanceentry.duration returns a domhighrestimestamp that is the duration of the measure (typically, the measure's end mark timestamp minus its start mark timestamp). methods this interface has no methods. example see the example in using the user timing api. specifications specification status comment user timing level 2the definition of 'performancemeasure' in that specification. working draft user timingthe definition of 'performancemeasure' in that specification. recommendation...
Using the Performance API - Web APIs
face for these standards is the performance interface and its methods and properties are extended by different standards. this guide describes how to use the performance interfaces that are defined in the high-resolution time standard. other web performance guides (listed in the see also section) describe how to use additional methods and properties of the performance interface. high precision timing high precision timing is achieved by using the domhighrestimestamp type for time values. the unit is milliseconds and should be accurate to 5 µs (microseconds). however, if the browser is unable to provide a time value accurate to 5 microseconds (because of hardware or software constraints, for example), the browser can represent the value as a time in milliseconds accurate to a millisecond. ...
... do the task can be measured. function calculate_time() { var starttime; var endtime; starttime = performance.now(); do_task(); endtime = performance.now(); return (endtime - starttime); } serializing the performance object json serialization of the performance object is done via the tojson() method. in the following example, json serialization for the performance, performance.timing and performance.navigation objects is printed in the object element. function print_json() { var json; var o = document.getelementsbytagname("output")[0]; if (window.performance.tojson === undefined) { json = "window.performance.tojson() is not supported"; o.innerhtml += json + "<br>"; } else { var s; json = window.performance.tojson(); // print the performance obj...
...document.getelementsbytagname("output")[0]; if (window.performance.tojson === undefined) { json = "window.performance.tojson() is not supported"; o.innerhtml += json + "<br>"; } else { var s; json = window.performance.tojson(); // print the performance object s = json.stringify(json); o.innerhtml = "<p>performance = " + s + "</p>"; // print the performance.timing and performance.navigation objects var perf = json.parse(s); var timing = perf.timing; o.innerhtml += "<p>peformance.timing = " + json.stringify(timing) + "</p>"; var navigation = perf.navigation; o.innerhtml += "<p>peformance.navigation = " + json.stringify(navigation) + "</p>"; } } specifications the interfaces described in this document are defined in the high resol...
PointerEvent - Web APIs
e that generated the event, the amount of pressure that was applied on the contact surface, etc. a pointer is a hardware agnostic representation of input devices (such as a mouse, pen or contact point on a touch-enable surface). the pointer can target a specific coordinate (or set of coordinates) on the contact surface such as a screen. a pointer's hit test is the process a browser uses to determine the target element for a pointer event. typically, this is determined by considering the pointer's location and also the visual layout of elements in a document on screen media. constructors pointerevent() creates a synthetic—and untrusted—pointerevent. properties this interface inherits properties from mouseevent and event. pointerevent.pointerid read only a unique identifier f...
...r causing the event. pointerevent.width read only the width (magnitude on the x axis), in css pixels, of the contact geometry of the pointer. pointerevent.height read only the height (magnitude on the y axis), in css pixels, of the contact geometry of the pointer. pointerevent.pressure read only the normalized pressure of the pointer input in the range 0 to 1, where 0 and 1 represent the minimum and maximum pressure the hardware is capable of detecting, respectively. pointerevent.tangentialpressure read only the normalized tangential pressure of the pointer input (also known as barrel pressure or cylinder stress) in the range -1 to 1, where 0 is the neutral position of the control. pointerevent.tiltx read only the plane angle (in degrees, in the range of -90 to 90) between the ...
...interevent.getcoalescedevents() returns a sequence of all pointerevent instances that were coalesced into the dispatched pointermove event. pointerevent.getpredictedevents() returns a sequence of pointerevent instances that the browser predicts will follow the dispatched pointermove event's coalesced events. pointer event types the pointerevent interface has several event types. to determine which event fired, look at the event's type property. note: it's important to note that in many cases, both pointer and mouse events get sent (in order to let non-pointer-specific code still interact with the user). if you use pointer events, you should call event.preventdefault() to keep the mouse event from being sent as well. pointerover this event is fired when a pointing device is move...
ProgressEvent - Web APIs
lhttprequest, or the loading of the underlying resource of an <img>, <audio>, <video>, <style> or <link>). ...
...prequest, or the loading of the underlying resource of an <img>, <audio>, <video>, <style> or <link>). ...
...dy performed by the underlying process. the ratio of work done can be calculated with the property and progressevent.total. when downloading a resource using http, this only represent the part of the content itself, not headers and other overhead. progressevent.total read only is an unsigned long long representing the total amount of work that the underlying process is in the progress of performing. when downloading a resource using http, this only represent the content itself, not headers and other overhead. methods also inherits methods from its parent event. progressevent.initprogressevent() initializes a progressevent created using the deprecated document.createevent("progressevent") method. examples the following example adds a progressevent to a new xmlhttprequest and...
RTCIceTransportState - Web APIs
process is currently underway. values "new" the rtcicetransport is currently gathering local candidates, or is waiting for the remote device to begin to transmit the remote candidates, or both. in this state, checking of candidates to look for those which might be acceptable has not yet begun. "checking" at least one remote candidate has been received, and the rtcicetransport has begun examining pairings of remote and local candidates in order to attempt to identify viable pairs that could be used to establish a connection. keep in mind that gathering of local candidates may still be underway, and, similarly, the remote device also may still be gathering candidates of its own. "connected" a viable candidate pair has been found and selected, and the rtcicetransport has connected th...
...es. "completed" the transport has finished gathering local candidates and has received a notification from the remote peer that no more candidates will be sent. in addition, all candidate pairs have been considered and a pair has been selected for use. if consent checks fail on all successful candidate pairs, the transport state will change to "failed". "disconnected" the ice agent has determined that connectivity has been lost for this rtcicetransport. this is not a failure state (that's "failed"). a value of "disconnected" means that a transient issue has occurred that has broken the connection, but that should resolve itself automatically without your code having to take any action. see the disconnected state for additional details. "failed" the rtcicetransport has finished the gat...
...matically without your code having to take any action. see the disconnected state for additional details. "failed" the rtcicetransport has finished the gathering process, has received the "no more candidates" notification from the remote peer, and has finished checking pairs of candidates, without successfully finding a pair that is both valid and for which consent can be obtained. this is a terminal state, indicating that the connection cannot be achieved or maintained. "closed" the transport has shut down and is no longer responding to stun requests. usage notes if an ice restart occurs, the candidate gathering and connectivity check process is started over again; this will cause a transition from the "connected" state if the restart occurred while the state was "completed". if the r...
RTCPeerConnection.setRemoteDescription() - Web APIs
offer or answer. the description specifies the properties of the remote end of the connection, including the media format. the method takes a single parameter—the session description—and it returns a promise which is fulfilled once the description has been changed, asynchronously. this is typically called after receiving an offer or answer from another peer over the signaling server. keep in mind that if setremotedescription() is called while a connection is already in place, it means renegotiation is underway (possibly to adapt to changing network conditions). because descriptions will be exchanged until the two peers agree on a configuration, the description submitted by calling setremotedescription() does not immediately take effect. instead, the current connection configuration rema...
... invalid. invalidstateerror the rtcpeerconnection is closed, or it's in a state which isn't compatible with the specified description's type. for example, if the type is rollback and the signaling state is one of stable, have-local-pranswer, or have-remote-pranswer, this exception is thrown, because you can't roll back a connection that's either fully established or is in the final stage of becoming connected. operationerror any errors that occur which don't match the others specifeid here are reported as operationerror. this includes identity validation errors. rtcerror an rtcerror with the errordetail set to sdp-syntax-error is reported if the sdp specified by rtcsessiondescription.sdp. the error object's sdplinenumber property indicates the line number within the sdp on which the syn...
...n session, with the newly-established offer as the starting point. upon starting the new negotiation with the newly-established offer, the local peer is now the callee, even if it was previously the caller. this happens instead of throwing an exception, thereby reducing the number of potential errors which might occur, and simplifies the processing you need to do when you receive an offer, by eliminating the need to handle the offer/answer process differently depending on whether the local peer is the caller or callee. note: earlier implementations of webrtc would throw an exception if an offer was set outside a stable or have-remote-offer state. deprecated syntax in older code and documentation, you may see a callback-based version of this function used. this has been deprecated and it...
RTCStatsReport - Web APIs
tatistics report contains a mapping of statistic category string names to objects containing the corresponding statistics data. calling getstats() on an rtcpeerconnection lets you specify whether you wish to obtain statistics for outbound, inbound, or all streams on the connection. the rtcrtpreceiver and rtcrtpsender versions of getstats() specifically only return statistics available to the incoming or outgoing stream on which you call them. the statistics objects for each category of statistic information, there is a dictionary whose properties provide the relevant information. properties common to all statistic categories all webrtc statistics objects are fundamentally based on the rtcstats dictionary, which provides the most fundamental information: the timestamp, the statistic type ...
...l, the type of relay being used, and so forth. remote-inbound-rtp the report is an rtcremoteinboundrtpstreamstats object providing statistics about your outbound rtp data stream, but from the perspective of the remote peer. that is, this information is about your outbound-rtp stream, but as seen by the remote device that's handling the stream. you can use this information to do things like determine how well the remote peer is receiving data. remote-outbound-rtp the report is an rtcremoteoutboundrtpstreamstats object that contains statistics about your inbound rtp (inbound-rtp) stream, but from the perspective of the remote peer. sender an object containing statistics about the rtcrtpsender for a stream on the rtcpeerconnection. if kind is "audio", this object is of type rtcaudiosenders...
...s, the type is rtcsendervideotrackattachmentstats. the data within provides statistics related to a particular mediastreamtrack's attachment to an rtcrtpsender; also included are the media level metrics that go along with the track. transport an object that contains statistics related to a transport for an rtcpeerconnection. the object is of type rtctransportstats. using rtcstatsreport ... coming soon-ish ... specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcstatsreport' in that specification. candidate recommendation initial specification. ...
SVGCircleElement - Web APIs
the svgcircleelement interface is an interface for the <circle> element. ...
... the svgcircleelement interface is an interface for the <circle> element. ...
... viewbox="0 0 250 250" width="250" height="250"> <circle cx="100" cy="100" r="50" fill="gold" id="circle" onclick="clickcircle();"/> </svg> javascript content this function clickcircle() is called when the circle is clicked. it randomly increases or decreases the radius of the circle element. function clickcircle() { var circle = document.getelementbyid("circle"); // randomly determine if the circle radius will increase or decrease var change = math.random() > 0.5 ? 10 : -10; // clamp the circle radius to a minimum of 10 and a maximum of 250, // so it won't disappear or get bigger than the viewport var newvalue = math.min(math.max(circle.r.baseval.value + change, 10), 250); circle.setattribute("r", newvalue); } click on the circle. specifications speci...
SVGFEColorMatrixElement - Web APIs
the svgfecolormatrixelement interface corresponds to the <fecolormatrix> element. ...
... the svgfecolormatrixelement interface corresponds to the <fecolormatrix> element. ...
...es. it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type. svg_fecolormatrix_type_matrix 1 corresponds to the matrix value. svg_fecolormatrix_type_saturate 2 corresponds to the saturate value. svg_fecolormatrix_type_huerotate 3 corresponds to huerotate value. svg_fecolormatrix_type_luminancetoalpha 4 corresponds to luminancetoalpha value. properties this interface also inherits properties from its parent interface, svgelement , and also implements properties of svgfilterprimitivestandardattributes. svgfecolormatrixelement.in1 read only an svganimatedstring corresponding to the in attribute of the given element. svgfecolormatrixelement.type read only an svgan...
SVGRect - Web APIs
Web › API › SVGRect
the svgrect represents a rectangle. rectangles consist of an x and y coordinate pair identifying a minimum x value, a minimum y value, and a width and height, which are constrained to be non-negative. an svgrect object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown. ...
...ed as read only, which means that attempts to modify the object will result in an exception being thrown. ...
...s read only, which means that attempts to modify the object will result in an exception being thrown. ...
Sensor APIs - Web APIs
ensor api does not tell you whether that api is connected to a real hardware sensor, whether that sensor works, if it's still connected, or even whether the user has granted access to it. making all this information consistently available is costly to performance and battery life. therefore, feature detection for sensor apis must include both detection of the apis themselves and defensive programming strategies (see below). the examples below show three methods for detecting sensor apis. additionally you can put object instantiation inside a try...catch block. notice that detection through the navigator interface is not one of the available options. if (typeof gyroscope === "function") { // run in circles... } if ("proximitysensor" in window) { // watch out! } if (window.ambientl...
...hree methods for detecting sensor apis. additionally you can put object instantiation inside a try...catch block. notice that detection through the navigator interface is not one of the available options. if (typeof gyroscope === "function") { // run in circles... } if ("proximitysensor" in window) { // watch out! } if (window.ambientlightsensor) { // go dark... } defensive programming as stated in feature detection, checking for a particular sensor api is insufficient for feature detection. the existence of an actual sensor must be confirmed as well. this is where defensive programming is needed. defensive programming requires three strategies. checking for thrown errors when instantiating a sensor object. listening for errors thrown during its use. handling the errors ...
...le.log(event.error.name, event.error.message); }) magsensor.start(); interfaces absoluteorientationsensorsecure context describes the device's physical orientation in relation to the earth's reference coordinate system. accelerometersecure context provides the acceleration applied to the device along all three axes. ambientlightsensorsecure context returns the current light level or illuminance of the ambient light around the hosting device. gyroscopesecure context provides the angular velocity of the device along all three axes. linearaccelerationsensorsecure context provides the acceleration applied to the device along all three axes, but without the contribution of gravity. magnetometersecure context provides information about the magnetic field as detected by the device’...
ServiceWorkerContainer - Web APIs
s an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations. most importantly, it exposes the serviceworkercontainer.register() method used to register service workers, and the serviceworkercontainer.controller property used to determine whether or not the current page is actively controlled. properties serviceworkercontainer.controller read only returns a serviceworker object if its state is activated (the same object returned by serviceworkerregistration.active). this property returns null during a force-refresh request (shift + refresh) or if there is no active worker. serviceworkercontainer.ready read only provid...
...ith the serviceworkerregistration. events controllerchange occurs when the document's associated serviceworkerregistration acquires a new active worker. also available via the serviceworkercontainer.oncontrollerchange property. error fired whenever an error occurs in the associated service workers. also available via the serviceworkercontainer.onerror property. message occurs when incoming messages are received by the serviceworkercontainer object (e.g. via a messageport.postmessage() call.) also available via the serviceworkercontainer.onmessage property. methods serviceworkercontainer.register() creates or updates a serviceworkerregistration for the given scripturl. serviceworkercontainer.getregistration() gets a serviceworkerregistration object whose scope matches the...
...xplicitly starts the flow of messages being dispatched from a service worker to pages under its control (e.g. sent via client.postmessage()). this can be used to react to sent messages earlier, even before that page's content has finished loading. examples the example below first checks to see if the browser supports service workers. if supported, the code registers the service worker and determines if the page is actively controlled by the service worker. if it isn't, it prompts the user to reload the page so the service worker can take control. the code also reports any registration failures. if ('serviceworker' in navigator) { // register a service worker hosted at the root of the // site using the default scope. navigator.serviceworker.register('/sw.js').then(function(registrati...
SpeechRecognition - Web APIs
speechrecognition.serviceuri specifies the location of the speech recognition service used by the current speechrecognition to handle the actual recognition. the default is the user agent's default speech service. methods speechrecognition also inherits methods from its parent interface, eventtarget. ...
...gnition. the default is the user agent's default speech service. methods speechrecognition also inherits methods from its parent interface, eventtarget. speechrecognition.abort() stops the speech recognition service from listening to incoming audio, and doesn't attempt to return a speechrecognitionresult. speechrecognition.start() starts the speech recognition service listening to incoming audio with intent to recognize grammars associated with the current speechrecognition. 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 int...
...nd property. speechstart fired when sound that is recognised by the speech recognition service as speech has been detected. also available via the onspeechstart property. speechend fired when speech recognised by the speech recognition service has stopped being detected. also available via the onspeechend property. start fired when the speech recognition service has begun listening to incoming audio with intent to recognize grammars associated with the current speechrecognition. also available via the onstart property. 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 u...
Storage API - Web APIs
yet; it's just an empty box waiting for content. this origin, however, has a lower quota than the other two do. it may be a less-visited site, or one known to have lower data storage requirements. origin 3's storage unit is completely full; it's reached its quota and can't store any more data without some existing material being removed. user agents are likely to use various techniques to determine the quota for various origins. one of the most likely methods—one which the specification specifically encourages, in fact—would be to consider the popularity and/or usage levels of individual sites to determine what their quotas should be. it's also conceivable that the browser might offer a user interface to customize these quotas. box modes the actual data storage within each site stor...
... a box is marked as "persistent", the contents won't be cleared by the user agent without either the data's origin itself or the user specifically doing so. this includes scenarios such as the user selecting a "clear caches" or "clear recent history" option. the user will be asked specifically for permission to remove persistent site storage units. quotas and usage estimates the user agent determines, using whatever mechanism it chooses, the maximum amount of storage a given site can use. this maximum is the origin's quota. the amount of this space which is in use by the site is called its usage. both of these values are estimates; there are several reasons why they're not precise: user agents are encouraged to obscure the exact size of the data used by a given origin, to prevent these v...
...igin, to prevent these values from being used for fingerprinting purposes. de-duplication, compression, and other methods to reduce the physical size of the stored data may be used. quotas are conservative estimates of the space available for the origin's use, and should be less than the available space on the device to help prevent overruns. user agents may use any method they choose to determine the size of origins' quotas, and are encouraged by the specification to provide popular or frequently-used sites with extra space. to determine the estimated quota and usage values for a given origin, use the navigator.storage.estimate() method, which returns a promise that, when resolved, receives a storageestimate that contains these figures. for example: navigator.storage.estimate().then(es...
Storage Access API - Web APIs
same-origin"> ... </iframe> the api is designed to limit the potential storage exceptions to origins for which the user has shown an intent to interact. this is enforced through the following constraints: access requests are automatically denied unless the embedded content is currently processing a user gesture such as a tap or click. this also prevents embedded content on the page from spamming the browser or user with excessive access requests. origins that have never been interacted with as a first party do not have a notion of first-party storage. from the user’s perspective, they only have a third-party relationship with that origin. access requests are automatically denied if the browser detects that the user hasn’t interacted with the embedded content in a first-party contex...
...t-party storage. from the user’s perspective, they only have a third-party relationship with that origin. access requests are automatically denied if the browser detects that the user hasn’t interacted with the embedded content in a first-party context recently (in firefox, "recently" is "within 30 days"). the browser may decide to involve the user in the decision of whether to grant an incoming storage access request. specifics regarding the lifetime of a storage grant and the circumstances under which the browser may decide to inform the user are currently being worked through and will be announced once ready. user prompts when requeststorageaccess() is called by an embedded, cross-origin document, the user agent may choose to involve the user in the decision of whether to grant sto...
...l, without needing to call requeststorageaccess() separately. if an embedded page from tracker.example has previously successfully obtained storage access on top-level origin foo.example, all embedded subresources from tracker.example on foo.example (e.g. scripts, images, stylesheets, etc.) will load with access to their first-party storage, which means they may send cookie headers and honor incoming set-cookie headers. in firefox, when the promise returned from requeststorageaccess() is resolved, the embedded page will gain access to its entire first-party storage, not just cookies. this includes access to apis such as web storage, indexeddb, dom cache, and so on. in firefox, the storage access grants are phased out after 30 calendar days passing, whereas in safari the storage access gra...
Using readable streams - Web APIs
r own custom readable streams in firefox 65+ and chrome 42+ (and equivalent chromium-based browsers). pipe chains are only supported in chrome at the moment, and that functionality is subject to change. finding some examples we will look at various examples in this article, taken from our dom-examples/streams repo. you can find the full source code there, as well as links to the examples. consuming a fetch as a stream the fetch api allows you to fetch resources across the network, providing a modern alternative to xhr. it has a number of advantages, and what is really nice about it is that browsers have recently added the ability to consume a fetch response as a readable stream. the body mixin now includes the body property, which is a simple getter exposing the body contents as a readab...
.... it has a number of advantages, and what is really nice about it is that browsers have recently added the ability to consume a fetch response as a readable stream. the body mixin now includes the body property, which is a simple getter exposing the body contents as a readable stream. this mixin is implemented by both the request and response interfaces, so it is available on both, although consuming the stream of a response body is perhaps a bit more obvious. as our simple stream pump example shows (see it live also), exposing it is a matter of just accessing the body property of the response: // fetch the original image fetch('./tortoise.png') // retrieve its body as readablestream .then(response => response.body) this provides us with a readablestream object. attaching a reader now w...
...sponse body is perhaps a bit more obvious. as our simple stream pump example shows (see it live also), exposing it is a matter of just accessing the body property of the response: // fetch the original image fetch('./tortoise.png') // retrieve its body as readablestream .then(response => response.body) this provides us with a readablestream object. attaching a reader now we’ve got our streaming body, reading the stream requires attaching a reader to it. this is done using the readablestream.getreader() method: // fetch the original image fetch('./tortoise.png') // retrieve its body as readablestream .then(response => response.body) .then(body => { const reader = body.getreader(); invoking this method creates a reader and locks it to the stream — no other reader may read this stre...
Streams API - Web APIs
this is something browsers do anyway when receiving assets to be shown on webpages — videos buffer and more is gradually available to play, and sometimes you'll see images display gradually as more is loaded. but this has never been available to javascript before. ...
...efaultreader represents a default reader that can be used to read stream data supplied from a network (e.g. a fetch request). readablestreamdefaultcontroller represents a controller allowing control of a readablestream's state and internal queue. default controllers are for streams that are not byte streams. writable streams writablestream provides a standard abstraction for writing streaming data to a destination, known as a sink. this object comes with built-in backpressure and queuing. writablestreamdefaultwriter represents a default writable stream writer that can be used to write chunks of data to a writable stream. writablestreamdefaultcontroller represents a controller allowing control of a writablestream's state. when constructing a writablestream, the underlying sink is ...
...the simple random stream example, showing how a stream can be teed and both resulting streams can be read independently. simple writer: this example shows how to to write to a writable stream, then decode the stream and write the contents to the ui. unpack chunks of a png: this example shows how pipethrough() can be used to transform a readablestream into a stream of other data types by transforming a data of a png file into a stream of png chunks. examples from other developers: progress indicators with streams, service workers, & fetch. specifications specification status comment streams living standard initial definition. ...
TextEncoder.prototype.encodeInto() - Web APIs
ing would have to be packed with some of the few characters that expant into 3 bytes. it is unlikely that long text will exceed s.length * 2 bytes in length. thus, a more optimistic approach might be to allocate s.length * 2 + 5 bytes, and perform reallocation in the rare circumstance that the optimistic prediction was wrong. if the output is expected to be long-lived, it makes sense to compute minimum allocation rounduptobucketsize(s.length), the maximum allocation size s.length * 3, and to have a chosen (as a tradeoff between memory usage and speed) threshold t such that if rounduptobucketsize(s.length) + t >= s.length * 3, you simply allocate for s.length * 3. otherwise, first allocate for rounduptobucketsize(s.length) and convert. if the read item it the return dictionary is s.length, t...
...ep multiply the remaining unconverted length by two instead of three. ...
... case, it makes sense not to implement the usual multiplying by two of the already written buffer length, because in such a case if a second reallocation happened, it would always overallocate compared to the original length times three.the above advice assumes that you don't need to allocate space for a zero terminator. that is, on the wasm side you are working with rust strings or a non-zero-terminating c++ class. if you are working with c++ std::string, even though the logical length is shown to you, you need to take the extra terminator byte into account when computing rounding up to allocator bucket size. see the next section about c strings. no zero-termination if the input string contains the character u+0000 in the input, encodeinto() will write a 0x00 byte in the output. encodeinto...
TouchEvent - Web APIs
and shape, amount of pressure, and target element. lists of touches are represented by touchlist objects. ...
... shape, amount of pressure, and target element. lists of touches are represented by touchlist objects. ...
...event's beginning. expressed as a floating-point multiple of the initial distance between the digits at the beginning of the event. values below 1.0 indicate an inward pinch (zoom out). values above 1.0 indicate an outward unpinch (zoom in). initial value: 1.0 touch event types there are several types of event that can be fired to indicate that touch-related changes have occurred. you can determine which of these has happened by looking at the event's touchevent.type property. touchstart sent when the user places a touch point on the touch surface. the event's target will be the element in which the touch occurred. touchend sent when the user removes a touch point from the surface (that is, when they lift a finger or stylus from the surface). this is also sent if the touch point moves ...
USBDevice - Web APIs
Web › API › USBDevice
ice.devicesubclass. usbdevice.devicesubclass read only one of three properties that identify usb devices for the purpose of loading a usb driver that will work with that device. the other two properties are usbdevice.deviceclass and usbdevice.deviceprotocol. usbdevice.deviceversionmajor read only the major version number of the device in a semantic versioning scheme. usbdevice.deviceversionminor read only the minor version number of the device in a semantic versioning scheme. usbdevice.deviceversionsubminor read only the patch version number of the device in a semantic versioning scheme. usbdevice.manufacturername read only the of the organization that manufactured the usb device. usbdevice.opened read only indicates whether a session has been started with a paired usb devic...
... identifies a usb device. usbdevice.productname read only the manufacturer-defined name that identifies a usb device. usbdevice.serialnumber read only the manufacturer-defined serial number for the specific usb device. usbdevice.usbversionmajor read only one of three properties that declare the usb protocol version supported by the device. the other two properties are usbdevice.usbversionminor and usbdevice.usbversionsubminor. usbdevice.usbversionminor read only one of three properties that declare the usb protocol version supported by the device. the other two properties are usbdevice.usbversionmajor and usbdevice.usbversionsubminor. usbdevice.usbversionsubminor read only one of three properties that declare the usb protocol version supported by the device. the other two prope...
...nor read only one of three properties that declare the usb protocol version supported by the device. the other two properties are usbdevice.usbversionmajor and usbdevice.usbversionsubminor. usbdevice.usbversionsubminor read only one of three properties that declare the usb protocol version supported by the device. the other two properties are usbdevice.usbversionmajor and usbdevice.usbversionminor. usbdevice.vendorid read only the official usg.org-assigned vendor id. methods usbdevice.claiminterface() returns a promise that resolves when the requested interface is claimed for exclusive access. usbdevice.clearhalt() returns a promise that resolves when a halt condition is cleared. usbdevice.controltransferin() returns a promise that resolves with a usbtransferinresult when a ...
WebGL2RenderingContext.getActiveUniforms() - Web APIs
pname a glenum specifying which information to query. possible values: gl.uniform_type: returns an array of glenum indicating the types of the uniforms. ...
... pname a glenum specifying which information to query. possible values: gl.uniform_type: returns an array of glenum indicating the types of the uniforms. ...
...between the elements. gl.uniform_matrix_stride: returns an array of glint indicating the strides between columns of a column-major matrix or a row-major matrix. gl.uniform_is_row_major: returns an array of glboolean indicating whether each of the uniforms is a row-major matrix or not. return value depends on which information is requested using the pname parameter. examples var uniformindices = gl.getuniformindices(program, ['ubored', 'ubogreen', 'uboblue']); var uniformoffsets = gl.getactiveuniforms(program, uniformindices, gl.uniform_offset); specifications specification status comment webgl 2.0the definition of 'getactiveuniforms' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'glgetac...
WebGLRenderingContext.blendEquation() - Web APIs
the webglrenderingcontext.blendequation() method of the webgl api is used to set both the rgb blend equation and alpha blend equation to a single equation. the blend equation determines how a new pixel is combined with a pixel already in the webglframebuffer. syntax void gl.blendequation(mode); parameters mode a glenum specifying how source and destination colors are combined. ...
...lend equation determines how a new pixel is combined with a pixel already in the webglframebuffer. syntax void gl.blendequation(mode); parameters mode a glenum specifying how source and destination colors are combined. 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. default value: gl.func_add exception if mode is not one of the three possib...
...d_enum error is thrown. return value none. examples to set the blend equation, use: gl.blendequation(gl.func_add); gl.blendequation(gl.func_subtract); gl.blendequation(gl.func_reverse_subtract); to get the blend equations, query the blend_equation, blend_equation_rgb and blend_equation_alpha constants which return gl.func_add, gl.func_subtract, gl.func_reverse_subtract, or if the ext_blend_minmax is enabled: ext.min_ext or ext.max_ext. gl.getparameter(gl.blend_equation_rgb) === gl.func_add; // true gl.getparameter(gl.blend_equation_alpha) === gl.func_add; // true specifications specification status comment webgl 1.0the definition of 'blendequation' in that specification. recommendation initial definition for webgl. opengl es 2.0the definition...
WebGLRenderingContext.texImage2D() - Web APIs
n the texture. ...
... format type channels bytes per pixel rgba unsigned_byte 4 4 rgb unsigned_byte 3 3 rgba unsigned_short_4_4_4_4 4 2 rgba unsigned_short_5_5_5_1 4 2 rgb unsigned_short_5_6_5 3 2 luminance_alpha unsigned_byte 2 2 luminance unsigned_byte 1 1 alpha unsigned_byte 1 1 other possible values in webgl2 for the versions of teximage2d that take an arraybufferview or a glintptr offset sized format base format r bits g bits b bits a bits shared bits color renderable texture filterable r8 ...
... for the versions of teximage2d that take a texture an htmlimageelement, htmlcanvaselement, htmlvideoelement, imagebitmap, or imagedata gl.alpha: discards the red, green and blue components and reads the alpha component. gl.rgb: discards the alpha components and reads the red, green and blue components. gl.rgba: red, green, blue and alpha components are read from the color buffer. gl.luminance: each color component is a luminance component, alpha is 1.0. gl.luminance_alpha: each component is a luminance/alpha component. 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 additi...
WebGLRenderingContext - Web APIs
stencil() specifies the stencil value used when clearing the stencil buffer. webglrenderingcontext.colormask() sets which color components to enable or to disable when drawing or rendering to a webglframebuffer. webglrenderingcontext.cullface() specifies whether or not front- and/or back-facing polygons can be culled. webglrenderingcontext.depthfunc() specifies a function that compares incoming pixel depth to the current depth buffer value. webglrenderingcontext.depthmask() sets whether writing into the depth buffer is enabled or disabled. webglrenderingcontext.depthrange() specifies the depth range mapping from normalized device coordinates to window or viewport coordinates. webglrenderingcontext.disable() disables specific webgl capabilities for this context. webglrenderingcon...
...ntext.deleteprogram() deletes a webglprogram. webglrenderingcontext.deleteshader() deletes a webglshader. webglrenderingcontext.detachshader() detaches a webglshader. webglrenderingcontext.getattachedshaders() returns a list of webglshader objects attached to a webglprogram. webglrenderingcontext.getprogramparameter() returns information about the program. webglrenderingcontext.getprograminfolog() returns the information log for a webglprogram object. webglrenderingcontext.getshaderparameter() returns information about the shader. webglrenderingcontext.getshaderprecisionformat() returns a webglshaderprecisionformat object describing the precision for the numeric format of the shader. webglrenderingcontext.getshaderinfolog() returns the information log for a webglshader object...
... done in other graphics {̣{glossary("api")}}, such as the canvas 2d rendering context. however, the properties and variables you can tweak are different for each api. effect of canvas size on rendering with webgl with scissor() and clear() we can demonstrate how the webgl drawing buffer is affected by the size of the canvas. the size of the first canvas is set to the styled element size, determined by css. this is done by assigning the width and height properties of the canvas to the values of the clientwidth and clientheight properties, respectively. in contrast, no such assignment is done for the second canvas. the internal width and height properties of the canvas remain at default values, which are different than the actual size of the canvas element in the browser window. the effec...
WebGLShaderPrecisionFormat - Web APIs
webglshaderprecisionformat.rangemax read only the base 2 log of the absolute value of the maximum value that can be represented. webglshaderprecisionformat.precision read only the number of bits of precision that can be represented. ...
... webglshaderprecisionformat.rangemax read only the base 2 log of the absolute value of the maximum value that can be represented. webglshaderprecisionformat.precision read only the number of bits of precision that can be represented. ...
...f bits of precision that can be represented. for integer formats this value is always 0. examples a webglshaderprecisionformat object is returned by the webglrenderingcontext.getshaderprecisionformat() method. var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.getshaderprecisionformat(gl.vertex_shader, gl.medium_float); // webglshaderprecisionformat { rangemin: 127, rangemax: 127, precision: 23 } specifications specification status comment webgl 1.0the definition of 'webglshaderprecisionformat' in that specification. recommendation initial definition. ...
A basic 2D WebGL animation example - Web APIs
ull; let glcanvas = null; // aspect ratio and coordinate system // details let aspectratio; let currentrotation = [0, 1]; let currentscale = [1.0, 1.0]; // vertex information let vertexarray; let vertexbuffer; let vertexnumcomponents; let vertexcount; // rendering data shared with the // scalers. ...
... then, for each shader in the specified list of shaders, we call a compileshader() function to compile it, passing into it the id and type of the shader function to build. each of those objects includes, as mentioned before, the id of the <script> element the shader code is found in...
... the id and type of the shader function to build. each of those objects includes, as mentioned before, the id of the <script> element the shader code is found in and the type of shader it is. the compiled shader is attached to the shader program by passing it into gl.attachshader(). we could go a step farther here, actually, and look at the value of the <script> element's type attribute to determine the shader type. once all of the shaders are compiled, the program is linked using gl.linkprogram(). if an error occurrs while linking the program, the error message is logged to console. finally, the compiled program is returned to the caller. compiling an individual shader the compileshader() function, below, is called by buildshaderprogram() to compile a single shader. function compile...
Matrix math for the web - Web APIs
this article explores how to create matrices and how to use them with css transforms and the matrix3d transform type. while this article uses css to simplify explanations, matrices are a core concept used by many different technologies including webgl, the webxr (vr and ar) api, and glsl shaders. this article is also available as an mdn content kit. the live examples use a collection of utility functions available under a global object named mdn. ...
...for the transform so that matrix is animated in making it easy to see what is being done. <div id='move-me' class='transformable'> <h2>move me with a matrix</h2> <p>lorem ipsum dolor sit amet, consectetur adipisicing elit...</p> </div> finally, for each of the examples we will generate a 4x4 matrix, then update the <div>'s style to have a transform applied to it, set to a matrix3d. bear in mind that even though the matrix is made up of 4 rows and 4 columns, it collapses into a single line of 16 values. matrices are always stored in one-dimensional lists in javascript. // create the matrix3d style property from a matrix array function matrixarraytocssmatrix(array) { return 'matrix3d(' + array.join(',') + ')'; } // grab the dom element let moveme = document.getelementbyid('move-me')...
...atrices is reversed and re-applied then the original points are returned. the order that matrices are multiplied in matters. when multiplying numbers, a * b = c, and b * a = c are both true. for example 3 * 4 = 12, and 4 * 3 = 12. in math these numbers would be described as commutative. matrices are not guaranteed to be the same if the order is switched, so matrices are non-commutative. another mind-bender is that matrix multiplication in webgl and css needs to happen in the reverse order that the operations intuitively happen. for instance, to scale something down by 80%, move it down 200 pixels, and then rotate about the origin 90 degrees would look something like the following in pseudo-code. transformation = rotate * translate * scale composing multiple transformations the functio...
Using shaders to apply color in WebGL - Web APIs
= ` varying lowp vec4 vcolor; void main(void) { gl_fragcolor = vcolor; } `; each fragment receives the interpolated color based on its position relative to the vertex positions instead of a fixed value. 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'), }, ... then, drawscene() can have the following added to it so it actually uses these colors when drawing the square: // tell webgl how to pull out the colors from the color buffer...
... added to it so it actually uses these colors when drawing the square: // tell webgl how to pull out the colors from the color buffer // into the vertexcolor attribute. ...
...te. ...
Using WebGL extensions - Web APIs
nces extensions may be supported by browser vendors before being officially ratified (but only when they are in draft stage). in that case, their name can be prefixed by the vendor prefix (moz_, webkit_, etc.) or the extension is only available once a browser preference has been toggled. if you wish to work with the bleeding edge of extensions, and want to keep working on upon ratification (assuming, of course, that the extension doesn't change in incompatible ways), that you query the canonical extension name as well as the vendor extension name. for instance: var ext = ( gl.getextension('oes_vertex_array_object') || gl.getextension('moz_oes_vertex_array_object') || gl.getextension('webkit_oes_vertex_array_object') ); note that, vendor prefix have been discouraged more and more an...
...y_object') || gl.getextension('webkit_oes_vertex_array_object') ); note that, vendor prefix have been discouraged more and more and thus most browser implement experimental extensions behind a feature flag rather than vendor prefix. the feature flags are: webgl.enable-draft-extensions in firefox chrome://flags/#enable-webgl-draft-extensions in chromium based browsers (chrome, opera). naming conventions webgl extensions are prefixed with "angle", "oes", "ext" or "webgl". these prefixes reflect origin and intent: angle_: extensions that are written by the angle library authors. oes_ and khr_: extensions that mirror functionality from opengl es (oes) or opengl api extensions approved by the respective architecture review boards (khronos). ovr_: extensions that optimize for virtu...
...avior has been significantly altered. querying available extensions the webgl context supports querying what extensions are available. var available_extensions = gl.getsupportedextensions(); the webglrenderingcontext.getsupportedextensions() method returns an array of strings, one for each supported extension. ...
Lifetime of a WebRTC session - Web APIs
e trying to mail a package to your friend michelle by labeling it “michelle” and dropping it in a mailbox when you don't know her address. you need to look up her address and include it on the package, or she'll wind up wondering why you forgot her birthday again. this is where signaling comes in. signaling signaling is the process of sending control information between two devices to determine the communication protocols, channels, media codecs and formats, and method of data transfer, as well as any required routing information. the most important thing to know about the signaling process for webrtc: it is not defined in the specification. why, you may wonder, is something fundamental to the process of establishing a webrtc connection left out of the specification? the answer is sim...
...er to exchange signaling information, you can choose to send json objects back and forth over a websocket connection, or you could use xmpp or sip over an appropriate channel, or you could use xmlhttprequest over https with polling, or any other combination of technologies you can come up with. you could even use email as the signaling channel. it’s also worth noting that the channel for performing signaling doesn’t even need to be over the network. one peer can output a data object that can be printed out, physically carried (on foot or by carrier pigeon) to another device, entered into that device, and a response then output by that device to be returned on foot, and so forth, until the webrtc peer connection is open. it'd be very high latency but it could be done. information exchang...
...the code on the signaling server. the exact contents and form of this identifier is up to you. each peer connects to an agreed-upon signaling server, such as a websocket server they both know how to exchange messages with. each peer tells the signaling server that they want to join the same webrtc session (identified by the token established in step 4). descriptions, candidates, etc. -- more coming up ice restart sometimes, during the lifetime of a webrtc session, network conditions change. one of the users might transition from a cellular to a wifi network, or the network might become congested, for example. when this happens, the ice agent may choose to perform ice restart. this is a process by which the network connection is renegotiated, exactly the same way the initial ice negotiat...
Using DTMF with WebRTC - Web APIs
des a guide for everyday developers about how to send dtmf over an rtcpeerconnection. the dtmf system is often referred to as "touch tone," after an old trade name for the system. webrtc doesn't send dtmf codes as audio data. instead, they're sent out-of-band, as rtp payloads. note, however, that although it's possible to send dtmf using webrtc, there is currently no way to detect or receive incoming dtmf. webrtc currently ignores these payloads; this is because webrtc's dtmf support is primarily intended for use with legacy telephone services that rely on dtmf tones to perform tasks such as: teleconferencing systems menu systems voicemail systems entry of credit card or other payment information passcode entry note: while the dtmf is not sent to the remote peer as audio, browsers ...
... <p>this example demonstrates the use of dtmf in webrtc. note that this example is "cheating" by generating both peers in one code stream, rather than having each be a truly separate entity.</p> <audio id="audio" autoplay controls></audio><br/> <button name="dial" id="dial">dial</button> <div class="log"></div> javascript let's take a look at the javascript code next. keep in mind that the process of establishing the connection is somewhat contrived here; you normally don't build both ends of the connection in the same document. global variables first, we establish global variables. let dialstring = "12024561111"; let callerpc = null; let receiverpc = null; let dtmfsender = null; let hasaddtrack = false; let mediaconstraints = { audio: true, video: false }; let...
... the connection process below. dtmfsender the rtcdtmfsender object for the connection. this will be obtained while setting up the connection, in the gotstream() function shown in adding the audio to the connection. hasaddtrack because some browsers have not yet implemented rtcpeerconnection.addtrack(), therefore requiring the use of the obsolete addstream() method, we use this boolean to determine whether or not the user agent supports addtrack(); if it doesn't, we'll fall back to addstream(). this gets figured out in connectanddial(), as shown in starting the connection process. mediaconstraints an object conforming to the mediaconstraints dictionary specifying the constraints to use when starting the connection. we want an audio-only connection, so video is false, while audio is true.
Writing WebSocket client applications - Web APIs
k the text input element, ready to receive the next line of text from the user. document.getelementbyid("text").value = ""; } receiving messages from the server websockets is an event-driven api; when messages are received, a message event is sent to the websocket object. to handle it, add an event listener for the message event, or use the onmessage event handler. to begin listening for incoming data, you can do something like this: examplesocket.onmessage = function (event) { console.log(event.data); } receiving and interpreting json objects let's consider the chat client application first alluded to in using json to transmit objects. there are assorted types of data packets the client might receive, such as: login handshake message text user list updates the code that int...
... something like this: examplesocket.onmessage = function (event) { console.log(event.data); } receiving and interpreting json objects let's consider the chat client application first alluded to in using json to transmit objects. ...
... var ul = ""; for (i=0; i < msg.users.length; i++) { ul += msg.users[i] + "<br>"; } document.getelementbyid("userlistbox").innerhtml = ul; break; } if (text.length) { f.write(text); document.getelementbyid("chatbox").contentwindow.scrollbypages(1); } }; here we use json.parse() to convert the json object back into the original object, then examine and act upon its contents. text data format text received over a websocket connection is in utf-8 format. closing the connection when you've finished using the websocket connection, call the websocket method close(): examplesocket.close(); it may be helpful to examine the socket's bufferedamount attribute before attempting to close the connection to determine if any data has yet to be tra...
WebXR performance guide - Web APIs
webxr applications involve multiple technologies which can be highly sensitive to performance constraints. as such, you may find yourself needing to make adjustments or compromises to optimize the performance of your webxr application to be as usable as possible on the broadest assortment of target devices. in this guide, we'll examine a variety of suggestions and recommendations that will help you make your webxr app as performant as possible. rendering tips ... talk about general stuff like limiting how many different loops there are during rendering, avoiding unnecessary drawing, etc. can probably also include stuff from https://github.com/immersive-web/webxr/blob/master/explainer.md#changing-the-field-of-view-for-inline-sessions managing rendering quality ... this section will c...
...ic kinds of data or use cases. while an individual vector or matrix doesn't occupy an inordinate amount of memory, the sheer number of vectors and matrices and other structures that are used to build each frame of a 3d scene means the memory management becomes a problem eventually if you keep allocating and de-allocating memory objects. consider the following function drawscene(gl, view, programinfo, buffers, texture, deltatime) { ... for (object in scene) { let vertexlist = ... let normalmatrix = mat4.create(); let modelviewmatrix = mat4.create(); let objectmatrix = mat4. // apply rotation updates to the object if needed mat4.rotate( } } this renders a scene. but it's inefficient, because it allocates as local variables a number of things, including at lea...
...t for every frame, the javascript runtime has to allocate memory for those and set them up—possibly triggering garbage collection—and then when each interaction of the loop is completed, the memory is released. a simple change can optimize this significantly: const vertexlist = ... const normalmatrix = mat4.create(); const modelviewmatrix = mat4.create(); function drawscene(gl, view, programinfo, buffers, texture, deltatime) { ... for (object in scene) { ... } } now, instead of allocating variables every loop iteration, we're using global constants(or class member constants). this has multiple benefits: the memory allocated for each value or structure will not need to be reallocated every frame. this reduces the potential for triggering garbage collection, and optimizes m...
Visualizations with Web Audio API - Web APIs
er's output to another node for it to work, as long as the input is connected to the source, either directly or via another node. 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. read those pages to get more information on how to use them. to capture data, you need to use the methods analysernode.getfloatfrequencydata() and analysernode.getbytefrequencydata() to capture f...
... var slicewidth = width * 1.0 / bufferlength; var x = 0; now we run through a loop, defining the position of a small segment of the wave for ea...
...hey would all fit on the canvas better.) the one value that needs explaining is the vertical offset position we are drawing each bar at: height-barheight/2. i am doing this because i want each bar to stick up from the bottom of the canvas, not down from the top, as it would if we set the vertical position to 0. therefore, we instead set the vertical position each time to the height of the canvas minus barheight/2, so therefore each bar will be drawn from partway down the canvas, down to the bottom. for(var i = 0; i < bufferlength; i++) { barheight = dataarray[i]/2; canvasctx.fillstyle = 'rgb(' + (barheight+100) + ',50,50)'; canvasctx.fillrect(x,height-barheight/2,barwidth,barheight); x += barwidth + 1; } }; again, at the end of the code we ...
Web Authentication API - Web APIs
. these include: verifying that the challenge is the same as the challenge that was sent ensuring that the origin was the origin expected validating that the signature over the clientdatahash and the attestation using the certificate chain for that specific model of the authenticator a complete list of validation steps can be found in the web authentication api specification. assuming that the checks pan out, the server will store the new public key associated with the user's account for future use -- that is, whenever the user desires to use the public key for authentication. authentication after a user has registered with web authentication, they can subsequently authenticate (a.k.a. - login or sign-in) with the service. the authentication flow looks similar to the regis...
...clientdatajson (only a hash is sent because the link to the authenticator may be a low-bandwidth nfc or bluetooth link and the authenticator is just going to sign over the hash to ensure that it isn't tampered with). authenticator creates an assertion - the authenticator finds a credential for this service that matches the relying party id and prompts a user to consent to the authentication. assuming both of those steps are successful, the authenticator will create a new assertion by signing over the clientdatahash and authenticatordata with the private key generated for this account during the registration call. authenticator returns data to browser - the authenticator returns the authenticatordata and assertion signature back to the browser. browser creates final data, application sends ...
...during the registration request to validate the signature by the authenticator. ensuring that the challenge that was signed by the authenticator matches the challenge that was generated by the server. checking that the relying party id is the one expected for this service. a full list of the steps for validating an assertion can be found in the web authentication api specification. assuming the validation is successful, the server will note that the user is now authenticated. this is outside the scope of the web authentication api specification, but one option would be to drop a new cookie for the user session. interfaces credential provides information about an entity as a prerequisite to a trust decision. credentialscontainer exposes methods to request credentials and n...
XRWebGLLayerInit.framebufferScaleFactor - Web APIs
for example, a value of 1.0 indicates that the frame buffer should be the same resolution as the actual display, while a value of 0.5 indicates that the frame buffer should be half the resolution of the display. ...
...n as the actual display, while a value of 0.5 indicates that the frame buffer should be half the resolution of the display. a value of 2.0, on the other hand, creates a frame buffer whose resolution is double that of the actual display buffer. there are valid use cases for all of these kinds of scaling. see managing rendering quality in webxr performance guide for more information. 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. syntax let layerinit = { framebufferscalefactor: scalefactor }; let gllayer = new xrwebgllayer(xrsession, gl, layerinit); let gllayer = new xrwebgllayer(xrsession, gl, { framebufferscalefactor: scalefactor }); value a fl...
...xrwebgllayer.getnativeframebufferscalefactor() static function. syntax let layerinit = { framebufferscalefactor: scalefactor }; let gllayer = new xrwebgllayer(xrsession, gl, layerinit); let gllayer = new xrwebgllayer(xrsession, gl, { framebufferscalefactor: scalefactor }); value a floating-point value indicating a multiplier to apply to the default frame buffer resolution in order to determine the resolution of the frame buffer for the xrwebgllayer. example in this example, a new xrwebgllayer is created for a webxr session, xrsession, with a frame buffer whose resolution is half that of the default display resolution of the xr device. xrsession.updaterenderstate({ baselayer: new xrwebgllayer(xrsession, gl, { framebufferscalefactor: 0.5 }); }); specifications sp...
Using the alert role - Accessibility
ing a new element. this allows the developer to reiterate information that has become more relevant or urgent to the user. for example, a form control may have instruction about the expected value. if a different value is entered, role="alert can be added to the instruction text so that the screen reader announces it as an alert. ...
...truction about the expected value. if a different value is entered, role="alert can be added to the instruction text so that the screen reader announces it as an alert. 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. this means that an existing alert can be "reused" multiple times. note: in most cases this approach is not recommended, because it's not id...
..., because it's not ideal to hide error or alert text that is currently not applicable. users of older assistive technology may still be able to perceive the alert text even when the alert does not currently applies, causing users to incorrectly believe that there is a problem. .hidden { display:none; } <p id="expirationwarning" role="alert" class="hidden">your log in session will expire in 2 minutes</p> // removing the 'hidden' class makes the element visible, which will make the screen reader announce the alert: document.getelementbyid("expirationwarning").classname = ""; working examples: alert role example using an aria alert box alert example using a modal aria dialog box notes using the alert role on an element implies that element has aria-live="assertive". the alert...
Using the aria-valuemax attribute - Accessibility
description the aria-valuemax attribute is used to define the maximum value allowed for a range widget such as a slider, spinbutton or progressbar. if the aria-valuenow has a known maximum and minimum, the author should provide properties for aria-valuemax and aria-valuemin. the value of aria-valuemax must be greater than or equal to the value of aria-valuemin. aria-valuemax is a required attribute of role slider, scrollbar and spinbutton. value string representation of a number possible effects on user agents and assistive technology if the aria-valuemax is indeterminate, or if aria-valuemin is not less than or equal to the value of aria-valuemax, this creates an error condition that will be handled by the assistive technology. note: opinions may differ on how assistive te...
...luemax, this creates an error condition that will be handled by the assistive technology. note: opinions may differ on how assistive technology should handle this technique. the information provided above is one of those opinions and therefore not normative. examples example 1: the snippet below shows a simple slider with a maximum value of 10. ...
...inions and therefore not normative. examples example 1: the snippet below shows a simple slider with a maximum value of 10. ...
ARIA: switch role - Accessibility
on</span> </button> <label for="speakerpower" class="switch">speaker power</label> description the aria switch role is identical to the checkbox role, except instead of being "checked" or "unchecked", it is either "on" and "off." like the checkbox role, the aria-checked attribute is required. the two possible values are true and false. unlike a <checkbox> or role="checkbox", there is no indeterminate or mixed state. the switch role does not support the value mixed for the aria-checked attribute; assigning a value of mixed to a switch instead sets the value to false. assistive technologies may choose to represent switch widgets with a specialized presentation to reflect the notion of an on/off switch. since a switch is an interactive control, it must be focusable and keyboard accessible. ...
...e varying opinions on how assistive technologies should handle this role; the above is a suggested practice and may differ from other sources. examples the following examples should help you understand how to apply and use the switch role. adding the switch role in aria this simple example just creates a widget and assigns the aria switch role to it. the button is styled with an appearance reminiscent of an on/off power switch. html the html is fairly simple here. the switch is implemented as a <button> element which is initially checked courtesy of its aria-checked attribute being set to "true". the switch has two child elements containing the "off" and "on" labels and is followed by a <label> identifying the switch. <button role="switch" aria-checked="true" id="speakerpower" c...
... button.switch { margin: 0; padding: 0; width: 70px; height: 26px; border: 2px solid black; display: inline-block; margin-right: 0.25em; line-height: 20px; vertical-align: middle; text-align: center; font: 12px "open sans", "arial", serif; } button.switch span { padding: 0 4px; pointer-events: none; } [role="switch"][aria-checked="fa...
Multipart labels: Using ARIA for labels with embedded fields inside them - Accessibility
problem you have a form where you ask your user a question, but the answer is mentioned in the question itself. a classic example we all know from our browser settings is the setting “delete history after x days”. “delete history after” is to the left of the textbox, x is the number, for example 21, and the word “days” follows the textbox, forming a sentence that is easy to understand. 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. isn’t that cool? you do not need to navigate around to find out the unit. “days” could easily be “months” or “years”, and in many ordina...
...are overridden by aria-labelledby. if on an html page you provide aria-labelledby, you should also provide a label for construct to also support older browsers that do not have aria support yet. with firefox 3, your blind users will automatically get better accessibility from the new attribute, but the users of older browsers are not left in the dark this way. ...
...with jaws 8, i have not found a way to make it to accept the label from the example above. ...
ARIA - Accessibility
rrect semantic html element over using aria, if such an element exists. for instance, native elements have built-in keyboard accessibility, roles and states. however, if you choose to use aria, you are responsible for mimicking (the equivalent) browser behaviour in script. 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. unfortunately, there isn't a more semantic tag available to developers in html 4, so we need to include aria roles and properties. these are specified by adding attributes to the element. in this example, the role="progressbar" attribute informs the browser that this element is actually a javascript-...
...gress bar is built using a <div>, which has no meaning. unfortunately, there isn't a more semantic tag available to developers in html 4, so we need to include aria roles and properties. these are specified by adding attributes to the element. in this example, the role="progressbar" attribute informs the browser that this element is actually a javascript-powered progress bar widget. the aria-valuemin and aria-valuemax attributes specify the minimum and maximum values for the progress bar, and the aria-valuenow describes the current state of it and therefore must be kept updated with javascript. 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. var pro...
...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. var progressbar = document.getelementbyid("percent-loaded"); // set its aria roles and states, // so that assistive technologies know what kind of widget it is. progressbar.setattribute("role", "progressbar"); progressbar.setattribute("aria-valuemin", 0); progressbar.setattribute("aria-valuemax", 100); // create a function that can be called at any time to update // the value of the progress bar. function updateprogress(percentcomplete) { progressbar.setattribute("aria-valuenow", percentcomplete); } note that aria was invented after html4, so does not validate in html4 or its xhtml variants. however, the accessibility gains it provides ...
Architecture - Accessibility
ded objects together in the container. nsiaccessibleeditabletext is supported if the area is potentially editable. if it's actually editable it will also provide state_editable. nsaccessible still represents any node in the tree. if the node is embedded in a parent that is an nsiaccessiblehypertext, the node will be exposed as an nsiaccessiblehyperlink. consumers can use this interface to determine the position of the object in the parent's text. nstextaccessible serves 2 purposes it is used by nshypertextaccessible to collect information about itself it is still exposed in msaa for backward compatibility by old windows assistive technologies. those at's don't yet know about any iaccessibletext yet, and want to see the hierarchy how they always did -- with text in leaf nodes. how doe...
...examples of objects not embedded in text are the child options in list boxes and combo boxes. otherwise, use iahyperlink::getstartindex() to find the index in parent. in firefox, the results of getendindex will always be the startindex + 1, because links are always just represented by a single embedded object ch...
... if the next character does not exist, proceed to the ne...
Keyboard-navigable JavaScript widgets - Accessibility
ative (i.e. tabindex="-1") yes no; author must focus the element with focus() in response to arrow or other key presses. zero (i.e. tabindex="0") yes in tab order relative to element's position in document (note that interactive elements like <a> have this behavior by default, they don't need the attribute). positive (e.g. tabindex="33") yes tabindex value determines where this element is positioned in the tab order: smaller values will position elements earlier in the tab order than larger values (for example, tabindex="7" will be positioned before tabindex="11"). non-native controls native html elements that are interactive, like <a>, <input> and <select>, are already accessible by keyboards, so to use one of them is the fastest path to make compo...
...a something like this.style.backgroundcolor = "gray"; or add a dotted border via this.style.border = "1px dotted invert". in the dotted border case you will need to make sure those elements have an invisible 1px border to start with, so that the element doesn't grow when the border style is applied (borders take up space, and ie doesn't implement css outlines). prevent used key events from performing browser functions if your widget handles a key event, prevent the browser from also handling it (for example, scrolling in response to the arrow keys) by using your event handler's return code. if your event handler returns false, the event will not be propagated beyond your handler. for example: <span tabindex="-1" onkeydown="return handlekeydown();"> if handlekeydown() returns false, the e...
...prevent the browser from also handling it (for example, scrolling in response to the arrow keys) by using your event handler's return code. if your event handler returns false, the event will not be propagated beyond your handler. for example: <span tabindex="-1" onkeydown="return handlekeydown();"> if handlekeydown() returns false, the event will be consumed, preventing the browser from performing any action based on the keystroke. don't rely on consistent behavior for key repeat, at this point unfortunately onkeydown may or may not repeat depending on what browser and os you're running on. ...
Color contrast - Accessibility
the color contrast between background and foreground content (that is, usually text) should be great enough to ensure legibility. when designing readable interfaces for different vision capabilities, the wcag guidelines recommend the following contrast ratios: type of content minimum ratio (aa rating) enhanced ratio (aaa rating) body text 4.5 : 1 7 : 1 large-scale text (120-150% larger than body text) 3 : 1 4.5 : 1 active user interface components and graphical objects such as icons and graphs 3 : 1 not defined these ratios do not apply to "incidental" text, such as inactive controls, logotypes, or purely decorative text. see the solution section below for further information. having good color contrast on your...
...elow). to check your contrast as you make your color choices, use a tool such as webaim's color contrast checker. 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. related wcag success criteria 1.4.3 minimum contrast (aa) the color contrast between background and foreground content should be at a minimum level to ensure legibility: text and its background should have a contrast ratio of at least 4.5:1. heading (or just larger) text should have a ratio of at least 3:1. larger text is defined as at least 18pt, or 14pt bold. 1.4.6 enhanced contrast (aaa) this follows, and builds on, cri...
...arger) text should have a ratio of at least 3:1. larger text is defined as at least 18pt, or 14pt bold. 1.4.6 enhanced contrast (aaa) this follows, and builds on, criterion 1.4.3. text and its background should have a contrast ratio of at least 7:1. heading (or just larger) text should have a ratio of at least 4.5:1. 1.4.11 non-text contrast (aa) (added in 2.1) there should be a minimum color contrast ratio of 3 to 1 for user interface components and graphical objects. ...
Understandable - Accessibility
ovide supplementary explainer material to help people who can't read it, or provide an alternative version that is written at lower secondary level. this doesn't mean that all subject matter should be understood by everyone, but that the style of writing should be accessible by everyone. it is better to just write all content at lower secondary level, even technical documentation like programming tutorials, unless there is a good reason not to (e.g. an alternative style for poetic effect), or they have to be written in a strict style (e.g. w3c specs). 3.1.6 pronunciation (aaa) a mechanism should be provided to give users access to pronounciation of words where they are is needed to understand the content fully. the html5 <audio> element can be used to create...
... option to stop it automatically advancing. better to avoid such functionality if possible. note: also see the wcag description for guideline 3.2 predictable: make web pages appear and operate in predictable ways. guideline 3.3 — input assistance: help users avoid and correct mistakes this guideline centers around helping users enter correct information when required with the minimum of mistakes. success criteria how to conform to the criteria practical resource 3.3.1 error identification (a) when a user is filling out a form or choosing between options, any error that is detected should be clearly reported to the user, along with the form control that the error relates to. it is advisable to implement client-side error detection ...
....4 error prevention (legal, financial, data) (aa) in the case of forms involved with entry of sensitive data (such as legal agreements, e-commerce transactions, or personal data), at least one of the following should be true: submissions are reversible. data is checked for errors, and the user is given an opportunity to correct them. a mechanism is available for confirming and correcting information before final submission. reversible — for any view where data can be entered, provide an equivalent view that allows you to edit or even delete an entry, as appropriate. checking data — as covered in 3.3.1, a combination of client-side and server-side validation should be used to detect errors and display helpful messages to the user to allow ...
:lang() - CSS: Cascading Style Sheets
Web › CSS › :lang
syntax formal syntax :lang( <language-code> ) parameter <language-code> a <string> representing the language you want to target. acceptable values are specified in the html spec. ...
... syntax formal syntax :lang( <language-code> ) parameter <language-code> a <string> representing the language you want to target. acceptable values are specified in the html spec. ...
... syntax formal syntax :lang( <language-code> ) parameter <language-code> a <string> representing the language you want to target. acceptable values are specified in the html spec. examples in this example, the :lang() pseudo-class is used to match the parents of quote elements (<q>) using child combinators. ...
-webkit-device-pixel-ratio - CSS: Cascading Style Sheets
bkit-device-pixel-ratio is a non-standard boolean css media feature which is an alternative to the standard resolution media feature. note: this media feature is a webkit feature. if possible, use the resolution media feature query instead. syntax the -webkit-device-pixel-ratio feature is specified as a <number> value. ...
... an alternative to the standard resolution media feature. note: this media feature is a webkit feature. if possible, use the resolution media feature query instead. syntax the -webkit-device-pixel-ratio feature is specified as a <number> value. it is a range feature, meaning that you can also use the prefixed -webkit-min-device-pixel-ratio and -webkit-max-device-pixel-ratio variants to query minimum and maximum values, respectively. values <number> the number of device pixels used to represent each css px. although the value is a <number>, and thus doesn't syntactically allow units, its implicit unit is dppx. implementation /* a unit of "dppx" is implied: */ @media (-webkit-min-device-pixel-ratio: 2) { ... } /* ... is equivalent to: */ @media (min-resolution: 2dppx) { ... } /* s...
...xel-ratio: 2) { ... } /* ... is equivalent to: */ @media (min-resolution: 2dppx) { ... } /* similarly: */ @media (-webkit-max-device-pixel-ratio: 2) { ... } /* ... is equivalent to: */ @media (max-resolution: 2dppx) { ... } examples html <p>this is a test of your device's pixel density.</p> css /* exact resolution */ @media (-webkit-device-pixel-ratio: 1) { p { color: red; } } /* minimum resolution */ @media (-webkit-min-device-pixel-ratio: 1.1) { p { font-size: 1.5em; } } /* maximum resolution */ @media (-webkit-max-device-pixel-ratio: 3) { p { background: yellow; } } result specifications specification status comment compatibility standardthe definition of '-webkit-device-pixel-ratio' in that specification. living standar...
color-index - CSS: Cascading Style Sheets
the color-index css media feature can be used to test the number of entries in the output device's color lookup table. syntax the color-index feature is specified as an <integer> value representing the number of entries in the output device's color lookup table. ...
...o test the number of entries in the output device's color lookup table. syntax the color-index feature is specified as an <integer> value representing the number of entries in the output device's color lookup table. (this value is zero if the device does not use such a table.) it is a range feature, meaning that you can also use the prefixed min-color-index and max-color-index variants to query minimum and maximum values, respectively. examples basic example html <p>this is a test.</p> css p { color: black; } @media (color-index) { p { color: red; } } @media (min-color-index: 15000) { p { color: #1475ef; } } result custom stylesheet this html will apply a special stylesheet for devices that have at least 256 colors. <link rel="stylesheet" href="http://foo.ba...
...ample html <p>this is a test.</p> css p { color: black; } @media (color-index) { p { color: red; } } @media (min-color-index: 15000) { p { color: #1475ef; } } result custom stylesheet this html will apply a special stylesheet for devices that have at least 256 colors. <link rel="stylesheet" href="http://foo.bar.com/base.css" /> <link rel="stylesheet" media="all and (min-color-index: 256)" href="http://foo.bar.com/color-stylesheet.css" /> specifications specification status comment media queries level 4the definition of 'color-index' in that specification. candidate recommendation the value can now be negative, in which case it computes to false. media queriesthe definition of 'color-index' in that specification. re...
@media - CSS: Cascading Style Sheets
Web › CSS › @media
e document if and only if the media query matches the device on which the content is being used. note: in javascript, the rules created using @media can be accessed with the cssmediarule css object model interface. syntax the @media at-rule may be placed at the top level of your code or nested inside any other conditional group at-rule. /* 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. description media types media types describe the general category of a device. except when using th...
...accessibility concerns to best accommodate people who adjust a site's text size, use ems when you need a <length> for your media queries. both em and px are valid units, but em works better if the user changes the browser text size. also consider using level 4 media queries to improve the user's experience. for example, prefers-reduced-motion to detect if the user has requested that the system minimize the amount of animation or motion it uses. security because media queries provide insights into the capabilities—and by extension, the features and design—of the device the user is working with, there is the potential that they could be abused to construct a "fingerprint" which identifies the device, or at least categorizes it to some degree of detail that may be undesirable to users. ...
...> '<' '='? <mf-name> '<' '='? <mf-value> | <mf-value> '>' '='? <mf-name> '>' '='? ...
Cross-browser Flexbox mixins - CSS: Cascading Style Sheets
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. this determines the direction in which flex items are laid out in. values: row (default) | row-reverse | column | column-reverse spec: https://drafts.csswg.org/css-flexbox/#flex-direction-property @mixin flex-direction($value: row) { @if $value == row-reverse { -webkit-box-direction: reverse; -webkit-box-orient: horizontal; -moz-box-direction: reverse; -moz-box-orient: horizontal; } ...
... values: nowrap (default) | wrap | wrap-reverse spec: https://drafts.csswg.org/css-flexbox/#flex-wrap-property @mixin flex-wrap($value: nowrap) { // no webkit/ff box fallback. -webkit-flex-wrap: $value; @if $value == nowrap { -ms-flex-wrap: none; } @else { -ms-flex-wrap: $value; } flex-wrap: $value; } flexbox flow ...
...spec: https://drafts.csswg.org/css-flexbox/#flex-basis-property @mixin flex-basis($value: auto) { -webkit-flex-basis: $value; flex-basis: $value; } flexbox "flex" (shorthand) the flex property specifies the components of a flexible length; flex-grow factor, flex-shrink factor, and the flex-basis. when an element is a flex item, flex is consulted instead of the main size property to determine the main size of the element. if an element is not a flex item, flex has no effect. values: see the flex reference for values and default spec: https://drafts.csswg.org/css-flexbox/#flex-property @mixin flex($fg: 1, $fs: 0, $fb: auto) { // set a variable to be used by box-flex properties $fg-boxflex: $fg; // box-flex only supports a flex-grow value so lets grab the // first item...
Box alignment in CSS Grid Layout - CSS: Cascading Style Sheets
this is in contrast to omitting align-items completely, in which case the height of each <div> stretches to fill its grid area. the align-items property sets the align-self property for all of the child grid items. this means that you can set the property individually, by using...
... align-items: start; } .item1 { grid-area: a; } .item2 { grid-area: b; } .item3 { grid-area: c; } .item4 { grid-area: d; } <div class="wrapper"> <div class="item1">item 1</div> <div class="item2">item 2</div> <div class="item3">item 3</div> <div class="item4">item 4</div> </div> keep in mind that once you set align-items: start, the height of each child <div> will be determined by the contents of the <div>. this is in contrast to omitting align-items completely, in which case the height of each <div> stretches to fill its grid area. the align-items property sets the align-self property for all of the child grid items. 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, ...
...er"> <div class="item1">item 1</div> </div> aligning the grid tracks on the block axis if you have a situation where your grid tracks use an area that is smaller than the grid container, then you can align the grid tracks themselves, inside that container. once again, this operates on the block and inline axes, with align-content aligning tracks on the block axis, and justify-content performing alignment on the inline axis. the place-content property is shorthand for align-content and justify-content. the values for align-content, justify-content and place-content are: normal start end center stretch space-around space-between space-evenly baseline first baseline last baseline in the below example i have a grid container of 500 pixels by 500 pixels. i have defined 3 row ...
CSS Grid Layout and Progressive Enhancement - CSS: Cascading Style Sheets
use css grid to overwrite older methods.</p> </li> <li class="card"><h2>six</h2> <p>we can use css grid to overwrite older methods.</p> </li> </ul> </div> the example demonstrates the typical problem that we have with floated layouts: if additional content is added to any one card, the layout breaks. as a concession for older browsers, i have set a min-height on the items, and hope that my content editors won’t add too much content and make a mess of the layout! i then enhance the layout using grid. i can turn my <ul> into a grid container with three column tracks. however, the width i have assigned to the list items themselves still applies, and it now makes those items a third of the width of the track: if i reset the width to auto, the...
...ything for grid supporting browsers here. */ } } feature queries have excellent browser support, and all of the browsers that support the updated grid specification support feature queries too. you can use them to deal with the issue we have with our enhanced: floated layout. i use an @supports rule to check for support of display: grid. i then do my grid code on the <ul>, set my width and min-height on the <li> to auto. i also remove the margins and negative margins, and replace the spacing with the grid-gap property. this means i don’t get a final margin on the last row of boxes. the layout now works, even if there is more content in one of the cards, than the others: * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-co...
... ul { overflow: hidden; margin: 0 -10px; padding: 0; list-style: none; } .wrapper li { float: left; width: calc(33.333333% - 20px); margin: 0 10px 20px 10px; } @supports (display: grid) { .wrapper ul { display: grid; grid-template-columns: repeat(3, 1fr); grid-gap: 20px; margin: 0; } .wrapper li { width: auto; min-height: auto; margin: 0; } } <div class="wrapper"> <ul> <li class="card"><h2>one</h2> <p>we can use css grid to overwrite older methods.</p> </li> <li class="card"><h2>two</h2> <p>we can use css grid to overwrite older methods.</p> <p>we can use css grid to overwrite older methods.</p> </li> <li class="c...
CSS Grid Layout - CSS: Cascading Style Sheets
out enables an author to align elements into columns and rows. however, many more layouts are either possible or easier with css grid than they were with tables. for example, a grid container's child elements could position themselves so they actually overlap and layer, similar to css positioned elements. basic example the example below shows a three-column track grid with new rows created at a minimum of 100 pixels and a maximum of auto. items have been placed onto the grid using line-based placement. * {box-sizing: border-box;} .wrapper { max-width: 940px; margin: 0 auto; } .wrapper > div { border: 2px solid rgb(233,171,88); border-radius: 5px; background-color: rgba(233,171,88,.5); padding: 1em; color: #d9480f; } html <div class="wrapper"> <div class="one">one</div>...
...round-color: rgba(233,171,88,.5); padding: 1em; color: #d9480f; } html <div class="wrapper"> <div class="one">one</div> <div class="two">two</div> <div class="three">three</div> <div class="four">four</div> <div class="five">five</div> <div class="six">six</div> </div> css .wrapper { display: grid; grid-template-columns: repeat(3, 1fr); grid-gap: 10px; grid-auto-rows: minmax(100px, auto); } .one { grid-column: 1 / 3; grid-row: 1; } .two { grid-column: 2 / 4; grid-row: 1 / 3; } .three { grid-column: 1; grid-row: 2 / 5; } .four { grid-column: 3; grid-row: 3; } .five { grid-column: 2; grid-row: 4; } .six { grid-column: 3; grid-row: 4; } reference css properties grid-template-columns grid-template-rows grid-template-areas grid-templ...
...rid-column: 2; grid-row: 4; } .six { grid-column: 3; grid-row: 4; } reference css properties grid-template-columns grid-template-rows grid-template-areas grid-template grid-auto-columns grid-auto-rows grid-auto-flow grid grid-row-start grid-column-start 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 alignme...
Microsoft CSS extensions - CSS: Cascading Style Sheets
microsoft applications such as edge and internet explorer support a number of special microsoft extensions to css. these extensions are prefixed with -ms-. microsoft-only properties (avoid using on websites) note: these properties will only work in microsoft applications, and are not on a standards track. ...
...special microsoft extensions to css. these extensions are prefixed with -ms-. microsoft-only properties (avoid using on websites) note: these properties will only work in microsoft applications, and are not on a standards track. ...
...e-limit-lines -ms-hyphenate-limit-zone -ms-ime-align -ms-overflow-style -ms-scrollbar-3dlight-color -ms-scrollbar-arrow-color -ms-scrollbar-base-color -ms-scrollbar-darkshadow-color -ms-scrollbar-face-color -ms-scrollbar-highlight-color -ms-scrollbar-shadow-color -ms-scrollbar-track-color -ms-scroll-chaining -ms-scroll-limit -ms-scroll-limit-x-max -ms-scroll-limit-x-min -ms-scroll-limit-y-max -ms-scroll-limit-y-min -ms-scroll-rails -ms-scroll-snap-points-x -ms-scroll-snap-points-y -ms-scroll-snap-x -ms-scroll-snap-y -ms-scroll-translation -ms-text-autospace -ms-touch-select -ms-wrap-flow -ms-wrap-margin -ms-wrap-through zoom pseudo-elements ::-ms-browse ::-ms-check ::-ms-clear ::-ms-expand ::-ms-fill ::-ms-fill-lower ::-ms-fill-upper ...
Specificity - CSS: Cascading Style Sheets
specificity is the means by which browsers decide which css property values are the most relevant to an element and, therefore, will be applied. specificity is based on the matching rules which are composed of different sorts of css selectors. how is specificity calculated? specificity is a weight that is applied to a given css declaration, determined by the number of each selector type in the matching selector. when multiple declarations have equal specificity, the last declaration found in the css is applied to the element. specificity only applies when the same element is targeted by multiple declarations. as per css rules, directly targeted elements will always take precedence over rules which an element inherits from its ancestor. note: proximity of elements in the document tree has...
...tions/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 matches-any pseudo-class :is() and the negation pseudo-class :not() are not considered a pseudo-class in the specificity calculation. but selectors placed into the pseudo-class count as normal selectors when determining the count of selector types. this chunk of css ... div.outer p { color: orange; } div:not(.outer) p { color: blueviolet; } ... when used with the following html ... <div class="outer"> <p>this is in the outer div.</p> <div class="inner"> <p>this text is in the inner div.</p> </div> </div> ... appears on the screen like this: the :where() exception the specifici...
...p">:where()</a></code> pseudo-class. </div> <div class="outer"> <p>this is in the outer div.</p> <div class="inner"> <p>this text is in the inner div.</p> </div> </div> ... appears on the screen like this: form-based specificity specificity is based on the form of a selector. in the following case, the selector *[id="foo"] counts as an attribute selector for the purpose of determining the selector's specificity, even though it selects an id. the following css styles ... *#foo { color: green; } *[id="foo"] { color: purple; } ... when used with this markup ... <p id="foo">i am a sample text.</p> ... end up looking like this: this is because it matches the same element but the id selector has a higher specificity. tree proximity ignorance the proximity of an e...
<alpha-value> - CSS: Cascading Style Sheets
ground color is used. values outside the range of 0 to 1 are permitted, but are clamped to like within the range 0 to 1. if the alpha value is given as a percentage, 0% corresponds to fully transparent while 100% indicates fully opaque. interpolation when animated, values of the <alpha-value> css data type are interpolated as real, floating-point numbers. ...
... used. values outside the range of 0 to 1 are permitted, but are clamped to like within the range 0 to 1. if the alpha value is given as a percentage, 0% corresponds to fully transparent while 100% indicates fully opaque. interpolation when animated, values of the <alpha-value> css data type are interpolated as real, floating-point numbers. ...
...pe are interpolated as real, floating-point numbers. the speed of the interpolation is determined by the timing function associated with the animation. examples setting text color opacity here an alpha value is used to set partially transparent text: /* <rgba()> */ color: rgba(34, 12, 64, 0.6); color: rgba(34.0 12 64 / 60%); setting shape image threshold here an alpha value is used to determine which parts of an image are considered part of a shape: /* shape-image-threshold */ shape-image-threshold: 70%; shape-image-threshold: 0.7; specifications specification status comment css color module level 4the definition of '<alpha-value>' in that specification. working draft no significant change. css color module level 3the definition of '<alpha-...
background-blend-mode - CSS: Cascading Style Sheets
m/mdn/interactive-examples and send us a pull request. blending modes should be defined in the same order as the background-image property. if the blending modes' and background images' list lengths are not equal, it will be repeated and/or truncated until lengths match. syntax /* one value */ background-blend-mode: normal; /* two values, one per background */ background-blend-mode: darken, luminosity; /* global values */ background-blend-mode: initial; background-blend-mode: inherit; background-blend-mode: unset; values <blend-mode> the blending mode to be applied. there can be several values, separated by commas. formal definition initial valuenormalapplies toall elements. in svg, it applies to container elements, graphics elements, and graphics referencing elements.. it also ...
...ontainer elements, graphics elements, and graphics referencing elements.. ...
...elected>screen</option> <option>overlay</option> <option>darken</option> <option>lighten</option> <option>color-dodge</option> <option>color-burn</option> <option>hard-light</option> <option>soft-light</option> <option>difference</option> <option>exclusion</option> <option>hue</option> <option>saturation</option> <option>color</option> <option>luminosity</option> </select> #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: screen; } document.getelementbyid("select").onchange = function(event) { document.getelementbyid("div").style.backgroundblendmode = document.getelementbyid("select").selecte...
border-image-slice - CSS: Cascading Style Sheets
o form the corners of the final border image. zones 5-8 are edge regions. these are repeated, scaled, or otherwise modified in the final border image to match the dimensions of the element. zone 9 is the middle region. it is discarded by default, but is used like a background image if the keyword fill is set. the border-image-repeat, border-image-width, and border-image-outset properties determine how these regions are used to form the final border image. 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-...
...h: changes the width of the border. the sampled image size is scaled to fit inside the border, which means that if the width is bigger than the slice, the image can start to look somewhat pixellated (unless of course you use an svg image). ...
...llated (unless of course you use an svg image). ...
box-lines - CSS: Cascading Style Sheets
Web › CSS › box-lines
this is a property of the original css flexible box layout module draft, and has been replaced by a newer standard. see flexbox for information about the current standard. the box-lines css property determines whether the box may have a single or multiple lines (rows for horizontally oriented boxes, columns for vertically oriented boxes). /* keyword values */ box-lines: single; box-lines: multiple; /* global values */ box-lines: inherit; box-lines: initial; box-lines: unset; by default a horizontal box will lay out its children in a single row, and a vertical box will lay out its children in a single column. this behavior can be changed using the box-lines property. the default value is single, which means that all elements will be placed in a single row or column, and any e...
... will be placed in a single row or column, and any elements that don't fit will simply be considered overflow. if a value of multiple is specified, however, then the box is allowed to expand to multiple lines (that is, multiple rows or columns) in order to accommodate all of its children. the box must attempt to fit its children on as few lines as possible by shrinking all elements down to their minimum widths or heights if necessary. if the children in a horizontal box still do not fit on a line after being reduced to their minimum widths, then children are moved one by one onto a new line, until the elements remaining on the previous line fit. this process can repeat to an arbitrary number of lines. if a line contains only a single element that doesn't fit, then the element should stay on...
...apart from the margins on the largest elements in each line. for calculating the height of a line, margins with a computed value of auto should be treated as having a value of 0. a similar process occurs for children in a vertical box. later lines in normal direction boxes are placed to the right of earlier lines and to the left in reverse direction boxes. once the number of lines has been determined, elements with a computed value for box-flex other than 0 stretch as necessary in an attempt to fill the remaining space on the lines. each line computes flexes independently, so only elements on that line are considered when evaluating box-flex and box-flex-groups. the packing of elements in a line, as specified by the box-pack property, is also computed independently for each line. syntax t...
column-width - CSS: Cascading Style Sheets
one of the values listed below. values <length> indicates the optimal column width. the actual column width may differ from the specified value: it may be wider when necessary to fill available space, and narrower when the available space is too small. the value must be strictly positive or the declaration is invalid. percentage values are also invalid. auto the width of the column is determined by other css properties, such as column-count. formal definition initial valueautoapplies toblock containers except table wrapper boxesinheritednocomputed valuethe absolute length, zero or largeranimation typea length formal syntax <length> | auto examples setting column width in pixels html <p class="content-box"> lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonum...
...plies toblock containers except table wrapper boxesinheritednocomputed valuethe absolute length, zero or largeranimation typea length formal syntax <length> | auto examples setting column width in pixels html <p class="content-box"> lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. ...
... css multi-column layout modulethe definition of 'column-width' in that specification. working draft initial definition. ...
font-weight - CSS: Cascading Style Sheets
ed values (e.g. 451) will be translated to one of these values for non-variable fonts using the fallback weights system. css fonts level 4 extends the syntax to accept any number between 1 and 1000 and introduces variable fonts, which can make use of this much finer-grained range of font weights. fallback weights if the exact weight given is unavailable, then the following rule is used to determine the weight actually rendered: if the target weight given is between 400 and 500 inclusive: look for available weights between the target and 500, in ascending order. if no match is found, look for available weights less than the target, in descending order. if no match is found, look for available weights greater than 500, in ascending order. if a weight less than 400 is gi...
... weights greater than the target, in ascending order. if a weight greater than 500 is given, look for available weights greater than the target, in ascending order. if no match is found, look for available weights less than the target, in descending order. meaning of relative weights when lighter or bolder is specified, the below chart shows how the absolute font weight of the element is determined. note that when using relative weights, only four font weights are considered — thin (100), normal (400), bold (700), and heavy (900). if a font-family has more weights available, they are ignored for the purposes of relative weight calculation. inherited value bolder lighter 100 400 100 200 400 100 300 400 100 400 ...
... give the designer a much closer degree of control over the chosen weight. for truetype or opentype variable fonts, the "wght" variation is used to implement varying widths. for the example below to work, you'll need a browser that supports the css fonts level 4 syntax in which font-weight can be any number between 1 and 1000. ...
<image> - CSS: Cascading Style Sheets
Web › CSS › image
.ico formats. (in this case, the intrinsic dimensions will be those of the image largest in area and the aspect ratio most similar to the containing box.) images with no intrinsic dimensions but with an intrinsic aspect ratio between its width and height, like an svg or other vector format. images with neither intrinsic dimensions, nor an intrinsic aspect ratio, like a css gradient. ...
...ons but with an intrinsic aspect ratio between its width and height, like an svg or other vector format. images with neither intrinsic dimensions, nor an intrinsic aspect ratio, like a css gradient. ...
... 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. if the specified size defines neither the width nor the height, the concrete object size is calculated so that it matches the intrinsic aspect ratio of the image but without exceeding the default object size in any dimension. if the image has n...
position - CSS: Cascading Style Sheets
Web › CSS › position
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax the position property is specified as a single keyword chosen from the list of values below. values static the element is positioned according to the normal flow of the document. the top, right, bottom, left, and z-index properties have no effect. ...
...uto. its effect on table-*-group, table-row, table-column, table-cell, and table-caption elements is undefined. absolute the element is removed from the normal document flow, and no space is created for the element in the page layout. it is positioned relative to its closest positioned ancestor, if any; otherwise, it is placed relative to the initial containing block. its final position is determined by the values of top, right, bottom, and left. this value creates a new stacking context when the value of z-index is not auto. the margins of absolutely positioned boxes do not collapse with other margins. fixed the element is removed from the normal document flow, and no space is created for the element in the page layout. it is positioned relative to the initial containing block establish...
...l containing block established by the viewport, except when one of its ancestors has a transform, perspective, or filter property set to something other than none (see the css transforms spec), in which case that ancestor behaves as the containing block. (note that there are browser inconsistencies with perspective and filter contributing to containing block formation.) its final position is determined by the values of top, right, bottom, and left. this value always creates a new stacking context. in printed documents, the element is placed in the same position on every page. sticky the element is positioned according to the normal flow of the document, and then offset relative to its nearest scrolling ancestor and containing block (nearest block-level ancestor), including table-related el...
<position> - CSS: Cascading Style Sheets
[ left | right ] [ <length> | <percentage> ] ] && [ [ top | bottom ] [ <length> | <percentage> ] ] ] note: the background-position property also accepts a three-value syntax. this is not allowed in other properties that use <position>. interpolation when animated, a point's abscissa and ordinate values are interpolated independently. ...
...<length> | <percentage> ] ] && [ [ top | bottom ] [ <length> | <percentage> ] ] ] note: the background-position property also accepts a three-value syntax. this is not allowed in other properties that use <position>. interpolation when animated, a point's abscissa and ordinate values are interpolated independently. ...
...ue syntax. this is not allowed in other properties that use <position>. interpolation when animated, a point's abscissa and ordinate values are interpolated independently. however, because the speed of the interpolation is determined by a single timing function for both coordinates, the point will move in a straight line. examples valid positions center left center top right 8.5% bottom 12vmin right -6px 10% 20% 8rem 14px invalid positions left right bottom top 10px 15px 20px 15px specifications specification status comment css values and units module level 3the definition of '<position>' in that specification. candidate recommendation relists links to both definitions: if css backgrounds and borders module level 3 is supported, its definition o...
text-transform - CSS: Cascading Style Sheets
the first letter of a word in uppercase. in greek (el), vowels lose their accent when the whole word is in uppercase (ά/Α), except for the disjunctive eta (ή/Ή). also, diphthongs with an accent on the first vowel lose the accent and gain a diaeresis on the second vowel (άι/ΑΪ). in greek (el), the lowercase sigma character has two forms: σ and ς. ς is used only when sigma terminates a word. when applying text-transform: lowercase to an uppercase sigma (Σ), the browser needs to choose the right lowercase form based on context. in irish (ga), certain prefixed letters remain in lowercase when the base initial is capitalized, so for example text-transform: uppercase will change ar aon tslí to ar aon tslÍ and not, as one might expect, ar aon tslÍ (firefox only). in som...
...h ij digraph must be handled like one single letter. uppercase (general) <p>initial string <strong>lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</strong> </p> <p>text-transform: uppercase <strong><span>lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</span></strong> </p> span { text-transform: uppercase; } strong { float: right; } this demonstrates transforming the text to uppercase. uppercase (greek vowels) <p>initial string <strong>Θα πάμε στο "Θεϊκό φαΐ" ή στη "Νεράιδα"</strong> </p> <p>text-transform: uppercase <strong><span>Θα πάμε στο "Θεϊκό φαΐ" ή στη "Νεράιδα"</span></strong> </p> span { text-transform: uppercase; } strong { float: right; } this demonstrates how greek vowels ex...
... vowel pair becomes a diaeresis on the second vowel. lowercase (general) <p>initial string <strong>lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</strong> </p> <p>text-transform: lowercase <strong><span>lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</span></strong> </p> span { text-transform: lowercase; } strong { float: right; } this demonstrates transforming the text to lowercase. lowercase (greek Σ) <p>initial string <strong>Σ is a greek letter that appears several times in ΟΔΥΣΣΕΥΣ.</strong> </p> <p>text-transform: lowercase <strong><span>Σ is a greek letter that appears several times in ΟΔΥΣΣΕΥΣ.</span></strong> </p> span { text-transform: lowercase; } strong { float: right; } this demonstrates how the greek charact...
white-space - CSS: Cascading Style Sheets
. break-spaces the behavior is identical to that of pre-wrap, except that: any sequence of preserved white space always takes up space, including at the end of the line. a line breaking opportunity exists after every preserved white space character, including between white space characters. such preserved spaces take up space and do not hang, and thus affect the box’s intrinsic sizes (min-content size and max-content size). the following table summarizes the behavior of the various white-space values: new lines spaces and tabs text wrapping end-of-line spaces normal collapse collapse wrap remove nowrap collapse collapse no wrap remove pre preserve preserve no wrap preserve pre-...
...white-space: <select> <option>normal</option> <option>nowrap</option> <option>pre</option> <option>pre-wrap</option> <option>pre-line</option> <option>break-spaces</option> </select> } </div> <div id="results" class="box"> <p> lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </div> .box { width: 300px; padding: 16px; border-radius: 10px; } #css...
...e: normal; font-size: 14px; } var select = document.queryselector("#css-code select"); var results = document.queryselector("#results p"); select.addeventlistener("change", function(e) { results.setattribute("style", "white-space: "+e.target.value); }) <p> lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> result specifications specification status comment css...
word-spacing - CSS: Cascading Style Sheets
ord-spacing value will make the sentences the styling is applied to unreadable. for text styled with a very large positive value, the words will be so far apart that it will no longer appear to be a sentence. for text styled with a large negative value, the words will overlap each other to the point where the the beginning and end of each word is unrecognizable. legible word-spacing must be determined on a case-by-case basis, as different font families have different character widths. there is no one value that can ensure all font families automatically maintain their legibility. mdn understanding wcag, guideline 1.4 explanations understanding success criterion 1.4.8 | w3c understanding wcag 2.0 formal definition initial valuenormalapplies toall elements. it also applies to ::first-le...
...hat can ensure all font families automatically maintain their legibility. mdn understanding wcag, guideline 1.4 explanations understanding success criterion 1.4.8 | w3c understanding wcag 2.0 formal definition initial valuenormalapplies toall elements. it also applies to ::first-letter and ::first-line.inheritedyespercentagesrefer to the width of the affected glyphcomputed valuean optimum, minimum, and maximum value, each consisting of either an absolute length, a percentage, or the keyword normalanimation typea length formal syntax normal | <length-percentage>where <length-percentage> = <length> | <percentage> specifications specification status comment css text module level 3the definition of 'word-spacing' in that specification. working draft re...
...rcentage>where <length-percentage> = <length> | <percentage> specifications specification status comment css text module level 3the definition of 'word-spacing' in that specification. working draft replaces the previous values with a <spacing-limit> value that defines the same thing, plus the <percentage> value. allows up to three values describing the optimum, minimum, and maximum value. css level 2 (revision 1)the definition of 'word-spacing' in that specification. recommendation no change. css level 1the definition of 'word-spacing' in that specification. recommendation initial definition. ...
Demos of open web technologies
web technologies, and we encourage their use. this page offers links to interesting demonstrations of these technologies. if you know of a good demonstration or application of open web technology, please add a link to the appropriate section here. ...
...blemenu (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 (or use the local download) summer html image map creator (source code) video video 3d animation "mozilla constantly evolving" video 3d animation "floating dance" streaming anime, movie trailer and interview billy's browser firefox flick virtual barber shop transformers movie trailer a scanner darkly movie trailer (with built in controls) events firing and volume control dragable and sizable videos 3d graphics webgl web audio fireworks ioquake3 (source code) escher puzzle (source code) kai 'opua (source code) virtual reality the polar sea (sourc...
...eworks ioquake3 (source code) escher puzzle (source code) kai 'opua (source code) virtual reality the polar sea (source code) sechelt fly-through (source code) css css zen garden css floating logo "mozilla" paperfold css blockout rubik's cube pure css slides planetarium (source code) loader with blend modes text reveal with clip-path ambient shadow with custom properties luminiscent vial css-based single page application (source code) transformations impress.js (source code) games ioquake3 (source code) kai 'opua (source code) web apis notifications api html5 notifications (source code) web audio api web audio fireworks oscope.js - javascript oscilloscope html5 web audio showcase (source code) html5 audio visualizer (source code) graphi...
Cross-browser audio basics - Developer guides
proach, because the default controls look different among various browsers. so creating your own controls ensures a consistent look for the controls across all browsers. html5 audio in detail now we've looked at a basic example, let's now explore the different aspects of html5 audio in more detail. audio html attributes we can specify a number of attributes with the audio tag to further determine the way audio is initialized. autoplay specifying autoplay will cause the audio to start playing as soon as possible and without any user interaction — in short, the audio will autoplay. <audio autoplay> ... </audio> note: this value is often ignored on mobile platforms, and its use is not recommended unless really necessary. auto-playing audio (and video) is usually really annoying. pl...
...rrenttime is a number which represents the time in seconds. if (myaudio.currenttime > 5) { myaudio.currenttime = 3; } volume the volume property allows us to set the audio volume, as a number between 0 and 1. // set the volume at 50% myaudio.volume = 0.5; creating your own custom audio player the javascript media api allows you to create your own custom player. let's take a look at a very minimal example. we can combine html and javascript to create a very simple player with a play and a pause button. first, we'll set up the audio in the html, without the controls attribute, since we are creating our own controls: <audio id="my-audio"> <source src="audiofile.mp3" type="audio/mpeg"> <source src="audiofile.ogg" type="audio/ogg"> <!-- place fallback here as <audio> supporting brow...
...a", function() { //you could display the playhead now }); progress the progress event indicates that the download of media is still in progress. it is good practice to display some kind of 'loader' at this point. myaudio.addeventlistener("progress", function() { // you could let the user know the media is downloading }); canplay canplay is a useful event to detect should you want to determine whether the media is ready to play. you could, for example, disable custom controls until this event occurs. myaudio.addeventlistener("canplay", function() { //audio is ready to play }); canplaythrough canplaythrough is similar to canplay but it lets you know that the media is ready to be played all the way through (that is to say that the file has completely downloaded, or it is estimated ...
Writing Web Audio API code that works in every browser - Developer guides
unfortunately, chrome, safari and opera still use the webkitaudiocontext prefixed name. furthermore, as a result of the spec being still in flux, some browsers use deprecated properties and method names that are not present in standards-compliant browsers: safari uses the old method names, firefox uses the new ones, and chrome and opera use both. in addition, not all features of web audio are already implemented in firefox yet. ...
...compliant browsers: safari uses the old method names, firefox uses the new ones, and chrome and opera use both. in addition, not all features of web audio are already implemented in firefox yet. what do we do!? we don't want to maintain two or more separate code bases, and feature detection code is cumbersome! plus we want to write code that reliably works in the future, or at least, works with a minimum amount of changes. is there a way to satisfy all these constraints at the same time? probably! writing for today (and tomorrow) first, get a copy of audiocontext-monkeypatch by chris wilson. this little library will "normalise" the interfaces for you and make it look as if your code is running in a standards compliant browser, by aliasing prefixed names to the unprefixed versions. and it won'...
...ed in firefox too. if they aren't, you might be able to change them into something "acceptable" for the time being, and count on the talented audio developers to implement those very soon. for example, up until a couple of days ago pannernode did not support the default hrtf panning model yet, and attempting to use a pannernode with that configuration simply resulted in silence or a mono output coming out from that node, depending on the build you used. today the support is already present in nightly, but not quite yet in aurora. in the meantime, you can explicitly specify 'equalpower' instead: var panner = new audiocontext.pannernode(); panner.panningmodel = 'equalpower'; note that there's a list of projects built with the web audio api, specifying which ones use the standard audiocontext a...
Mouse gesture events - Developer guides
when gesture events occur. if you handle a gesture event and wish to prevent the default action from taking place as well, be sure to call the event's preventdefault() method. types of gesture events mozswipegesture the mozswipegesture event is sent when the user uses three fingers to "swipe" the trackpad. 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. this is typically used to zoom in and out on content (this is the default behavior in firefox, for example). mozmagnifygestureupdate the mozmagnifygestureupdate event is sent periodically while processing a magnify gesture, to provide updated status information. the even...
...can simply watch for this event; however, if you want to provide feedback during the handling of the gesture, you should also watch the mozmagnifygesturestart and mozmagnifygestureupdate events. the delta value is the cumulative change over the course of handling the entire sequence of magnify gesture events. mozrotategesturestart the mozrotategesturestart event is sent when the user begins performing a rotate gesture, by placing two fingers on the trackpad and rotating them around the center of the trackpad. firefox uses this gesture to move backward and forward through the tabs in the current window. mozrotategestureupdate the mozrotategestureupdate event is sent periodically while processing a rotate gesture, to provide updated status information. the event's delta value represents the amo...
...re events have additional fields providing information about the gesture. these are: direction the direction in which the swipe moved. delta the amount by which the gesture moved; for rotation, this value is in degrees. positive values are clockwise and negative values are counterclockwise. for magnification, this value is implementation-specific, but the value is positive for zooming in and negative for zooming out. direction constants the direction field in the gesture events can take one of the following values: simplegestureevent.direction_left leftward swipe. simplegestureevent.direction_right rightward swipe. simplegestureevent.direction_up upward swipe. simplegestureevent.direction_down downward swipe. simplegestureevent.rotation_c...
Using HTML sections and outlines - Developer guides
html5 semantic elements don't need a special dom interface, but they will need a specific css styling in older browser that don't support them explicitly. unknown elements are styled as display: inline by default, so you'll want to set them to display: block: article, aside, footer, header, nav, section { display: block; } of course the web developer can style them differently, but keep in mind that in a non-html5 browser, the default styling is different from what is expected for such elements. also note that the <time> element has not been included, because the default styling for it in a non-html5 browser is the same as the one in an html5-compatible one. next up, older ie versions do not allow styling of unsupported elements, unless you create an instance of them in the dom. you c...
...("section"); document.createelement("time"); </script> <![endif]--> as a last precaution, you could also add an explicit <noscript> element inside the <head> element to warn any users that have javascript disabled that your page relies on javascript: <noscript> <p><strong>this web page requires javascript to be enabled.</strong></p> <p>javascript is an object-oriented computer programming language commonly used to create interactive effects within web browsers.</p> <p><a href="https://goo.gl/koeeaj">how to enable javascript?</a></p> </noscript> this leads to the following code to allow the support of the html5 sections and headings elements in non-html5 browsers, even for internet explorer (8 and older), with a proper fallback for the case where this latter browser is con...
...this isn't a really bad thing neccessarily — sites will often have a few validation errors — but it's something to be aware of still. conclusion the new s...
A hybrid approach - Developer guides
this hybrid approach centers around breaking down mobile development into its three goals, and then applying the best techniques available to tackle each goal individually. ...
...an only using fluid images. by combining the techniques listed above, we can get a mobile web development strategy that is both more flexible than pure separate sites and has better performance than pure responsive design. the bad one downside of mixing approaches is that it can lead to an increase in the number of code paths, both on the client and server side. this can make it more time-consuming to develop than other approaches. with proper planning, though, the code can still be organized in a maintainable way. another downside is that because this approach relies on responsive design, it typically works best on a new project or one that has an existing flexible layout, not as a retrofit. similarly, because it uses user-agent detection, you will have to update your detection rules as t...
...ld also be doing more development involving this approach very soon! in fact, one potential path for the main mozilla site is roughly outlined in the “the good” section above: using user-agent detection, route visitors to a landing page for the firefox version for their device. every page on the site should look great at a wide variety of resolutions, being built with responsive design in mind. future plans include exploring serving images based on user-agent. so far there is not much to see for mobile, since things are still in the formative stages of development, but you can always watch the new mozilla.org grow up on github. subscribe to the mozilla webdev blog for updates about our progress. summary no approach is a one-size-fits-all solution. web applications that want to he...
HTML attribute: required - HTML: Hypertext Markup Language
ll match. the attribute is not supported or relevant to range and color, as both have default values. it is also not supported on hidden as it can not be expected that a user to fill out a form that is hidden. nor is it supported on any of the button types, including image. note color and range don't support required, but type color defaults to #00000, and range defaults to the midpoint between min and max -- with min and max defaulting to 0 and 100 respectively in most browsers if not declared -- so always has a value. when an input has the required attribute, the :required pseudo-class also applies to it. conversely, inputs that support the required attribute but don't have the attribute set match the :optional pseudo-class. in the case of a same named group of radio buttons, if a singl...
...required="true" tells a screen reader that an element (any element) is required, but has no bearing on the optionality of the element. attribute interactions because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified. usability when including the required attribute, provide a visible indication near the control informing the user that the input, select or textarea is required. in addition, target required form controls with the :required pseudo-class, styling them in a way to indicate they are required. this improves usability for sited user. assistive technology should inform the user that the form control in mandatory based on the required attribute, but adding aria-required="true" doesn't hurt, in case the br...
...atus comment html living standardthe definition of 'required attribute' in that specification. living standard html5the definition of 'required attribute' in that specification. recommendation html 5.1the definition of 'required attribute' in that specification. recommendation accessibility concerns provide an indication to users informing them the form control is required. 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. example html <form> <div class="group"> <input type="text"> <label>normal</label> </div> <div class="group"> <input ty...
Standard metadata names - HTML: Hypertext Markup Language
Web › HTML › Element › meta › name
user interface. the content attribute contains a valid css <color>. standard metadata names defined in other specifications the css color adjustment specification defines the following metadata name: color-scheme: specifies one or more color schemes with which the document is compatible. the browser will use this information in tandem with the user's browser or device settings to determine what colors to use for everything from background and foregrounds to form controls and scrollbars. the primary use for <meta name="color-scheme"> is to indicate compatibility with—and order of preference for—light and dark color modes. 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...
...e viewport. not used by any browser. initial-scale a positive number between 0.0 and 10.0 defines the ratio between the device width (device-width in portrait mode or device-height in landscape mode) and the viewport size. maximum-scale a positive number between 0.0 and 10.0 defines the maximum amount to zoom in. it must be greater or equal to the minimum-scale or the behaviour is undefined. browser settings can ignore this rule and ios10+ ignores it by default. minimum-scale a positive number between 0.0 and 10.0 defines the minimum zoom level. it must be smaller or equal to the maximum-scale or the behaviour is undefined. browser settings can ignore this rule and ios10+ ignores it by default. user-scal...
...rgest rectangle inscribed within the display. the cover value means that the viewport is scaled to fill the device display. it is highly recommended to make use of the safe area inset variables to ensure that important content doesn't end up outside the display. notes: though unstandardized, this declaration is respected by most mobile browsers due to de-facto dominance. the default values may vary between devices and browsers. to learn about this declaration in firefox for mobile, see this article. accessibility concerns with viewport scaling disabling zooming capabilities by setting user-scalable to a value of no prevents people experiencing low vision conditions from being able to read and understand page content. mdn understandin...
<source>: The Media or Image Source element - HTML: Hypertext Markup Language
Web › HTML › Element › source
this element includes the global attributes. media media query of the resource's intended media; this should be used only in a <picture> element. sizes is a list of source sizes that describes the final rendered width of the image represented by the source. each source size consists of a comma-separated list of media condition-length pairs. this information is used by the browser to determine, before laying the page out, which image defined in srcset to use. please note that sizes will have its effect only if width dimension descriptors are provided with srcset instead of pixel ratio values (200w instead of 2x for example). the sizes attribute has an effect only when the <source> element is the direct child of a <picture> element. src required for <audio> and <video>, address o...
...ute is specified, it's compared against the types the user agent can present, and if it's not recognized, the server doesn't even get queried; instead, the next <source> element is checked at once. 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>. usage notes the <source> element is an empty element (or void element), which means that it not only has no content but also has no closing tag. that is, you never use "</source>" in your html. for information about image formats supported by web browsers and guidance on selecting appropriate formats to use, see our image file type and format guide on the web. for det...
...ontent is a great resource. picture example in this example, two <source> elements are included within the <picture>, providing versions of an image to use when the available space exceeds certain widths. if the available width is less than the smaller of these widths, the user agent will fall back to the image given by the <img> element. <picture> <source srcset="mdn-logo-wide.png" media="(min-width: 800px)"> <source srcset="mdn-logo-medium.png" media="(min-width: 600px)"> <img src="mdn-logo-narrow.png" alt="mdn web docs"> </picture> with the <picture> element, you must always include an <img> with a fallback image, with an alt attribute to ensure accessibility (unless the image is an irrelevant background decorative image). specifications specification status ...
<tr>: The Table Row element - HTML: Hypertext Markup Language
Web › HTML › Element › tr
a table. there are no groups, no cells that span multiple rows or columns, no captions, and only the most basic styling to create lines around the components of the table for something resembling clarity. there are just four rows (including one header row), each with four columns (including one header column). not even the table section elements are used; instead, the browser is allowed to determine this automatically. we'll add <thead>, <tbody>, and <tfoot> in the next example. <table> <tr> <th>name</th> <th>id</th> <th>member since</th> <th>balance</th> </tr> <tr> <td>margaret nguyen</td> <td>427311</td> <td><time datetime="2010-06-03">june 3, 2010</time></td> <td>0.00</td> </tr> <tr> <td>edvard galinski</td> <td>533175</td> <td><time...
...e> css this time, the html is unchanged, so let's dive right into the css. table { border: 1px solid black; font: 16px "open sans", helvetica, arial, sans-serif; } thead > tr { background-color: rgb(228, 240, 245); } th, td { border: 1px solid black; padding:4px 6px; } while we add a font property to the <table> element here to set a more visually-appealing typeface (or an an abominable sans-serif typeface, depending on your personal opinion), the interesting part is the second style here, where we style <tr> elements located within the <thead> so they have a light blue background color. this is a way to quickly apply a background color to all of the cells in the heading area at once. this does not affect the style of the <th> elements in the first column, though, where we ...
...</td> </tr> </tbody> </table> css the css is much more involved this time. it's not complicated, but there's a lot going on. let's break it down. the table and base styles table { border: 1px solid black; font: 16px "open sans", helvetica, arial, sans-serif; border-spacing: 0; border-collapse: collapse; } here we've added the border-spacing and border-collapse properties to eliminate spacing between cells and collapse borders that touch one another to be a single border instead of winding up with double borders. th, td { border: 1px solid black; padding:4px 6px; } th { vertical-align: bottom; } and here are the default styles for all table cells. now let's customize! the top header: overall we're going to look at the top header in two pieces. first, the overall ...
HTTP caching - HTTP
Web › HTTP › Caching
saving some bandwidth. here is an example of this process with a shared cache proxy: the freshness lifetime is calculated based on several headers. if a "cache-control: max-age=n" header is specified, then the freshness lifetime is equal to n. if this header is not present, which is very often the case, it is checked if an expires header is present. if an expires header exists, then its value minus the value of the date header determines the freshness lifetime. finally, if neither header is present, look for a last-modified header. if this header is present, then the cache's freshness lifetime is equal to the value of the date header minus the value of the last-modified header divided by 10. the expiration time is computed as follows: expirationtime = responsetime + freshnesslifetime - ...
... cached document. when a validation request is made, the server can either ignore the validation request and response with a normal 200 ok, or it can return 304 not modified (with an empty body) to instruct the browser to use its cached copy. the latter response can also include headers that update the expiration time of the cached document. ...
... this can be useful for serving content dynamically, for example. when using the vary: user-agent header, caching servers should consider the user agent when deciding whether to serve the page from cache. ...
HTTP conditional requests - HTTP
http has a concept of conditional requests, where the result, and even the success of a request, can be changed by comparing the affected resources with the value of a validator. such requests can be useful to validate the content of a cache, and sparing a useless control, to verify the integrity of a document, like when resuming a download, or when preventing to lose updates when uploading or modifying a document on the server. principles http conditional requests are requests that are executed differently, depending on the value of specific headers. these headers define a precondition, and the result of the request will be different if the precondition is matched or not. the different behaviors are defined by the method of the request used, and by the set of headers used for a precondit...
...nd are of two kinds: the date of last modification of the document, the last-modified date. an opaque string, uniquely identifying each version, called the entity tag, or the etag. comparing versions of the same resource is a bit tricky: depending on the context, there are two kinds of equality checks: strong validation is used when byte to byte identity is expected, for example when resuming a download. weak validation is used when the user-agent only needs to determine if the two resources have the same content. this is even if they are minor differences; like different ads, or a footer with a different date. the kind of validation is independent of the validator used. both last-modified and etag allow both types of validation, though the complexity to implement it on the server...
...the request will succeed, only if the resource didn't exist before: if-none-match will only work with http/1.1 (and later) compliant servers. if unsure if the server will be compliant, you need first to issue a head request to the resource to check this. conclusion conditional requests are a key feature of http, and allow the building of efficient and complex applications. for caching or resuming downloads, the only work required for webmasters is to configure the server correctly; setting correct etags in some environments can be tricky. once achieved, the browser will serve the expected conditional requests. for locking mechanisms, it is the opposite: web developers need to issue a request with the proper headers, while webmasters can mostly rely on the application to carry out the ch...
Connection management in HTTP/1.x - HTTP
for its transport protocol, providing a connection between the client and the server. in its infancy, http used a single model to handle such connections. these connections were short-lived: a new one created each time a request needed sending, and closed once the answer had been received. this simple model held an innate limitation on performance: opening each tcp connection is a resource-consuming operation. several messages must be exchanged between the client and the server. network latency and bandwidth affect performance when a request needs sending. modern web pages require many requests (a dozen or more) to serve the amount of information needed, proving this earlier model inefficient. two newer models were created in http/1.1. the persistent-connection model keeps connections open...
...et, or even http/2 in cleartext. this protocol upgrade mechanism is documented in more detail elsewhere. short-lived connections the original model of http, and the default one in http/1.0, is short-lived connections. each http request is completed on its own connection; this means a tcp handshake happens before each http request, and these are serialized. the tcp handshake itself is time-consuming, but a tcp connection adapts to its load, becoming more efficient with more sustained (or warm) connections. short-lived connections do not make use of this efficiency feature of tcp, and performance degrades from optimum by persisting to transmit over a new, cold connection. this model is the default model used in http/1.0 (if there is no connection header, or if its value is set to close). in...
...vely this may be called a keep-alive connection. a persistent connection is one which remains open for a period of time, and can be reused for several requests, saving the need for a new tcp handshake, and utilizing tcp's performance enhancing capabilities. this connection will not stay open forever: idle connections are closed after some time (a server may use the keep-alive header to specify a minimum time the connection should be kept open). persistent connections also have drawbacks; even when idling they consume server resources, and under heavy load, dos attacks can be conducted. in such cases, using non-persistent connections, which are closed as soon as they are idle, can provide better performance. http/1.0 connections are not persistent by default. setting connection to anything ...
Cache-Control - HTTP
ensitive, but lowercase is recommended. multiple directives are comma-separated. some directives have an optional argument, which can be either a token or a quoted-string. (see spec for definitions) cache request directives standard cache-control directives that can be used by the client in an http request. cache-control: max-age=<seconds> cache-control: max-stale[=<seconds>] cache-control: min-fresh=<seconds> cache-control: no-cache cache-control: no-store cache-control: no-transform cache-control: only-if-cached cache response directives standard cache-control directives that can be used by the server in an http response. cache-control: must-revalidate cache-control: no-cache cache-control: no-store cache-control: no-transform cache-control: public cache-control: private cache-con...
...source is considered fresh. unlike expires, this directive is relative to the time of the request. s-maxage=<seconds> overrides max-age or the expires header, but only for shared caches (e.g., proxies). ignored by private caches. max-stale[=<seconds>] indicates the client will accept a stale response. an optional value in seconds indicates the upper limit of staleness the client will accept. min-fresh=<seconds> indicates the client wants a response that will still be fresh for at least the specified number of seconds. stale-while-revalidate=<seconds> indicates the client will accept a stale response, while asynchronously checking in the background for a fresh one. the seconds value indicates how long the client will accept a stale response. see "keeping things fresh with stale-while...
...ust ignore them as per the http specification. in firefox, immutable is only honored on https:// transactions. for more information, see also this blog post. other no-transform an intermediate cache or proxy cannot edit the response body, content-encoding, content-range, or content-type. it therefore forbids a proxy or browser feature, such as google’s web light, from converting images to minimize data for a cache store or slow connection. only-if-cached set by the client to indicate "do not use the network" for the response. the cache should either respond using a stored response, or respond with a 504 status code. conditional headers such as if-none-match should not be set. there is no effect if only-if-cached is set by a server as part of a response. examples preventing cachin...
Date - HTTP
Web › HTTP › Headers › Date
at which the message was originated. ...
..."04" or "59". <second> 2 digit second number, e.g. "04" or "59". gmt greenwich mean time. http dates are always expressed in gmt, never in local time. ...
...cond> gmt directives <day-name> one of "mon", "tue", "wed", "thu", "fri", "sat", or "sun" (case-sensitive). <day> 2 digit day number, e.g. "04" or "23". <month> one of "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" (case sensitive). <year> 4 digit year number, e.g. "1990" or "2016". <hour> 2 digit hour number, e.g. "09" or "23". <minute> 2 digit minute number, e.g. "04" or "59". <second> 2 digit second number, e.g. "04" or "59". gmt greenwich mean time. http dates are always expressed in gmt, never in local time. examples date: wed, 21 oct 2015 07:28:00 gmt new date().toutcstring() // "mon, 09 mar 2020 08:13:24 gmt" specifications specification title rfc 7231, section 7.1.1.2: date hypertext trans...
If-Modified-Since - HTTP
f-modified-since can only be used with a get or head. when used in combination with if-none-match, it is ignored, unless the server doesn't support if-none-match. the most common use case is to update a cached entity that has no associated etag. ...
..."04" or "59". <second> 2 digit second number, e.g. "04" or "59". gmt greenwich mean time. http dates are always expressed in gmt, never in local time. ...
...cond> gmt directives <day-name> one of "mon", "tue", "wed", "thu", "fri", "sat", or "sun" (case-sensitive). <day> 2 digit day number, e.g. "04" or "23". <month> one of "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" (case sensitive). <year> 4 digit year number, e.g. "1990" or "2016". <hour> 2 digit hour number, e.g. "09" or "23". <minute> 2 digit minute number, e.g. "04" or "59". <second> 2 digit second number, e.g. "04" or "59". gmt greenwich mean time. http dates are always expressed in gmt, never in local time. examples if-modified-since: wed, 21 oct 2015 07:28:00 gmt specifications specification title rfc 7232, section 3.3: if-modified-since hypertext transfer protocol (http/1.1): conditional requ...
If-Unmodified-Since - HTTP
re rejected if the stored document has been modified since the original has been retrieved. in conjunction with a range request with a if-range header, it can be used to ensure that the new fragment requested comes from an unmodified document. ...
..."04" or "59". <second> 2 digit second number, e.g. "04" or "59". gmt greenwich mean time. http dates are always expressed in gmt, never in local time. ...
...cond> gmt directives <day-name> one of "mon", "tue", "wed", "thu", "fri", "sat", or "sun" (case-sensitive). <day> 2 digit day number, e.g. "04" or "23". <month> one of "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" (case sensitive). <year> 4 digit year number, e.g. "1990" or "2016". <hour> 2 digit hour number, e.g. "09" or "23". <minute> 2 digit minute number, e.g. "04" or "59". <second> 2 digit second number, e.g. "04" or "59". gmt greenwich mean time. http dates are always expressed in gmt, never in local time. examples if-unmodified-since: wed, 21 oct 2015 07:28:00 gmt specifications specification title rfc 7232, section 3.4: if-unmodified-since hypertext transfer protocol (http/1.1): conditional ...
Last-Modified - HTTP
the last-modified response http header contains the date and time at which the origin server believes the resource was last modified. it is used as a validator to determine if a resource received or stored is the same. less accurate than an etag header, it is a fallback mechanism. conditional requests containing if-modified-since or if-unmodified-since headers make use of this field. header type response header forbidden header name no cors-safelisted response header yes syntax last-modified: <day-name>, <day> <month> <year> <hour>:<minute>:<second> gmt directives <day-name> one of "mon", "tue", "wed", "thu", "fri", "sat", or "sun" (case-sensitive). <day> 2 digit day number, e.g. "04" or "23". <month> one of "jan", "feb", "mar", "apr", "...
..."04" or "59". <second> 2 digit second number, e.g. "04" or "59". gmt greenwich mean time. http dates are always expressed in gmt, never in local time. ...
...cond> gmt directives <day-name> one of "mon", "tue", "wed", "thu", "fri", "sat", or "sun" (case-sensitive). <day> 2 digit day number, e.g. "04" or "23". <month> one of "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" (case sensitive). <year> 4 digit year number, e.g. "1990" or "2016". <hour> 2 digit hour number, e.g. "09" or "23". <minute> 2 digit minute number, e.g. "04" or "59". <second> 2 digit second number, e.g. "04" or "59". gmt greenwich mean time. http dates are always expressed in gmt, never in local time. examples last-modified: wed, 21 oct 2015 07:28:00 gmt specifications specification title rfc 7232, section 2.2: last-modified hypertext transfer protocol (http/1.1): conditional requests ...
Firefox user agent string reference - HTTP
oducts based on gecko, the string can take one of two forms, where the tokens have the same meaning except those noted below: mozilla/5.0 (platform; rv:geckoversion) gecko/geckotrail appname/appversion mozilla/5.0 (platform; rv:geckoversion) gecko/geckotrail firefox/firefoxversion appname/appversion appname/appversion indicates the application name and version. for instance, this could be "camino/2.1.1", or "seamonkey/2.7.1". firefox/firefoxversion is an optional compatibility token that some gecko-based browsers may choose to incorporate, to achieve maximum compatibility with websites that expect firefox. firefoxversion will generally represent the equivalent firefox release corresponding to the given gecko version. some gecko-based browsers may not opt into using this token; for th...
...string as desktop firefox. other gecko-based browsers these are some sample ua strings from other gecko-based browsers on various platforms. ...
...ecko-based browsers on various platforms. ...
Link prefetching FAQ - HTTP
tml 4.01 specification explicitly allows for the definition of new link relation types (see section 6.12: link types). however, the exact mechanism employed by mozilla is not yet standardized. an internet-draft is in the works. standardization of this technique is part of the scope of html 5, see the current working draft, section §5.11.3.13. link type "prefetch". how is browser idle time determined? in the current implementation (mozilla 1.2), idle time is determined using the nsiwebprogresslistener api. we attach a listener to the toplevel nsiwebprogress object ("@mozilla.org/docloaderservice;1"). from this, we receive document start & stop notifications, and we approximate idle time as the period between the last document stop and the next document start. the last document stop notific...
...ate for all content. however, it is possible to instruct mozilla to validate a prefetched document when the user follows a href to the prefetched document by specifying the cache-control: must-revalidate http response header. this header enables caching, but requires an if-modified-since or if-none-match validation request before the serving the document out of the browser's cache. as a server admin, can i distinguish prefetch requests from normal requests? yes, we send the following header along with each prefetch request: x-moz: prefetch of course, this request header is not at all standardized, and it may change in future mozilla releases. chrome uses "x-purpose: prefetch" or "purpose: prefetch" header. is there a preference to disable link prefetching? yes, there is a hidden prefere...
...eference to disable <link> tag prefetching may simply encourage websites to stick with js/dom hacks, and that would not be good for users. this is one reason why prefetching is enabled by default. which browsers support link prefetching? browsers based on mozilla 1.2 (or later) as well as browsers based on mozilla 1.0.2 (or later) support prefetching. this includes firefox and netscape 7.01+. camino builds as of march 2003 are based on mozilla 1.0.1, and therefore do not support prefetching. test your browser to see if it supports link prefetching. privacy implications along with the referral and url-following implications already mentioned above, prefetching will generally cause the cookies of the prefetched site to be accessed. (for example, if you google amazon, the google results page...
Equality comparisons and sameness - JavaScript
e 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. the result of a comparison using strict equality is easier to predict, and may evaluate more quickly due to the lack of type coercion. same-value equality same-value equality addresses a final use case: determining whether two values are functionally identical in all contexts. (this use case demonstrates an instance of the liskov substitution principle.) one instance occurs when an attempt is made to mutate an immutable property: // add an immutable negative_zero property to the number constructor. object.defineproperty(number, 'negative_zero', { value: -0, writable: false, configu...
...if your use case does not require this, it is suggested to avoid object.is and use === instead. even if your requirements involve having comparisons between two nan values evaluate to true, generally it is easier to special-case the nan checks (us...
... math.atan2 math.ceil math.pow math.round in some cases,it's possible for a -0 to be introduced into an expression as a return value of these methods even when no -0 exists as one of the parameters. for example, using math.pow to raise -infinity to the power of any negative, odd exponent evaluates to -0. refer to the documentation for the individual methods. math.floor math.max math.min math.sin math.sqrt math.tan it's possible to get a -0 return value out of these methods in some cases where a -0 exists as one of the parameters. e.g., math.min(-0, +0) evaluates to -0. refer to the documentation for the individual methods. ~ << >> each of these operators uses the toint32 algorithm internally. since there is only one representation for 0 in the internal 32-bit integer ...
Expressions and operators - JavaScript
<= 5 note: (=>) is not an operator, but the notation for arrow functions. arithmetic operators an arithmetic operator takes numerical values (either literals or variables) as their operands and returns a single numerical value. the standard arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/). these operators work as they do in most other programming languages when used with floating point numbers (in particular, note that division by zero produces infinity). for example: 1 / 2; // 0.5 1 / 2 == 1.0 / 2.0; // this is true in addition to the standard arithmetic operations (+, -, *, /), javascript provides the arithmetic operators listed in the following table: arithmetic operators operator description example r...
...operator is the only javascript operator that takes three operands. the operator can have one of two values based on a condition. the syntax is: condition ? val1 : val2 if condition is true, the operator has the value of val1. otherwise it has the value of val2. you can use the conditional operator anywhere you would use a standard operator. for example, var status = (age >= 18) ? 'adult' : 'minor'; this statement assigns the value "adult" to the variable status if age is eighteen or more. otherwise, it assigns the value "minor" to status. comma operator the comma operator (,) simply evaluates both of its operands and returns the value of the last operand. this operator is primarily used inside a for loop, to allow multiple variables to be updated each time through the loop. it is re...
...ttype where objectname is the name of the object to compare to objecttype, and objecttype is an object type, such as date or array. use instanceof when you need to confirm the type of an object at runtime. for example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown. for example, the following code uses instanceof to determine whether theday is a date object. because theday is a date object, the statements in the if statement execute. var theday = new date(1995, 12, 17); if (theday instanceof date) { // statements to execute } operator precedence the precedence of operators determines the order they are applied when evaluating an expression. you can override operator precedence by using parentheses. the followi...
Grammar and types - JavaScript
ce about javascript's lexical grammar.) it is considered best practice, however, to always write a semicolon after a statement, even when it is not strictly needed. this practice reduces the chances of bugs getting into the code. the source text of javascript script gets scanned from left to right, and is converted into a sequence of input elements which are tokens, control characters, line terminators, comments, or whitespace. (spaces, tabs, and newline characters are considered whitespace.) comments the syntax of comments is the same as in c++ and in many other languages: // a one line comment /* this is a longer, * multi-line comment */ /* you can't, however, /* nest comments */ syntaxerror */ comments behave like whitespace, and are discarded during script execution. note: y...
...in the following code, the variable input is not assigned a value, and the if statement evaluates to true. var input; if (input === undefined) { dothis(); } else { dothat(); } the undefined value behaves as false when used in a boolean context. for example, the following code executes the function myfunction because the myarray element is undefined: var my...
... = 42 + ' is the answer' // "42 is the answer" with all other operators, javascript does not convert numeric values to strings. for example: '37' - 7 // 30 '37' + 7 // "377" converting strings to numbers in the case that a value representing a number is in memory as a string, there are methods for conversion. parseint() parsefloat() parseint only returns whole numbers, so its use is diminished for decimals. additionally, a best practice for parseint is to always include the radix parameter. the radix parameter is used to specify which numerical system is to be used. parseint('101', 2) // 5 an alternative method of retrieving a number from a string is with the + (unary plus) operator: '1.1' + '1.1' // '1.11.1' (+'1.1') + (+'1.1') // 2.2 // note: the parentheses are added for ...
Iterators and generators - JavaScript
ap() and filter(). iterators and generators bring the concept of iteration directly into the core language and provide a mechanism for customizing the behavior of for...of loops. for details, see also: iteration_protocols for...of function* and generator yield and yield* iterators in javascript an iterator is an object which defines a sequence and potentially a return value upon its termination. specifically, an iterator is any object which implements the iterator protocol by having a next() method that returns an object with two properties: value the next value in the iteration sequence. done this is true if the last value in the sequence has already been consumed. if value is present alongside done, it is the iterator's return value. once created, an iterator object can ...
...t value in the iteration sequence. done this is true if the last value in the sequence has already been consumed. if value is present alongside done, it is the iterator's return value. once created, an iterator object can be iterated explicitly by repeatedly calling next(). iterating over an iterator is said to consume the iterator, because it is generally only possible to do once. after a terminating value has been yielded additional calls to next() should simply continue to return {done: true}. the most common iterator in javascript is the array iterator, which simply returns each value in the associated array in sequence. while it is easy to imagine that all iterators could be expressed as arrays, this is not true. arrays must be allocated in their entirety, but iterators are consume...
.../ 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 iterator. if you need to do this, use iterables. generator functions while custom iterators are a useful tool, their creation requires careful programming due to the need to explicitly maintain their internal state. generator functions provide a powerful alternative: they allow you to define an iterative algorithm by writing a single function whose execution is not continuous. generator functions are written using the function* syntax. when called, generator functions do not initially execute their code. instead, they return a special type of ite...
Character classes - JavaScript
character classes distinguish kinds of characters such as, for example, distinguishing between letters and digits. types the following table is also duplicated on this cheatsheet. do not forget to edit it as well, thanks! characters meaning . has one of the following meanings: matches any single character except line terminators: \n, \r, \u2028 or \u2029. for example, /.y/ matches "my" and "ay", but not "yes", in "yes make my day". inside a character set, the dot loses its special meaning and matches a literal dot. note that the m multiline flag doesn't change the dot behavior. so to match a pattern across multiple lines, the character set [^] can be used — it will match any character including newlines. es2018 added ...
... in "yes make my day". inside a character set, the dot loses its special meaning and matches a literal dot. note that the m multiline flag doesn't change the dot behavior. so to match a pattern across multiple lines, the character set [^] can be used — it will match any character including newlines. es2018 added the s "dotall" flag, which allows the dot to also match line terminators. \d matches any digit (arabic numeral). equivalent to [0-9]. for example, /\d/ or /[0-9]/ matches "2" in "b2 is the suite number". \d matches any character that is not a digit (arabic numeral). equivalent to [^0-9]. for example, /\d/ or /[^0-9]/ matches "b" in "b2 is the suite number". \w matches any alphanumeric character from t...
...in the middle of a word) // \d{4} indicates a digit, four times // \b indicates another boundary (i.e. do not end matching in the middle of a word) console.table(randomdata.match(regexpfourdigits)); // ['8787', '3512', '8735'] looking for a word (from the latin alphabet) starting with a var aliceexcerpt = "i’m sure i’m not ada,’ she said, ‘for her hair goes in such long ringlets, and mine doesn’t go in ringlets at all."; var regexpwordstartingwitha = /\b[aa]\w+/g; // \b indicates a boundary (i.e. do not start matching in the middle of a word) // [aa] indicates the letter a or a // \w+ indicates any character *from the latin alphabet*, multiple times console.table(aliceexcerpt.match(regexpwordstartingwitha)); // ['ada', 'and', 'at', 'all'] looking for a word (from unicode cha...
Unicode property escapes - JavaScript
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. ...
...// ε // 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. if a character is used in a limited set of scripts, the script property will only match for the "predominant" used script. if we want to match characters based on a "non-predominant" script, we could use the script_extensions property (scx for short). ...
...he unicode specification and the scripts table in the ecmascript specification. if a character is used in a limited set of scripts, the script property will only match for the "predominant" used script. if we want to match characters based on a "non-predominant" script, we could use the script_extensions property (scx for short). // ٢ is the digit 2 in arabic-indic notation // while it is predominantly written within the arabic script // it can also be written in the thaana script "٢".match(/\p{script=thaana}/u); // null as thaana is not the predominant script super() "٢".match(/\p{script_extensions=thaana}/u); // ["٢", index: 0, input: "٢", groups: undefined] unicode property escapes vs. character classes with javascript regular expressions, it is also possible to use char...
Date.prototype.getTimezoneOffset() - JavaScript
note that this means that the offset is positive if the local timezone is behind utc, and negative if it is ahead. ...
... note that this means that the offset is positive if the local timezone is behind utc, and negative if it is ahead. ...
... in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax dateobj.gettimezoneoffset() return value a number representing the time-zone offset, in minutes, from the date based on current host system settings to utc. description the time-zone offset is the difference, in minutes, from local time to utc. note that this means that the offset is positive if the local timezone is behind utc, and negative if it is ahead. for example, for time zone utc+10:00 (australian eastern standard time, vladivostok time, chamorro standard time), -600 will be returned. current locale utc-8 utc utc+3 return value 480 0 -180 the time zone...
Date.prototype.setUTCHours() - JavaScript
nd returns the number of milliseconds since january 1, 1970 00:00:00 utc until the time represented by the updated date instance. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax dateobj.setutchours(hoursvalue[, minutesvalue[, secondsvalue[, msvalue]]]) parameters hoursvalue an integer between 0 and 23, representing the hour. minutesvalue optional. an integer between 0 and 59, representing the minutes. secondsvalue optional. an integer between 0 and 59, representing the seconds. if you specify the secondsvalue parameter, you must also specify the minutesvalue. msvalue optional. a number between 0 ...
...ing the hour. minutesvalue optional. an integer between 0 and 59, representing the minutes. secondsvalue optional. an integer between 0 and 59, representing the seconds. if you specify the secondsvalue parameter, you must also specify the minutesvalue. msvalue optional. a number between 0 and 999, representing the milliseconds. if you specify the msvalue parameter, you must also specify the minutesvalue and secondsvalue. return value the number of milliseconds between january 1, 1970 00:00:00 utc and the updated date. description if you do not specify the minutesvalue, secondsvalue, and msvalue parameters, the values returned from the getutcminutes(), getutcseconds(), and getutcmilliseconds() methods are used. if a parameter you specify is outside of the expected range, setutchour...
...te. description if you do not specify the minutesvalue, secondsvalue, and msvalue parameters, the values returned from the getutcminutes(), getutcseconds(), and getutcmilliseconds() methods are used. if a parameter you specify is outside of the expected range, setutchours() attempts to update the date information in the date object accordingly. for example, if you use 100 for secondsvalue, the minutes will be incremented by 1 (minutesvalue + 1), and 40 will be used for seconds. 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.toLocaleTimeString() - JavaScript
he language whose formatting conventions should be used. in implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent. see the intl.datetimeformat() constructor for details on these parameters and how to use them. the default value for each date-time component property is undefined, but if the hour, minute, second properties are all undefined, then hour, minute, and second are assumed to be "numeric". return value a string representing the time portion of the given date instance according to language-specific conventions. performance when formatting large numbers of dates, it is better to create an intl.datetimeformat object and use the function provided by its format property. examples us...
... ecmascript internationalization api (ecma-402)the definition of 'date.prototyp...
... ecmascript internationalization api (ecma-402)the definition of 'date.prototype.tolocaletimestring' in that specification. ...
Intl.DateTimeFormat() constructor - JavaScript
gorithm to use. possible values are "basic" and "best fit"; the default is "best fit". see the following paragraphs for information about the use of this property. the following properties describe the date-time components to use in formatted output, and their desired representations. implementations are required to support at least the following subsets: weekday, year, month, day, hour, minute, second weekday, year, month, day year, month, day year, month month, day hour, minute, second hour, minute implementations may support other subsets, and requests will be negotiated against all available subset-representation combinations to find the best match. two algorithms are available for this negotiation and selected by the formatmatcher property: a fully specified "bas...
...thm and an implementation-dependent "best fit" algorithm. weekday the representation of the weekday. possible values are: "long" (e.g., thursday) "short" (e.g., thu) "narrow" (e.g., t). two weekdays may have the same narrow style for some locales (e.g. tuesday's narrow style is also t). era the representation of the era. possible values are: "long" (e.g., anno domini) "short" (e.g., ad) "narrow" (e.g., a) year the representation of the year. possible values are: "numeric" (e.g., 2012) "2-digit" (e.g., 12) month the representation of the month. possible values are: "numeric" (e.g., 2) "2-digit" (e.g., 02) "long" (e.g., march) "short" (e.g., mar) "narrow" (e.g., m). two months may have the same narrow style ...
...2) "2-digit" (e.g., 02) "long" (e.g., march) "short" (e.g., mar) "narrow" (e.g., m). two months may have the same narrow style for some locales (e.g. may's narrow style is also m). day the representation of the day. possible values are: "numeric" (e.g., 1) "2-digit" (e.g., 01) hour the representation of the hour. possible values are "numeric", "2-digit". minute the representation of the minute. possible values are "numeric", "2-digit". second the representation of the second. possible values are "numeric", "2-digit". timezonename the representation of the time zone name. possible values are: "long" (e.g., british summer time) "short" (e.g., gmt+1) the default value for each date-time component property is undefined, but i...
Intl.DateTimeFormat.prototype.formatToParts() - JavaScript
or the day period, for example, "am", "pm", "in the morning", or "noon" era the string used for the era, for example "bc" or "ad". fractionalsecond the string used for the fractional seconds, for example "0" or "00" or "000". hour the string used for the hour, for example "3" or "03". literal the string used for separating date and time values, for example "/", ",", "o'clock", "de", etc. minute the string used for the minute, for example "00". month the string used for the month, for example "12". relatedyear the string used for the related 4-digit gregorian year, in the event that the calendar's representation would be a yearname instead of a year, for example "2019". second the string used for the second, for example "07" or "42". timezonename the string used for the name...
...s, for example "geng-zi" polyfill a polyfill for this feature is available in the proposal repository. examples datetimeformat outputs localized, opaque strings that cannot be manipulated directly: var date = date.utc(2012, 11, 17, 3, 0, 42); var formatter = new intl.datetimeformat('en-us', { weekday: 'long', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', fractionalseconddigits: 3, hour12: true, timezone: 'utc' }); formatter.format(date); // "monday, 12/17/2012, 3:00:42.000 am" however, in many user interfaces there is a desire to customize the formatting of this string. the formattoparts method enables locale-aware formatting of strings produced by datetimeformat formatters by providing you the string ...
...for example by using array.prototype.map(),...
String.prototype.lastIndexOf() - JavaScript
the lastindexof() method returns the index within the calling string object of the last occurrence of the specified value, searching backwards from fromindex. returns -1 if the value is not found. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.lastindexof(searchvalue[, fromindex]) parameters searchvalue a string representing the value to search for. if searchvalue is an empty string, then fromindex is returned. ...
...is interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.lastindexof(searchvalue[, fromindex]) parameters searchvalue a string representing the value to search for. if searchvalue is an empty string, then fromindex is returned. fromindex optional the index of the last character in the string to be considered as the beginning of a match. the default value is +infinity. if fromindex >= str.length, the whole string is searched. if fromindex < 0, the behavior will be the same as if it would be 0. return value the index of the last occurrence of searchvalue; -1 if not found. description characters in a string are indexed fro...
... case-sensitivity the lastindexof() method is case sensitive. 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". let anystring = 'brave new...
String - JavaScript
umber that is the utf-16 code unit value at the given index. string.prototype.codepointat(pos) returns a nonnegative integer number that is the code point value of the utf-16 encoded code point starting at the specified pos. string.prototype.concat(str [, ...strn ]) combines the text of two (or more) strings and returns a new string. string.prototype.includes(searchstring [, position]) determines whether the calling string contains searchstring. string.prototype.endswith(searchstring [, length]) determines whether a string ends with the characters of the string searchstring. string.prototype.indexof(searchvalue [, fromindex]) returns the index within the calling string object of the first occurrence of searchvalue, or -1 if not found. string.prototype.lastindexof(searchvalue [, fro...
...es whether the calling string contains searchstring. string.prototype.endswith(searchstring [, length]) determines whether a string ends with the characters of the string searchstring. string.prototype.indexof(searchvalue [, fromindex]) returns the index within the calling string object of the first occurrence of searchvalue, or -1 if not found. string.prototype.lastindexof(searchvalue [, fromindex]) returns the index within the calling string object of the last occurrence of searchvalue, or -1 if not found. string.prototype.localecompare(comparestring [, locales [, options]]) returns a number indicating whether the reference string comparestring comes before, after, or is equivalent to the given string in sort order. string.prototype.match(regexp) used to match regular expression r...
...exp) search for a match between a regular expression regexp and the calling string. string.prototype.slice(beginindex[, endindex]) extracts a section of a string and returns a new string. string.prototype.split([sep [, limit] ]) returns an array of strings populated by splitting the calling string at occurences of the substring sep. string.prototype.startswith(searchstring [, length]) determines whether the calling string begins with the characters of string searchstring. string.prototype.substr() returns the characters in a string beginning at the specified location through the specified number of characters. string.prototype.substring(indexstart [, indexend]) returns a new string containing characters of the calling string from (or between) the specified index (or indeces). stri...
WebAssembly.instantiate() - JavaScript
rst webassembly.instance. the secondary overload takes an already-compiled webassembly.module and returns a promise that resolves to an instance of that module. this overload is useful if the module has already been compiled. important: this method is not the most efficient way of fetching and instantiating wasm modules. if at all possible, you should use the newer webassembly.instantiatestreaming() method instead, which fetches, compiles, and instantiates a module all in one step, directly from the raw bytecode, so doesn't require conversion to an arraybuffer. syntax primary overload — taking wasm binary code promise<resultobject> webassembly.instantiate(buffersource, importobject); parameters buffersource a typed array or arraybuffer containing the binary code of the .wasm m...
...that resolves to an webassembly.instance object. exceptions if either of the parameters are not of the correct type or structure, a typeerror is thrown. if the operation fails, the promise rejects with a webassembly.compileerror, webassembly.linkerror, or webassembly.runtimeerror, depending on the cause of the failure. examples note: you'll probably want to use webassembly.instantiatestreaming() in most cases, as it is more efficient than instantiate(). 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. we then call an exported webassembly function that is exported by the instance. var importobject ...
....then(bytes => webassembly.instantiate(bytes, importobject) ).then(result => result.instance.exports.exported_func() ); note: you can also find this example at index.html on github (view it live also). 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(). var worker = new worker("wasm_worker.js"); webassembly.compilestreaming(fetch('simple.wasm')) .then(mod => worker.postmessage(mod) ); in the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread. when the module is received, we create an...
isNaN() - JavaScript
hence, the necessity of an isnan function. origin of nan values nan values are generated when arithmetic operations result in undefined or unrepresentable values. ...
...ing rules; you may alternatively want to use number.isnan(), as defined in ecmascript 2015. syntax isnan(value) parameters value the value to be tested. return value true if the given value is nan; otherwise, false. description the necessity of an isnan function unlike all other possible values in javascript, it is not possible to rely on the equality operators (== and ===) to determine whether a value is nan or not, because both nan == nan and nan === nan evaluate to false. hence, the necessity of an isnan function. origin of nan values nan values are generated when arithmetic operations result in undefined or unrepresentable values. such values do not necessarily represent overflow conditions. a nan also results from attempted coercion to numeric values of non-numeric value...
...e, dividing zero by zero results in a nan — but dividing other numbers by zero does not. confusing special-case behavior since the very earliest versions of the isnan function specification, its behavior for non-numeric arguments has been confusing. when the argument to the isnan function is not of type number, the value is first coerced to a number. the resulting value is then tested to determine whether it is nan. thus for non-numbers that when coerced to numeric type result in a valid non-nan numeric value (notably the empty string and boolean primitives, which when coerced give numeric values zero or one), the "false" returned value may be unexpected; the empty string, for example, is surely "not a number." the confusion stems from the fact that the term, "not a number", has a specifi...
export - JavaScript
ere are two types of exports: named exports (zero or more exports per module) default exports (one per module) // exporting individual features export let name1, name2, …, namen; // also var, const export let name1 = …, name2 = …, …, namen; // also var, const export function functionname(){...} export class classname {...} // export list export { name1, name2, …, namen }; // renaming exports export { variable1 as name1, variable2 as name2, …, namen }; // exporting destructured assignments with renaming export const { name1, name2: bar } = o; // default exports export default expression; export default function (…) { … } // also class, function* export default function name1(…) { … } // also class, function* export { name1 as default, … }; // aggregating module...
...andatory to use the same name of the corresponding object. but a default export can be imported with any name for example: // file test.js let k; export default k = 12; // some other file import m from './test'; // note that we have the freedom to use import m instead of import k, because k was default export console.log(m); // will log 12 you can also rename named exports to avoid naming conflicts: export { myfunction as function1, myvariable as variable }; re-exporting / aggregating it is also possible to "import/export" from different modules in a parent module so that they are available to import from that module. in other words, one can create a single module concentrating various exports from various modules. this can be achieved with the "export from" syntax:...
...in another script, it is straightforward to import the default export: import cube from './my-module.js'; console.log(cube(3)); // 27 using export from let's take an example where we have the following hierarchy: childmodule1.js: exporting myfunction and myvariable childmodule2.js: exporting myclass parentmodule.js: acting as an aggregator (and doing nothing else) top level module: consuming the exports of parentmodule.js this is what it would look like using code snippets: // in childmodule1.js let myfunction = ...; // assign something useful to myfunction let myvariable = ...; // assign something useful to myvariable export {myfunction, myvariable}; // in childmodule2.js let myclass = ...; // assign something useful to myclass export myclass; // in parentmodule.js // only a...
for...of - JavaScript
for (const entry of iterable) { console.log(entry); } // ['a', 1] // ['b', 2] // ['c', 3] for (const [key, value] of iterable) { console.log(value); } // 1 // 2 // 3 iterating over a set const iterable = new set([1, 1, 2, 2, 3, 3]); for (const value of iterable) { console.log(value); } // 1 // 2 // 3 iterating over the arguments object you can iterate over the arguments object to examine all of the parameters passed into a javascript function: (function() { for (const argument of arguments) { console.log(argument); } })(1, 2, 3); // 1 // 2 // 3 iterating over a dom collection iterating over dom collections like nodelist: the following example adds a read class to paragraphs that are direct descendants of an article: // note: this will only work in platforms that hav...
...in these cases, the iterator is closed. function* foo(){ yield 1; yield 2; yield 3; }; for (const o of foo()) { console.log(o); break; // closes iterator, execution continues outside of the loop } console.log('done'); iterating over generators you can also iterate over generators, i.e. functions generating an iterable object: function*...
...upon exiting a loop, the generator is closed and trying to iterate over it again does not yield any further results. const gen = (function *(){ yield 1; yield 2; yield 3; })(); for (const o of gen) { console.log(o); break; // closes iterator } // the generator should not be re-used, the following does not make sense! for (const o of gen) ...
Web media technologies
ccessible from javascript as htmltrackelement objects. <source> the html <source> element is used within an <audio> or <video> element to specify source media to present. multiple sources can be used to provide the media in different formats, sizes, or resolutions. accessible from javascript as htmlsourceelement objects. apis media capabilities api the media capabilities api lets you determine the encoding and decoding capabilities of the device your app or site is running on. this lets you make real-time decisions about what formats to use and when. media capture and streams api a reference for the api which makes it possible to stream, record, and manipulate media both locally and across a network. this includes using local cameras and microphones to capture video, audio, and stil...
...uide to media types and formats on the web a guide to the file types and codecs available for images, audio, and video media on the web. this includes recommendations for what formats to use for what kinds of content, best practices including how to provide fallbacks and how to prioritize media types, and also includes general browser support information for each media container and codec. streaming audio and video a guide which covers how to stream audio and video, as well as techniques and technologies you can take advantage of to ensure the best possible quality and/or performance of your streams. autoplay guide for media and web audio apis unexpected automatic playback of media or audio can be an unwelcome surprise to users. while autoplay serves a purpose, it should be used carefull...
...play blocking. this article is a guide to autoplay, with tips on when and how to use it and how to work with browsers to handle autoplay blocking gracefully. positional audio in a 3d environment in 3d environments, which may either be 3d scenes rendered to the screen or a mixed reality experience experienced using a headset, it's important for audio to be performed so that it sounds like it's coming from the direction of its source. this guide covers how to accomplish this. playing video in a 3d environment in this guide, we examine how to play video into a 3d scene. this technique can be used in both standard webgl applications presented on a flat computer screen, or in a webxr-generated virtual or augmented reality environment. other topics related topics which may be of interest,...
Animation performance and frame rate - Web Performance
(fps). while it is not always possible to maintain 60fps, it is important to maintain a high and steady frame rate for all animations. let's take a look at how we can use browser tools to inspect the frame rate. we'll also discuss some tips to create and maintain a fast and steady frame rate. the developer tool's frame rate and waterfall charts provide insight into the work the browser is performing to animate code. using these tools you can measure an application's animation frame rate, and diagnose performance bottlenecks if any are found. with css animations you specify a number of keyframes, each of which uses css to define the appearance of the element at a particular stage of the animation. the browser creates the animation as a transition from each keyframe to the next. compared wi...
... recording. you'll only need to record a few seconds. open up the first recording. exactly what you'll see depends a lot on your machine and system load, but it will be something like this: this is showing three distinct views: (a) an overview of the waterfall, (b) the frame rate, and (c) the timeline details. waterfall overview this is showing a compressed view of the waterfall. the predominance of green is telling us that we're spending a lot of time painting. frame rate this is showing frame rate. average frame rate here is 46.67fps, well below the target of 60fps. worse, though, is that the frame rate is very jagged, with lots of dips into the twenties and teens. it's unlikely you'll see a smooth animation here, especially when you add in user interaction. waterfall the rest...
...in the screenshot above we've highlighted a paint operation, and the box on the right tells us it took 13.11ms. with only 16.7ms in our total budget, it's not surprising we are missing a consistently high frame rate. you can experiment with this: try removing the box shadow using the page inspector, and see how that affects paint time. but next, we'll see how using transform instead of margin eliminates those expensive paints entirely. animating using transform now switch the radio button in the web page to "use transform", and make a new recording. it will look something like this: waterfall overview compared with the version that uses margin, we're seeing a lot less green and a lot more pink, which could be either layout or style recalculation. frame rate compared with the vers...
Lazy loading - Web Performance
d on the home page of an e-commerce site which has a link to a cart page/section and all its resources (js, css, images...) are downloaded only when the user navigates to that cart page. strategies lazy loading can be applied to multiple resources and through multiple strategies. general code splitting javascript, css and html can be split into smaller chunks. this enables sending the minimal code required to provide value upfront, improving page-load times. the rest can be loaded on demand. entry point splitting: separates code by entry point(s) in the app dynamic splitting: separates code where dynamic import() statements are used javascript script type module any script tag with type="module" is treated like a javascript module and is deferred by default. ...
... are off-screen until the user scrolls near them. <img src="image.jpg" loading="lazy" alt="..." /> <iframe src="video-player.html" loading="lazy"></iframe> the load event fires when the eagerly-loaded content has all been loaded; at that time, it's entirely possible (or even likely) that there may be lazily-loaded images that are within the visual viewport that haven't yet loaded. you can determine if a given image has finished loading by examining the value of its boolean complete property. polyfill include this polyfill to provide support for older and currently incompatible browsers: loading-attribute-polyfill intersection observer api intersection observers allow the user to know when an observed element enters or exits the browser’s viewport. event handlers when browser compa...
...older and currently incompatible browsers: loading-attribute-polyfill intersection observer api intersection observers allow the user to know when an observed element enters or exits the browser’s viewport. event handlers when browser compatibility is crucial, there are a few options: polyfill intersection observer fallback to scroll, resize or orientation change event handlers to determine if a specific element is in viewport specifications specification status comment html living standard living standard ...
Optimizing startup performance - Web Performance
dition, the browser may automatically parallelize these decoders. any data processing that can be done in parallel should be. don't do one chunk of data after another; do them all at once when possible! don't include scripts or stylesheets that don't participate in the critical path in your startup html file. load them only when needed. reduce the side of your javascript files. try to send the minify version of the file to the browser and use compression like gzip or brotli. utilize resource hints (like preconnect or preload) whenever possible to indicate to the browser which files are more critical for your application. the more stuff you can do asynchronously, the better advantage your app can take of multicore processors. porting issues once the initial loading is done and the app'...
...a function to be executed before the main thread is allowed to continue. by establishing a queue of functions to be called in sequence, you can more easily manage running bits of code without blocking the main thread. that leaves, though, the problem of having to refactor your existing code to actually work that way. that can take some time. ...
...having to refactor your existing code to actually work that way. that can take some time. how asynchronous should i get? it's worth keeping in mind that most browsers typically start complaining that your script is blocking the main thread for too long at around 10 seconds or so. ideally, you won't block anywhere near that long, but as long as you keep it below that, you should be okay. keep in mind, though, that if someone has an older, slower computer than yours, they may experience longer delays than you do! other suggestions there are other things beyond going asynchronous, which can help you improve your app's startup time. here are a few of them: download time keep in mind how long it will take the user to download your game's data. if your game is really big, really popular, or...
Performance budgets - Web Performance
o a file, a file type, all files loaded on a page, a specific metric (e.g. time to interactive), a custom metric (e.g. time to hero element), or a threshold over a period of time. why do i need a performance budget? a budget exists to reflect your reachable goals. it's a tradeoff between user experience, against other performance indicators (e.g. conversion rate). these goals can be: timing based (e.g. time to interactive, first contentful paint). quantity-based (e.g. amount of js files/total image size). rule-based (e.g. pagespeed index, lighthouse score). their primary goal is to prevent regressions, but they can provide insights to forecast trends (i.e. on september, 50% of the budget was spent in a week). additionally, it can uncover development needs (i.e. a large library...
...efine a performance budget? a budget should include 2 levels: warning. error. the warning level allows you to be proactive and plan any tech debt, while not blocking development or deploys. the error level is an upper bound limit, where changes will have a negative and noticeable impact. in order to begin, you need to first measure the devices and connection speeds where your users are coming from (e.g. a ~$200 android device over a 3g connection), using multiple tools. these time-based metrics will translate into file-size budgets. a default baseline to reduce bounce rate is to achieve time to interactive under 5 seconds in 3g/4g, and under 2 seconds for subsequent loads. however, based on the specific goals and content of your site, you might choose to focus on other metrics. for...
.... the first step is to define a development baseline for each branch to compare to and the precision of the difference between development and production can be used as a goal towards better match the live environment. the lighthouse bot integrates with travis ci and can be used to gather lighthouse and webpage test metrics from a development url. the bot will pass or fail based on the provided minimum scores. how do i enforce a performance budget? the sooner that you can identify a potential addition pushing the budget, the better you can analyze the current state of your site, and pinpoint optimizations or unnecessary code. however, you should have multiple budgets and be dynamic. they are meant to reflect your ongoing goals but allow risks and experiments. for example, you may introdu...
Performance Monitoring: RUM vs synthetic monitoring - Web Performance
ke through a web application, reporting back the performance the simulator experiences. the traffic measured is not of your actual users, but rather synthetically generated traffic collecting data on page performance. an example of synthetic monitoring is webpagetest.org. it is done in a controlled environment where variable like geography, network, device, browser, and cached status are predetermined. it provides waterfall charts for every asset served by the host and cdn as well as every third party asset and asset requests generated by all third party scripts, such as ads and analytic services. controlling for environmental variables is helpful in understanding where performance bottlenecks have been occurring and identifying the source of any performance issues. for example, but it isn'...
...t back performance metrics experienced. rum helps identify how an application is being used, including the geographic distribution of users and the impact of that distribution on the end user experience. unlike synthetic monitoring, rum captures the performance of actual users regardless of device, browser, network or geographic location. as users interact with an application, all performance timings are captured, regardless of what actions are taken or pages viewed. rum monitors actual use cases, not the synthetic, assumed use cases predefined by an engineer, pm, or marketing team. this is particularly important for large sites or complex apps, where the functionality or content is constantly changing, and where the population accessing the application may differ greatly in life experience...
...only a narrow view of performance. rum, on the other hand, provides real metrics from real users using the site or application. while this is more expensive and likely less convenient, it provides vital user experience data. performance apis there are many monitoring services. if you do want to roll your own monitoring system, take a look at the performance apis, mainly performancenavigationtiming and performanceresourcetiming, but also performancemark, performancemeasure, and performancepainttiming. ...
Using dns-prefetch - Web Performance
this is because the ip behind your site’s domain will have already been resolved by the time the browser sees the hint. second, it’s also possible to specify dns-prefetch (and other resources hints) as...
... <head> <link rel="dns-prefetch" href="https://fonts.gstatic.com/"> <!-- and all other head elements --> </head> <body> <!-- your page content --> </body> </html> you should place dns-prefetch hints in the <head> element any time your site references resources on cross-origin domains, but there are some things to keep in mind. 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. this is because the ip behind your site’s domain will have already been resolved by the time the browser sees the hint. second, it’s also possible to specify dns-prefetch (and other resources hints) as an http header by using the http link field: link: <http...
...cify 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. while dns-prefetch only performs a dns lookup, preconnect establishes a connection to a server. this process includes dns resolution, as well as establishing the tcp connection, and performing the tls handshake—if a site is served over https. combining the two provides an opportunity to further reduce the perceived latency of cross-origin requests. you can safely use them together like so: <link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin> <link rel="dns-prefetch" href="https://fonts.gstatic.com/"> note: if a page needs to make connections to many third-party ...
Privacy, permissions, and information security
as users use the web for more and more of their daily tasks, more of their private or personally-identifying information they share, ideally only with sites they trust. cooperation among web content, the web browser, and the web server is needed to achieve as much privacy and information security as possible. in this article, we examine how to create web content that minimizes the risk of users' personal information or imagery being obtained unexpectedly by third parties. security and privacy defined before we go into any depth about the various security and privacy features available to users on the web, let's define some important terms. personally identifiable information personally identifiable information (pii) is information which can be used, in whole or in part, to track do...
...is. personal and private information <what kind of information is private or personal?> privacy risks <what are ways personal information can be gotten by third parties?> fingerprinting fingerprinting is a technique used to gather a variety of information that's made available by a user's browser and collating it until it becomes possible to uniquely identify that user's browser. even seemingly innocuous information can in principle be used in the fingerprinting process, though the more unique the information is to the particular device the better. modern browsers take steps to help prevent fingerprinting-based attacks by either not allowing information to be accessed or, where the information must be made available, by introducing variations that prevent it from being used for iden...
...this is the technology behind the https (hypertext transport protocol secured) protocol not all of these are generally directly used within code; notably, t...
Introduction to progressive web apps - Progressive web apps (PWAs)
web apps use technologies like media queries and viewport to make sure that their uis will fit any form factor: desktop, mobile, tablet, or whatever comes next. safety the web platform provides a secure delivery mechanism that prevents snooping while simultaneously ensuring that content hasn’t been tampered with, as long as you take advantage of https and develop your apps with security in mind. it's also easy for users to ensure that they're installing the right app, because its url will match your site's domain. this is very different from apps in app stores, which may have a number of similarly-named apps, some of which may even be based on your own site, which only adds to the confusion. web apps eliminate that confusion and ensure that users get the best possible experience. bro...
...of your app when those features are unavailable. presenting a trusted website with a good performance is a consequence of using these enhancements; this in turn means building web apps which follow better practices. this way everybody will be able to use the app, but those with modern browsers will benefit from pwa features even more. ...
... for now, let's move to the second part of this series, where we’ll be looking at the structure of our example app. ...
Applying SVG effects to HTML content - SVG: Scalable Vector Graphics
sk specified below it. everything else specifies details about the gradient mask itself. applying the svg effect to (x)html is accomplished by assigning the target class defined above to an element, like this: <p class="target" style="background:lime;"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam. </p> <p> lorem ipsum dolor sit amet, consectetur adipisicing <b class="target">elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</b> ut enim ad minim veniam. </p> the above example would be rendered with the mask applied to it. example: clipping this example demonstrates using svg to clip html content. notice that even the clickable areas for...
.../p> the above example would be rendered with the mask applied to it. example: clipping this example demonstrates using svg to clip html content. notice that even the clickable areas for links are clipped. <p class="target" style="background:lime;"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam. </p> <p> lorem ipsum dolor sit amet, consectetur adipisicing <b class="target">elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</b> ut enim ad minim veniam. </p> <button onclick="toggleradius()">toggle radius</button> <svg height="0"> <clippath id="clipping-path-1" clippathunits="objectboundingbox"> <circle cx="0.25" cy="0.25" r="0.25" id=...
... } example: filtering this demonstrates applying a filter to html content using svg. it establishes several filters, which are applied with css to three elements in both the normal and mouse hover states. <p class="target" style="background: lime;"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam. </p> <pre class="target">lorem</pre> <p> lorem ipsum dolor sit amet, consectetur adipisicing <b class="target">elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</b> ut enim ad minim veniam. </p> any svg filter can be applied this way. for example, to apply a blur effect, you might use: <svg height="0"> <filter id="f1"> <fegaussianblur stdd...
alignment-baseline - SVG: Scalable Vector Graphics
matches the box’s corresponding baseline to that of its parent. before-edge the alignment-point of the object being aligned is aligned with the "before-edge" baseline of the parent text content element. text-bottom matches th...
...ph>, and <textpath> usage notes value auto | baseline | before-edge | text-before-edge | middle | central | after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical | top | center | bottom default value auto animatable yes auto the value is the dominant-baseline of the script to which the character belongs - i.e., use the dominant-baseline of the parent. baseline uses the dominant baseline choice of the parent. matches the box’s corresponding baseline to that of its parent. before-edge the alignment-point of the object being aligned is aligned with the "before-edge" baseline of the parent text content element. text-bottom matches the bottom of the box to the top of the parent’s content area. text-before-edg...
... specifications specification status comment css inline layoutthe definition of 'alignment-baseline' in that specification. working draft no change scalable vector graphics (svg) 2the definition of 'alignment-baseline' in that specification. candidate recommendation refers to the definition in css inline layout and notes the changes t...
arabic-form - SVG: Scalable Vector Graphics
isolated this value indicates that the glyph represents the isolated form. ...
... isolated this value indicates that the glyph represents the isolated form. ...
... isolated this value indicates that the glyph represents the isolated form. ...
fill-rule - SVG: Scalable Vector Graphics
note: as a presentation attribute, fill-rule can be used as a css property. ...
...therefore considered outside the shape, and not filled. --> <polygon fill-rule="evenodd" stroke="red" points="150,0 121,90 198,35 102,35 179,90"/> </svg> usage notes value nonzero | evenodd default value nonzero animatable yes the fill-rule attribute provides two options for how the inside (that is, the area to be filled) of a shape is determined: nonzero the value nonzero determines the "insideness" of a point in the shape by drawing a ray from that point to infinity in any direction, and then examining the places where a segment of the shape crosses the ray. starting with a count of zero, add one each time a path segment crosses the ray from left to right and subtract one each time a path segment crosses the ray from right to left. ...
...if this number is odd, the point is inside; if even, the point is outside. example html,body,svg { height:100% } <svg viewbox="-10 -10 320 120" xmlns="http://www.w3.org/2000/svg"> <!-- effect of evenodd ...
kernelUnitLength - SVG: Scalable Vector Graphics
ance for the x and y coordinates, for <feconvolvematrix>, it indicates the intended distance between successive columns and rows in the kernel matrix. 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. by specifying value(s) for kernelunitlength, the kernel becomes defined in a scalable, abstract coordinate system. if the attribute is not specified, the default value is one pixel in the offscreen bitmap, which is a pixel-based coordinate system, and thus potentially not scalable. ...
...mber> default value pixel in offscreen bitmap animatable yes <number-optional-number> the first number is the x value. the second number is the y value. if the x value is not specified, it defaults to the same value as x. fediffuselighting for the <fediffuselighting>, kernelunitlength indicates the intended distance in current filter units (i.e., units as determined by the value of attribute primitiveunits) for the x and y coordinate, respectively, in the surface normal calculation formulas. the first number is the x value. the second number is the y value. if the y value is not specified, it defaults to the same value as x. by specifying value(s) for kernelunitlength, the kernel becomes defined in a scalable, abstract coordinate system. if the attribute ...
...ystem, and thus potentially not scalable. if a negative or zero value is specified the default value will be used instead. value <number-optional-number> default value pixel in offscreen bitmap animatable yes fespecularlighting for the <fespecularlighting>, kernelunitlength indicates the intended distance in current filter units (i.e., units as determined by the value of attribute primitiveunits) for the x and y coordinate, respectively, in the surface normal calculation formulas. the first number is the x value. the second number is the y value. if the y value is not specified, it defaults to the same value as x. by specifying value(s) for kernelunitlength, the kernel becomes defined in a scalable, abstract coordinate system. if the attribute ...
requiredFeatures - SVG: Scalable Vector Graphics
this provides a way to design svg that gracefully falls back when features aren't available. if the attribute is not present, then its implicit evaluated value is true. ...
...ect 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. determines whether all of the named features are supported by the browser. see feature strings below for a list of allowed values. feature strings the following are the feature strings for the requiredfeatures attribute. these same feature strings apply to the hasfeature method call that is part of the svg dom's support for the domimplementation interface. in some cases the feature strings map directly...
...ings the following are the feature strings for the requiredfeatures attribute. these same feature strings apply to the hasfeature method call that is part of the svg dom's support for the domimplementation interface. in some cases the feature strings map directly to a set of attributes, properties or elements, in others they represent some functionality of the browser. note that the format and naming for feature strings changed from svg 1.0 to svg 1.1. the svg 1.0 feature strings are not listed here but can be found in the svg specification. some browser support svg 1.0 feature strings for compatibility reasons. however, the svg 1.0 feature strings are considered deprecated. http://www.w3.org/tr/svg11/feature#svg at least one of the following feature is supported: http://www.w3.or...
text-anchor - SVG: Scalable Vector Graphics
it is not applicable to other types of auto-wrapped text. for those cases you should use text-align. for multi-line text, the alignment takes place for each line. the text-anchor attribute is applied to each individual text chunk within a given <text> element. ...
...text chunk within a given <text> element. each text chunk has an initial current text position, which represents the point in the user coordinate system resulting from (depending on context) application of the x and y attributes on the <text> element, any x or y attribute values on a <tspan>, <tref> or <altglyph> element assigned explicitly to the first rendered character in a text chunk, or determination of the initial current text position for a <textpath> element. note: as a presentation attribute, text-anchor can be used as a css property. as a presentation attribute, it can be applied to any element but it has effect only on the following five elements: <altglyph>, <text>, <textpath>, <tref>, and <tspan> html, body, svg { height: 100%; } <svg viewbox="0 0 120 120" xmlns="http://...
...ction (often typical for asian text), the top side of the text is rendered at the initial text position. middle the rendered characters are aligned such that the middle of the text string is at the current text position. (for text on a path, conceptually the text string is first laid out in a straight line. the midpoint between the start of the text string and the end of the text string is determined. then, the text string is mapped onto the path with this midpoint placed at the current text position.) end the rendered characters are shifted such that the end of the resulting rendered text (final current text position before applying the text-anchor property) is at the initial current text position. for an element with a direction property value of ltr (typical for most european languages...
<feConvolveMatrix> - SVG: Scalable Vector Graphics
ng image. a wide variety of imaging operations can be achieved through convolutions, including blurring, edge detection, sharpening, embossing and beveling. a matrix convolution is based on an n-by-m matrix (the convolution kernel) which describes how a given pixel value in the input image is combined with its neighboring pixel values to produce a resulting pixel value. each result pixel is determined by applying the kernel matrix to the corresponding source pixel and its neighboring pixels. the basic convolution formula which is applied to each color value for a given pixel is: colorx,y = ( sum i=0 to [ordery-1] { sum j=0 to [orderx-1] { source x-targetx+j, y-targety+i * kernelmatrixorderx-j-1, ordery-i-1 } ...
...input image which is 5 pixels by 5 pixels, whose color values for one of the color channels are as follows: 0 20 40 235 235 100 120 140 235 235 200 220 240 235 235 225 225 255 255 255 225 225 255 255 255 and you define a 3-by-3 convolution kernel as follows: 1 2 3 4 5 6 7 8 9 let's focus on the color value at the second row and second column of the image (source pixel value is 120). ...
...20 40 235 235 100 120 140 235 235 200 220 240 235 235 225 225 255 255 255 225 225 255 255 255 and you define a 3-by-3 convolution kernel as follows: 1 2 3 4 5 6 7 8 9 let's focus on the color value at the second row and second column of the image (source pixel value is 120). ...
<svg> - SVG: Scalable Vector Graphics
Web › SVG › Element › svg
inner svg elements or inside html documents. html,body,svg { height:100% } <svg viewbox="0 0 300 100" xmlns="http://www.w3.org/2000/svg" stroke="red" fill="grey"> <circle cx="50" cy="50" r="40" /> <circle cx="150" cy="50" r="4" /> <svg viewbox="0 0 10 10" x="200" width="100"> <circle cx="5" cy="5" r="4" /> </svg> </svg> attributes baseprofile deprecated since svg 2 the minimum svg language profile that the document requires. value type: <string> ; default value: none; animatable: no contentscripttype deprecated since svg 2 the default scripting language used by the svg fragment. value type: <string> ; default value: application/ecmascript; animatable: no contentstyletype deprecated since svg 2 the default style sheet language used by the svg fragment. value ...
...ge used by the svg fragment. value type: <string> ; default value: text/css; animatable: no height the displayed height of the rectangular viewport. (not the height of its coordinate system.) value type: <length>|<percentage> ; default value: auto; animatable: yes preserveaspectratio how the svg fragment must be deformed if it is displayed with a different aspect ratio. value type: (none| xminymin| xmidymin| xmaxymin| xminymid| xmidymid| xmaxymid| xminymax| xmidymax| xmaxymax) (meet|slice)? ; default value: xmidymid meet; animatable: yes version deprecated since svg 2 which version of svg is used for the inner content of the element. value type: <number> ; default value: none; animatable: no viewbox the svg viewport coordinates for the current svg fragment. value type: <list-of-n...
...aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role usage notes categoriescontainer element, structural elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elementsstructural elementsgradient elements<a>, <altglyphdef>, <clippath>, <color-profile>, <cursor>, <filter>, <font>, <font-face>, <foreignobject>, <image>, <marker>, <mask>, <pattern>,...
SVG 1.1 Support in Firefox - SVG: Scalable Vector Graphics
someday. there is also a description of the mozilla support of the changes in svg 2. element implementation status a quick overview of the svg 1.1 elements and the current status of the native support. element notes structure module svg implemented. ...
...rcle implemented. line implemented. ellipse implemented. polyline implemented. polygon implemented. text module text implemented. ...
...recently implemented presentation attributes: direction, unicode-bidi, font-variant, text-decoration svgtextelement recently imlemented bindings: selectsubstring recently implemented attributes: textlength, lengthadjust tspan implemented. ...
Basic shapes - SVG: Scalable Vector Graphics
however, since they're used in most svg documents, it's necessary to give them some sort of introduction. basic shapes to insert a shape, you create an element in the document. ...
...t="30"/> x the x position of the top left corner of the rectangle. y the y position of the top left corner of the rectangle. width the width of the rectangle height the height of the rectangle rx the x radius of the corners of the rectangle ry the y radius of the corners of the rectangle circle the <circle> element draws a circle on the screen. ...
... <ellipse cx="75" cy="75" rx="20" ry="5"/> rx the x radius of the ellipse. ry the y radius of the ellipse. cx the x position of the center of the ellipse. cy the y position of the center of the ellipse. ...
Introduction - SVG: Scalable Vector Graphics
1.5, and that support level has been growing with each release since. hopefully, along with the tutorial here, mdn can help developers keep up with the differences between gecko and some of the other major implementations. before starting you should have a basic understanding of xml or another markup language such as html. if you are not too familiar with xml, here are some guidelines to keep in mind: svg elements and attributes should all be entered in the case shown here since xml is case-sensitive (unlike html). attribute values in svg must be placed inside quotes, even if they are numbers. svg is a huge specification. this tutorial attempts to cover the basics. once you are familiar you should be able to use the element reference and the interface reference to find out anything els...
... entered in the case shown here since xml is case-sensitive (unlike html). attribute values in svg must be placed inside quotes, even if they are numbers. svg is a huge specification. this tutorial attempts to cover the basics. once you are familiar you should be able to use the element reference and the interface reference to find out anything else you need to know. ...
... apart from the full svg recommendations, the working group at the w3c introduced svg tiny and svg basic in 2003. ...
Texts - SVG: Scalable Vector Graphics
Web › SVG › Tutorial › Texts
display of text in an image, and the other are svg fonts. the latter may be described in a later section of the tutorial, while we will focus completely on the first part: bringing text into an svg image. basics we have seen in the introducing example, that the text element can be used to put arbitrary text in svg documents: <text x="10" y="10">hello world!</text> the x and y attributes determine, where in the viewport the text will appear. the attribute text-anchor, which can have the values "start", "middle", "end" or "inherit", decides in which direction the text flows from this point. the attribute dominant-baseline decides the vertical alignment. like with the shape elements text can be colorized with the fill attribute and given a stroke with the stroke attribute. both may also re...
...be a child of a text element or another tspan element. a typical usecase is to paint one word of a sentence bold red. <text> this is <tspan font-weight="bold" fill="red">bold and red</tspan> </text> playable code <svg width="350" height="60" xmlns="http://www.w3.org/2000/svg"> <text> this is <tspan font-weight="bold" fill="red">bold and red</tspan> </text> <style><![cdata[ text{ dominant-baseline: hanging; font: 28px verdana, helvetica, arial, sans-serif; } ]]></style> </svg> the tspan element has the following custom attributes: x set a new absolute x coordinate for the containing text. this overwrites the default current text position. the attribute may also contain a list of numbers, that are one by one applied to the single characters of the tspan element. ...
...http://www.w3.org/1999/xlink" xlink:href="#my_path"> a curve. ...
Same-origin policy - Web security
rent domain or a superdomain of its current domain. if set to a superdomain of the current domain, the shorter superdomain is used for same-origin checks. for example, assume a script from the document at http://store.company.com/dir/other.html executes the following: document.domain = "company.com"; afterward, the page can pass the same-origin check with http://company.com/dir/page.html (assuming http://company.com/dir/page.html sets its document.domain to "company.com" to indicate that it wishes to allow that - see document.domain for more). however, company.com could not set document.domain to othercompany.com, since that is not a superdomain of company.com. the port number is checked separately by the browser. any call to document.domain, including document.domain = document.domain, ...
...t explorer, firefox, chrome, safari (scroll down to cve-2010-0051) and opera. images displayed by <img>. media played by <video> and <audio>. external resources embedded with <object> and <embed>. fonts applied with @font-face. some browsers allow cross-origin fonts, others require same-origin. anything embedded by <iframe>. sites can use the x-frame-options header to prevent cross-origin framing. how to allow cross-origin access use cors to allow cross-origin access. cors is a part of http that lets servers specify what hosts are permitted to load content from that server. how to block cross-origin access to prevent cross-origin writes, check an unguessable token in the request — known as a cross-site request forgery (csrf) token. you must prevent cross-origin reads of pages th...
...and indexeddb are separated by origin. each origin gets its own separate storage, and javascript in one origin cannot read from or write to the storage belonging to another origin. cookies use a separate definition of origins. a page can set a cookie for its own domain or any parent domain, as long as the parent domain is not a public suffix. firefox and chrome use the public suffix list to determine if a domain is a public suffix. internet explorer uses its own internal method to determine if a domain is a public suffix. the browser will make a cookie available to the given domain including any sub-domains, no matter which protocol (http/https) or port is used. when you set a cookie, you can limit its availability using the domain, path, secure, and httponly flags. when you read a cookie, y...
Subdomain takeovers - Web security
ions in lifecycle management for virtual hosts and dns. depending on the size of the organization, this may require communication and coordination across multiple departments, which can only increase the likelihood for a vulnerable misconfiguration. define standard processes for provisioning and deprovisioning hosts. do all steps as closely together as possible. ...
...work within your organization to make this part of the vendor qualification process. my subdomain has been taken over. ...
...organization to make this part of the vendor qualification process. my subdomain has been taken over. what should i do? if you discover that a subdomain of your domain has been taken over, the first step, if possible, is to "cut power" by removing the dns entry for the subdomain. if your site has multiple layers of virtualization (e.g., a cdn in addition to virtual hosting), you may need to examine each layer to see where exactly the attacker asserted their virtual host claim to take over your domain. learn more 'deep thoughts' on subdomain takeover vulnerabilities subdomain takeover: basics ...
XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes xpath stands for xml path language. it uses a non-xml syntax to provide a flexible way of addressing (pointing to) different parts of an xml document. it can also be used to test addressed nodes within a document to determine whether they match a pattern or not. 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. xpath uses a path notation (as in urls) for navigating through the hierarchical structure of an xm...
...ou may consider js-xpath or wicked-good-xpath. documentation introduction to using xpath in javascript describes a non-xslt use of xpath. xpath:axes list and definition of the axes defined in the xpath specification. axes are used to describe the relationships between nodes. xpath:functions list and description of the core xpath functions and xslt-specific additions to xpath. transforming xml with xslt xslt uses xpath to address code segments in an xml document that it wishes to transform. xpath snippets these are javascript utility functions, that can be used in your own code, based on dom level 3 xpath apis. what is xslt? this extensive introduction to xslt and xpath assumes no prior knowledge of the technologies, and guides the reader through background, context, structu...
...o address code segments in an xml document that it wishes to transform. xpath snippets these are javascript utility functions, that can be used in your own code, based on dom level 3 xpath apis. what is xslt? this extensive introduction to xslt and xpath assumes no prior knowledge of the technologies, and guides the reader through background, context, structure, concepts, and introductory terminology. jxon jxon (lossless javascript xml object notation) is a generic name by which is defined the representation of javascript objects using xml. there are some cases in which the whole content of an xml document must be read from the javascript interpreter (like for web-apps languages or settings xml documents, for example). in these cases jxon could represent the most practical way and vali...
<xsl:stylesheet> - XSLT: Extensible Stylesheet Language Transformations
separated. extension-element-prefixes specifies a space-separated list of any namespace prefixes for extension elements in this document. default-collation specifies the default collation used by all xpath expressions appearing in attributes or text value templates that have the element as an ancestor, unless overridden by another default-collation attribute on an inner element. it also determines the collation used by certain xslt constructs (such as <xsl:key> and xsl:for-each-group) within its scope. default-mode defines the default value for the mode attribute of all <xsl:template> and <xsl:apply-templates> elements within its scope. default-validation defines the default value of the validation attribute of all relevant instructions appearing within its scope. expand-text deter...
...es the collation used by certain xslt constructs (such as <xsl:key> and xsl:for-each-group) within its scope. default-mode defines the default value for the mode attribute of all <xsl:template> and <xsl:apply-templates> elements within its scope. default-validation defines the default value of the validation attribute of all relevant instructions appearing within its scope. expand-text determines whether descendant text nodes of the element are treated as text value templates. id specifies an id for this stylesheet. this is most often used when the stylesheet is embedded in another xml document. input-type-annotations specifies whether type annotations are stripped from the element so the same results are produced whether the source documents have been validated against a schema or ...
... text nodes of the element are treated as text value templates. id specifies an id for this stylesheet. this is most often used when the stylesheet is embedded in another xml document. input-type-annotations specifies whether type annotations are stripped from the element so the same results are produced whether the source documents have been validated against a schema or not. use-when determines whether the element and all the nodes that have it as ancestor are excluded from the stylesheet. xpath-default-namespace specifies the namespace that will be used if the element name is unprefixed or an unprefixed type name within an xpath expression. type required outermost element of stylesheet. specifications specification status comment xslt 3.0the definit...
Using the Mozilla JavaScript interface to XSL Transformations - XSLT: Extensible Stylesheet Language Transformations
eventlistener("load", onload, false); testtransform.load("test-transform.xml"); function onload() { processor.importstylesheet(testtransform); } xsltprocessor.importstylesheet() requires one argument, a dom node. if that node is a document node, you can pass in a full xsl transform or a literal result element transform, otherwise it must be an xsl:stylesheet or xsl:transform element. transforming the document you can use the xsltprocessor.transformtodocument() or xsltprocessor.transformtofragment() methods to transform a document using the imported xslt stylesheet. transformtodocument xsltprocessor.transformtodocument() takes one argument, the source node to transform, and returns a new document with the results of the transformation: var newdocument = processor.transformtodocument(d...
...only produce html dom objects if the owner document is itself an htmldocument, or if the output method of the stylesheet is html. it will not produce an html dom objects if only the toplevel element of the result is <html> as xsltprocessor.transformtofragment() is rarely used to create this element. if you want to override this, you can set the output method normally in the standard way. ...
... setting parameters you can control parameters for the stylesheet using the xsltprocessor.setparameter(), xsltprocessor.getparameter(), and xsltprocessor.removeparameter() methods. ...
WebAssembly
less webassembly code that has already been compiled by the browser and can be efficiently shared with workers, and instantiated multiple times. webassembly.instance() a webassembly.instance object is a stateful, executable instance of a module. instance objects contain all the exported webassembly functions that allow calling into webassembly code from javascript. webassembly.instantiatestreaming() the webassembly.instantiatestreaming() function is the primary api for compiling and instantiating webassembly code, returning both a module and its first instance. webassembly.memory() a webassembly.memory object is a resizable arraybuffer that holds the raw bytes of memory accessed by an instance. webassembly.table() a webassembly.table object is a resizable typed array of opaque values...
... 52notes notes disabled in the firefox 52 extended support release (esr).opera android full support 43safari ios full support 11samsung internet android full support 7.0nodejs full support 8.0.0compilestreamingchrome full support 61edge full support 16firefox full support 58ie no support noopera full support 47safari no support nowebview...
... 52notes notes disabled in the firefox 52 extended support release (esr).opera android full support 43safari ios full support 11samsung internet android full support 7.0nodejs full support 8.0.0instantiatestreamingchrome full support 61edge full support 16firefox full support 58ie no support noopera full support 47safari no support nowebview...
2015 MDN Fellowship Program - Archive of obsolete content
r: @brittanystoroz webgl brief project description webgl is the latest incarnation of the opengl family of real time rendering immediate mode graphics apis. webgl is getting some cool new features in 2015 with the standardization efforts around the webgl 2.0 spec being published. activities and deliverables help us develop a curriculum on mdn for teaching developers new to graphics programming the webgl apis. required skills and experience computer graphics experience with programmable shaders and the opengl, opengl es, webgl, or direct3d apis. command of javascript and module systems preferred. mentor information nick desaulniers, sleeps at desk. github: nickdesaulniers twitter: @lostoracle web app performance brief project description web performance is a feature that ne...
...rs on a regular basis. in 2015, mdn will expand the impact of this content by developing kits of key learning materials, including such elements as code samples, videos and other elements being finalized. activities and deliverables act as lead curator for technical curriculum addressing a key web technology, developing code samples, videos, interactive exercises and other components to be determined. you may propose your own subject area (examples: virtual reality on the web, network security, css, etc.) or we will work with you to match you to the best subject based on your background and mozilla priorities. required skills and experience experienced web developer with expertise in javascript, css, html and/or other key technologies. proficient in written and spoken english. mentor inf...
Window: deviceproximity event - Archive of obsolete content
max read only double (float) the maximum value in the range the sensor detects (if available, 0 otherwise). related events userproximity ...
... max read only double (float) the maximum value in the range the sensor detects (if available, 0 otherwise). related events userproximity ...
Content Scripts - Archive of obsolete content
e specified using html, and use separate scripts to interact with this content. in many ways these are like content scripts, but they're not the focus of this article. to learn about how to interact with the content for a given user interface module, please see the module-specific documentation: panel, sidebar, frame. almost all the examples presented in this guide are available as complete, but minimal, add-ons in the addon-sdk-content-scripts repository on github. loading content scripts you can load a single script by assigning a string to either the contentscript or the contentscriptfile option. the contentscript option treats the string itself as a script: // main.js var pagemod = require("sdk/page-mod"); var contentscriptvalue = 'document.body.innerhtml = ' + ...
... you can also use contentscript and contentscriptfile together. if you do this, scripts specified using contentscriptfile are loaded before those specified using contentscript. this enables you to load a javascript library like jquery by ur...
page-mod - Archive of obsolete content
so you can rewrite the above code like this: var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "*.mozilla.org", contentscriptfile: "./my-script.js" }); unless your content script is extremely simple and consists only of a...
... script in your "data" directory. so you can rewrite the code above like this: var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "*", contentscriptfile: "./my-script.js" }); to attach multiple scripts, pass an array of urls. var data = require("sdk/self").data; var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "*", contentscriptfile: [data.url("jquery.min.js"), data.url("my-script.js")] }); content scripts specified using this option are loaded before those specified by the contentscript option. name: contentscript type: string,array this option specifies one or more content scripts to attach to targeted documents. each script is supplied directly as a single string: var pagemod = require("sdk/page-mod"); pag...
panel - Archive of obsolete content
ndleclick(state) { textentrypanel.show(); } // when the panel is displayed it generated an event called // "show": we will listen for that event and when it happens, // send our own "show" event to the panel's script, so the // script can prepare the panel for display. textentrypanel.on("show", function() { textentrypanel.port.emit("show"); }); // listen for messages called "text-entered" coming from // the content script. the message payload is the text the user // entered. // in this implementation we'll just log the text to the console. textentrypanel.port.on("text-entered", function (text) { console.log(text); textentrypanel.hide(); }); the content script "get-text.js" looks like this: // when the user hits return, send the "text-entered" // message to main.js. // the message ...
...ndleclick(state) { textentrypanel.show(); } // when the panel is displayed it generated an event called // "show": we will listen for that event and when it happens, // send our own "show" event to the panel's script, so the // script can prepare the panel for display. textentrypanel.on("show", function() { textentrypanel.port.emit("show"); }); // listen for messages called "text-entered" coming from // the content script. the message payload is the text the user // entered. // in this implementation we'll just log the text to the console. textentrypanel.port.on("text-entered", function (text) { console.log(text); textentrypanel.hide(); }); the page script is exactly the same as the content script above, except that instead of self, we use addon to access the messaging apis: // wh...
tabs - Archive of obsolete content
onopen: function onopen(tab) { // do stuff like listen for content // loading. } }); parameters options : object required options: name type url string string url to be opened in the new tab. this is a required property. optional options: name type isprivate boolean boolean which will determine whether the new tab should be private or not. if your add-on does not support private browsing this will have no effect. see the private-browsing documentation for more information. defaults to false. innewwindow boolean if present and true, a new browser window will be opened and the url will be opened in the first tab in that window. this is an optional property. ...
...icating whether or not the page was loaded from the bfcache. activate this event is emitted when the tab is made active. note that you cannot guarantee that a tab's content, or even its url, are initialized at the time activate is emitted. this is because when a new tab is opened, its activate event may be emitted before the content is loaded. you can use the tab's readystate property to determine whether the tab's content and url will be available: if readystate is uninitialized or loading, then you can't access the tab's properties and must wait for the tab's ready event. arguments tab : listeners are passed the tab object. deactivate this event is emitted when the tab is made inactive. arguments tab : listeners are passed the tab object. ...
windows - Archive of obsolete content
usage the windows module provides basic functions for working with browser windows. with this module, you can: enumerate the currently opened browser windows open new browser windows listen for common window events such as open and close private windows if your add-on has not opted into private browsing, then you won't see any private browser windows. private browser windows won't appear in the browserwindows property, you won't receive any window events, and you won't be able to open private windows. to learn more about private windows, how to opt into private browsing, and how to support private browsing, refer to the documentation for the private-browsing module. ...
...", onclick: function() { example.close(); } }); this example uses the action button api, which is only available from firefox 29 onwards. parameters options : object required options: name type url string string url to be opened in the new window. this is a required property. isprivate boolean boolean which will determine whether the new window should be private or not. if your add-on does not support private browsing this will have no effect. see the private-browsing documentation for more information. optional options: name type onopen function a callback function that is called when the window has opened. this does not mean that the url content has loaded, o...
content/mod - Archive of obsolete content
constructors functions attachto(modification, window) function applies given modification to a given window. for example, the following code applies a style to a content window, adding a border to all divs in page: var attachto = require("sdk/content/mod").attachto; var style = require("sdk/stylesheet/style").style; var style = style({ source: "div { border: 4px solid gray }" }); // assuming window points to the content page we want to modify attachto(style, window); parameters modification : object the modification we want to apply to the target. window : nsidomwindow the window to be modified. detachfrom(modification, window) function removes attached modification from a given window. if window is not specified, modification is removed from all the windows it's being attach...
...window is not specified, modification is removed from all the windows it's being attached to. for example, the following code applies and removes a style to a content window, adding a border to all divs in page: var { attachto, detachfrom } = require("sdk/content/mod"); var style = require("sdk/stylesheet/style").style; var style = style({ source: "div { border: 4px solid gray }" }); // assuming window points to the content page we want to modify attachto(style, window); // ... detachfrom(style, window); parameters modification : object the modification we want to remove from the target window : nsidomwindow the window to be modified. if window is not provided modification is removed from all targets it's being attached to. gettargetwindow(target) function takes target, value rep...
core/promise - Archive of obsolete content
rationale most of the js apis are asynchronous complementing its non-blocking nature. while this has a good reason and many advantages, it comes with a price. ...
...ndler represents a catch for readasync(), while the value handler represents code that happens after the try/catch block. that code then needs its own try/catch block to handle errors there. in terms of promises, this means chaining your error handler: readasync(url). then(parse). then(null, function handleparseerror(error) { // handle here both `readasync` and `parse` errors. }); consuming promises in general, the whole purpose of promises is to avoid the so-called callback spaghetti. as a matter of fact it would be great if we could convert any synchronous functions to asynchronous by making it aware of promises. module exports promised function to do exactly that: const { promised } = require('sdk/core/promise'); function sum(x, y) { return x + y }; var asyncsum = promised(sum...
dev/panel - Archive of obsolete content
0]; toaddon.start(); toaddon.postmessage("message from the panel document"); console.log(toaddon); }); communicating with the debugger server the firefox developer tools use a client/server protocol: a tool, such as a javascript debugger or style editor, is the client, and the program being debugged, such as firefox, is the server. clients connect to the server and send it messages to examine and modify the state of the program being debugged. the remote debugging protocol page describes the protocol in detail. when the user opens a panel and the panel is created, the framework calls the panel's setup method. the setup method will be passed a debuggee object, which is a messageport that the add-on can use to exchange messages with the debugger server. for example, here's a main.js ...
...ementbyid("content"); window.addeventlistener("message", function(event) { var debuggee = event.ports[0]; volcan.connect(debuggee). then(listtabs). then(writetablist); }); function listtabs(root) { return root.listtabs(); } function writetablist(tablist) { content.textcontent = tablist.tabs[tablist.selected].url; } we don't have detailed documentation for volcan.js, but it's coming soon. in the meantime, here's a quick guide. connecting volcan.js provides a global connect() function that takes a messageport connected to the debugger server, and returns a promise which is fulfilled with an object representing the root actor: volcan.connect(debuggee).then(gotroot); function gotroot(root) { // can use root actor here } actors actors in the remote debugging protocol are...
io/text-streams - Archive of obsolete content
a given text encoding. you can also create textreader objects using io/file's open() function. parameters inputstream : stream the backing stream, an nsiinputstream. it must already be opened. charset : string inputstream is expected to be in the character encoding named by this value. if not specified, "utf-8" is assumed. see nsicharsetconvertermanager.idl for documentation on how to determine other valid values for this. textwriter(outputstream, charset) creates a buffered output stream that writes text to a backing stream using a given text encoding. you can also create textwriter objects using io/file's open() function. parameters outputstream : stream the backing stream, an nsioutputstream. it must already be opened. charset : string text will be written to outputstream us...
...t encoding. you can also create textwriter objects using io/file's open() function. parameters outputstream : stream the backing stream, an nsioutputstream. it must already be opened. charset : string text will be written to outputstream using the character encoding named by this value. if not specified, "utf-8" is assumed. see nsicharsetconvertermanager.idl for documentation on how to determine other valid values for this. textreader methods close() closes both the stream and its backing stream. read(numchars) reads and returns a string from the stream. if the stream is closed, an exception is thrown. parameters numchars : number the number of characters to read. if not given, the remainder of the stream is read. returns string : the string read. if the stream is at the end,...
places/bookmarks - Archive of obsolete content
s : bookmark|group|separator|array a bookmark item (bookmark, group, separator), or an array of bookmark items to be saved. options : object optional options: name type resolve function a resolution function that is invoked during an attempt to save a bookmark item that is not derived from the latest state from the platform. invoked with two arguments, mine and platform, where mine is the item that is being saved, and platform is the current state of the item on the item. the object returned from this function is what is saved on the platform. by default, all changes on an outdated bookmark item overwrite the platform's bookmark item. returns placesemitter : returns a placesemitter. remove(items) a helper function that takes in a book...
...together, meaning that if an item matches any of the query objects, it will be retrieved. for example, suppose we called search() with two query objects: [{ url: "mozilla.org", tags: ["mobile"]}, { tags: ["firefox-os"]}] this will return: all bookmark items from mozilla.org that are also tagged "mobile" all bookmark items that are tagged "firefox-os" an options object may be used to determine overall settings such as sort order and how many objects should be returned. parameters queries : object|array an object representing a query, or an array of objects representing queries. each query object can take several properties, which are queried against the bookmarks database. each property is and'd together, meaning that bookmarks must match each property within a query object. multip...
system/events - Archive of obsolete content
tch. listener : function function that will be called when an event is fired, with a single event object as argument. this object has three attributes: type: the event type name subject: the event subject object data: the event data string strong : boolean default is false, a weak reference, which means it can be garbage collected at any time if there are no other references to it. determines if we should keep a strong or weak reference to the listener method. once(type, listener, strong) listen only once to a particular event type parameters type : string the event type name to watch. listener : function function that will be called when an event is fired. strong : boolean default is false, a weak reference, which means it can be garbage collected at any time if there are ...
... weak reference to the listener method. once(type, listener, strong) listen only once to a particular event type parameters type : string the event type name to watch. listener : function function that will be called when an event is fired. strong : boolean default is false, a weak reference, which means it can be garbage collected at any time if there are no other references to it. determines if we should keep a strong or weak reference to the listener method. off(type, listener) stop listening for an event parameters type : string the event type name to unsubscribe to. listener : function the function we registered to listen for events. ...
test/assert - Archive of obsolete content
al : object the actual result. expected : object the expected result. message : string optional message to log, providing extra information about the test. deepequal(actual, expected, message) tests that two objects have a deep equality relation. ...
...ve a deep equality relation. deep equality is defined in the commonjs specification for assert, item 7, which is quoted here: all identical values are equivalent, as determined by ===. if the expected value is a date object, the actual value is equivalent if it is also a date object that refers to the same time. other pairs that do not both pass typeof value == "object", equivalence is determined by ==. for all other object pairs, including array objects, equivalence is determined by having the same number of owned properties (as verified with object.prototype.hasownproperty.call), the same set of keys (although not necessarily the same order), equivalent values for every corresponding key, and an identical "prototype" property. note: this accounts for both named and indexed properties...
ui/button/toggle - Archive of obsolete content
window or tab, call state(), passing in the window or tab you are interested in, and it will return the state: var labelforactivetab = button.state("tab").label; to learn more about this, see the api documentation for state(). updating checked you can update a toggle button's checked property in just the same way you update its other properties, but there's one extra thing you need to keep in mind. the checked property is not only updated directly by assignment, but is also updated when the user clicks the button (or when some code calls button.click()). when that happens, the button is updated for the window whose button was clicked. because window-specific state overrides global state, if you try to update checked by direct assignment to the button, this will be overridden by the user...
...disabled buttons appear disabled in the ui, and do not respond to clicks. defaults to false. onchange function change handler for the button. onclick function click handler for the button. badge number or string new in firefox 36. badge to attach to the button. the badge c...
console - Archive of obsolete content
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. console methods all console methods except exception() and trace() accept one or more javascript objects as arguments and log them to the console. depending on the console's underlying implementation and user interface, you may be able to examine the properties of non-primitive objects that are logged. console.debug(...) deprecated, you should use console.log() instead. console.error(object[, object, ...]) logs the arguments to the console, preceded by "error:" and the name of your add-on: console.error("this is an error message"); error: my-addon: this is an error message console.exception(exception) logs the given exception i...
... info error(), exception(), info(), log(), time(), timeend(), trace(), warn() warn error(), exception(), warn() error error(), exception() off nothing setting the logging level the logging level defaults to "error". there are two system preferences that can be used to override this default: extensions.sdk.console.loglevel: if set, this determines the logging level for all installed sdk-based add-ons. extensions.extensionid.sdk.console.loglevel, where extensionid is an add-on's program id. if set, this determines the logging level for the specified add-on. this overrides the global preference if both preferences are set. both these preferences can be set programmatically using the preferences/service api, or manually using abou...
package.json - Archive of obsolete content
ten into the install manifest when the add-on is built using jpm xpi. others, such as lib, permissions, and preferences, represent instructions to the jpm tool itself to generate and include particular code and data structures in your add-on. creating a manifest the package.json file is initially generated in your add-on's root directory the first time you run jpm init. ...
... description the add-on's description; this is a human-readable message describing what the add-on does. this defaults to the text "a basic add-on". this value will be used as the add-on's em:description element in its install.rdf. engines object with supported applications (key) and required version numbers (value). the version number can both specify a minimum and maximum version separated by a space. firefox: firefox desktop fennec: firefox for android thunderbird: thunderbird seamonkey: seamonkey any application uuid example: "engines": { "firefox": ">= 38.0a1", "fennec": ">= 38.0a1" } fullname note: this is deprecated along with cfx; it's not available when using jpm. th...
Modifying Web Pages Based on URL - Archive of obsolete content
t and jquery together (making sure to load jquery first). // import the page-mod api var pagemod = require("sdk/page-mod"); // import the self api var self = require("sdk/self"); // create a page mod // it will run a script whenever a ".org" url is loaded // the script replaces the page contents with a message pagemod.pagemod({ include: "*.org", contentscriptfile: [self.data.url("jquery-1.7.min.js"), self.data.url("my-script.js")] }); you can use both contentscript and contentscriptfile in the same page-mod. if you do this, scripts loaded using contentscriptfile are loaded first. // import the page-mod api var pagemod = require("sdk/page-mod"); // import the self api var self = require("sdk/self"); // create a page-mod // it will run a script whenever a ".org" url is loaded // the s...
..., scripts loaded using contentscriptfile are loaded first. // import the page-mod api var pagemod = require("sdk/page-mod"); // import the self api var self = require("sdk/self"); // create a page-mod // it will run a script whenever a ".org" url is loaded // the script replaces the page contents with a message pagemod.pagemod({ include: "*.org", contentscriptfile: self.data.url("jquery-1.7.min.js"), contentscript: '$("body").html("<h1>page matches ruleset</h1>");' }); note, though, that you can't load a script from a web site. the script must be loaded from data. communicating with the content script your add-on script and content scripts can't directly access each other's variables or call each other's functions, but they can send each other messages. to send a message from one...
Modules - Archive of obsolete content
illa-specific code (e.g., if porting to the browser). the use of eval() will probably not be of concern because it is only being used on the exported_symbols array which should not depend on user input. function importmodule (thatobj) { thatobj = thatobj || window; var exported_symbols = [ // put the symbols here ]; // your code here... ...
...e: (assuming neither 'i' nor 'thatobj' is being exported!) for (var i=0; i < exported_symbols.length; i++) {thatobj[exported_symbols[i]] = eval(exported_symbols[i]);} } or for one-time-only usage of a module: (function (thatobj) { thatobj = thatobj || window; var exported_symbols = [ // put the symbols here ]; // your code here... ...
Preferences - Archive of obsolete content
ist of preferences in about:config (where available). preferences that have a user value are bold, and those that don't have a user value are printed in normal font. you can get both trees using the nsiprefservice.getbranch() and nsiprefservice.getdefaultbranch() functions. see below for details. the effect of default preferences on get methods when one of the get methods of nsiprefbranch (assuming it's a branch of the tree with current values) is called, it does the following: checks whether the current tree has a value for the preference and whether or not the preference is locked. if there's a value of the correct type (for example, getboolvalue() expects a value of type nsiprefbranch.pref_bool), and the preference is not locked, the method returns that value. if there's a value of...
...tion that can be defined per preference and has the old value and along with the new value of the preference. it also uses a technique so you can just do prefs.preferencename.setval('blah') instead of having to branch.setcharpref etc. ...
Rosetta - Archive of obsolete content
they usually deal with – imagine, for example, the meaning of a c pointer within a html page! nevertheless, the increasing computational power of modern browsers together with the introduction of typed arrays in ecmascript allow us, in theory, to build full virtual machines in pure ecmascript. therefore, it is also possible, in theory, to use ecmascript for a smaller task: parsing exotic programming languages (i.e., creating compilers). beyond ecmascript this is not the place for showing a full compiler written in ecmascript. we can show, however, a possible way to start from. the following code is nothing but the base for an extensible collection of compilers. but by default, no compilers are loaded. it relies on the fact that unrecognized mime types will be simply ignored: this allows u...
....h> int main () { printf("hello world number 1!\n"); return 0; } </script> <script type="text/x-c" src="example.c"></script> </head> <body> <p>lorem ipsum</p> <script type="text/javascript"> rosetta.translateall(); </script> </body> </html> example.c: c example #include <stdio.h> int main () { printf("hello world number 2!\n"); return 0; } if creating a compiler for the c programming language, as in the example above, can really look a huge task, there are many dialects of ecmascript which could be easily translated to standard ecmascript. the previous example shows a possible solution for all these cases, from the simplest to the hardest one. mime types here is a short list of the mime types associated to some programming languages: language mime type ...
JavaScript timers - Archive of obsolete content
val() cancels repeated action which was set up using setinterval(). clearimmediate() cancels the immediate actions, just like cleartimeout() for settimeout(). 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. in javascript programming language, all daemons are processes created by javascript timers or by a worker instantiation. here are some code snippets which simplify and abstract the management of daemons. requestanimationframe() requestanimationframe() tells the browser that you wish to perform an animation and requests that the browser schedule a repaint of the window for the next animation frame. the method takes as a...
...that the browser schedule a repaint of the window for the next animation frame. the method takes as an argument a callback to be invoked before the repaint. performance.now() performance.now() returns a timestamp, measured in milliseconds, accurate to one thousandth of a millisecond. this timestamp is equal to the number of milliseconds since the navigationstart attribute of the performance.timing interface. date.now() date.now() returns the number of milliseconds elapsed since 1 january 1970 00:00:00 utc. using javascript timers within workers workers can use timeouts and intervals just like the main thread can. this can be useful, for example, if you want to have your worker thread run code periodically instead of nonstop. functions available to workers in addition to the standa...
Tree - Archive of obsolete content
i++) { if (treeview.iscontainer(i) && !treeview.iscontaineropen(i)) treeview.toggleopenstate(i); } to collapse all tree nodes just change the condition: var treeview = tree.treeboxobject.view; for (var i = 0; i < treeview.rowcount; i++) { if (treeview.iscontainer(i) && treeview.iscontaineropen(i)) treeview.toggleopenstate(i); } getting the text from the selected row assuming the given <tree>: <tree id="my-tree" seltype="single" onselect="ontreeselected()"> use the following javascript: function ontreeselected(){ var tree = document.getelementbyid("my-tree"); var cellindex = 0; var celltext = tree.view.getcelltext(tree.currentindex, tree.columns.getcolumnat(cellindex)); alert(celltext); } getting the tree item from the focused row assuming <tree...
... unselected (for example, a multi-select tree). getting the cell from a mouse click your first choice is likely to try <treecell onclick="yourfunc();"/> or something similar. but this will not work. you can't add event handlers to <treecell>. instead, you can add the event handler to the <tree> element. you can then use the event and some utility methods to find the <treecell>. ...
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. stringview a library that implements a stringview view for javascript typed arrays. this lets you access data in typed arrays using c-like string functions. r...
...se another scripting language you might expect that most of the browsers will not recognize it. nevertheless, the increasing computational power of modern browsers together with the introduction of typed arrays in ecmascript allow us, in theory, to build full virtual machines in pure ecmascript. therefore, it is also possible, in theory, to use ecmascript for a smaller task: parsing exotic programming languages (i.e., creating compilers). this snippets shows a possible way to start from. browser-oriented code tabbed browser code (firefox/seamonkey) basic operations, such as page loading, with the tabbed browser, which is the heart of mozilla's browser applications cookies reading, writing, modifying, and removing cookies page loading code used to load pages, reload pages, and listen...
Deploying a Plugin as an Extension - Archive of obsolete content
we'll cover the basics. the id specifies a unique id that uniquely identifes this extension of the form. if you have written extensions for firefox in the past, you'll notice that ...
...we'll cover the basics. the id specifies a unique id that uniquely identifes this extension of the form. if you have written extensions for firefox in the past, you'll notice that we no longer requir...
Jetpack Processes - Archive of obsolete content
it. createsandbox() this creates a new javascript sandbox and returns its global scope. this global scope does not contain privileged apis, or any non-standard javascript objects for that matter, though new globals can be endowed by simply attaching them to the global scope as properties. evalinsandbox(asandbox, ascript) evaluates the given script contents in the given sandbox's global scope. at minimum, javascript 1.8.1 is used. individual lines of the form //@line 1 "foo.js" can be used to specify filename and line number information for debugging purposes. gc() synchronously performs garbage collection. handles messages that communicate between the browser and jetpack process may contain only serializable (json) data and handles. a handle can be used to provide context for messages. eith...
...te. oninvalidate a callback to call when the handle is garbage collected, either through an explicit call to invalidate() or being unrooted and then unreachable. the callback is only called from the process that the handle was not garbage collected in. read-write. special messages core:process-error(context) when the jetpack process crashes, this message is sent to the parent. if a crash report minidump is available, the context.dumpid property will list the minidump id of the crash report that was collected. core:exception(error) when an exception occurs in a jetpack script and is not caught, this message is sent to the parent. the error object contains the following properties: filename, linenumber, and message. history see bug 556846 and bug 578821 for details. sample code for example c...
Adding sidebars - Archive of obsolete content
you can choose an obscure key combination that won't conflict with firefox, such as ctrl+shift+(some letter), but there's no way of knowing if any other extension uses that same combination as well. shortcut keys can be very valuable for advanced users, but don't rely on them. the xul page for the sidebar can hold any content you want and it's no different from other xul windows or overlays. one minor difference is that the xul sidebar should be defined using the « xul reference « root element instead of window or dialog. the load event is fired every time the sidebar is opened, and unload every time it's closed, so you can use those for initialization and clean up . another, more important difference to take into account is that users can resize the sidebar to their liking, and in most c...
...ause you can't have an background image stretch using css. a less common use for the stack element is to use the left and top attributes on its children in order to have absolute positioning for the content on the layers. this kind of positioning can be useful for various artistic effects, as well as some type of desktop-like or dashboard-like interface, where items are located in positions determined by the user, and they can overlap with each other. this can become complicated very easily, though. remember that you can't have flexibility and absolute positioning at the same time. trees the bookmarks and history sidebars in firefox use the « xul reference « element to show their content. trees are another strong option when you need to show a great amount of information in a compact pr...
Appendix A: Add-on Performance - Archive of obsolete content
note: see the newer article performance best practices in extensions for more up-to-date information about how to optimize the performance of your add-on. add-ons can have a noticeable performance impact on firefox. this is evident when opening a firefox profile that has many add-ons installed; some profiles can take minutes to load, which is a serious inconvenience for users that gives them a negative view of firefox. add-on developers need to make sure that they minimize their add-ons' performance impact, and here are a few simple guidelines that should be followed to achieve that. startup this is the area where add-ons have the most noticeable impact. most add-ons use the load event handler in the main overlay to initialize their objects and sometimes read files or even fetch remote da...
...ir objects and sometimes read files or even fetch remote data. the problem with the onload event is that it runs before the main window becomes visible, so all handlers need to complete before the user can see the window. an add-on can normally add a few hundred milliseconds to startup time because of the load handler, and it's not hard to figure out what having several add-ons will do. luckily, minimizing your startup time is easy, if you follow these guidelines: do not load or run code before it’s needed. add-ons can have extra features that are only available depending on user preferences. other add-ons have most of their features depend on a user being logged in to a service. don’t load at startup something you won’t need at the time. javascript code modules. use them. jsm prov...
Appendix B: Install and Uninstall Scripts - Archive of obsolete content
done"; if (!application.prefs.getvalue(firstrunpref, false)) { application.prefs.setvalue(firstrunpref, true); // all the rest of the first run code goes here. } } in this case you would need to declare the first run preference in your default preferences file, with a default value of false. you should also change the preference value before you run any other first run code. keep in mind that the user could have set multiple firefox windows to open at startup, so there's a race condition on which window will run the first run code. if you need to run code on every update, or some of them, the code would be very similar. instead of a boolean preference, it would be best to use a string preference with the last-installed add-on version. and then do a version comparison to decide ...
...lly going to be closed. then you'll have reasonable certainty that the add-on will be removed and you can perform any cleanup operations safely. for this, you need to add an observer for the quit-application topic. this is when you'll know the application will close. then you can check the flag you set up on the first stage and perform any necessary deletions. you shouldn't perform very time-consuming operations here, at least not without telling users what is going on. ...
Setting Up a Development Environment - Archive of obsolete content
$(build_dir)/meta-inf/zigbert.sf # the signing key /certificate file. signature_rsa_file = $(build_dir)/meta-inf/zigbert.rsa# the signing key /certificate file. signature_files := $(signature_extra_files) \ $(signature_rsa_file) $(signature_files): $(build_dir) $(xpi_built) @signtool -d $(signature_dir) -k $(cert_name) \ -p $(cert_password) $(build_dir) keep in mind that your password should not be in your makefiles, and you must be very careful with the certificate information. ideally this should be handled by a single person, and only done near the end of the release process. you should also have a different make command, such as make signed in order to distinguish the signed and unsigned development builds. firefox profile management it is good develo...
...e in it, although that's not completely reliable. javascript debugger the name says it all. the venkman javascript debugger is a great way to trace execution of your javascript code. to debug extension and browser code, right-click on the loaded scripts panel and uncheck exclude browser files. the list of loaded scripts will grow long to include all of the scripts in firefox. having our file naming conventions prove very useful in this case. you can set breakpoints, step in and out of methods, and even get profiling information from javascript execution. you can inspect variables, keep track of watch expressions, and evaluate arbitrary js at any point in execution. this extension has seen little maintenance in quite some time, so it is very buggy. it is specially unreliable when debugging...
User Notifications and Alerts - Archive of obsolete content
notification box by default, so you don't need to do any overlaying. the notificationbox elements can be obtained from the gbrowser object. in this case we don't pass any arguments to getnotificationbox so that we get the notification box that corresponds to the tab currently on display. the appendnotification method takes the message, id, image (32x32), level and buttons. the level argument determines the "strength" of the message, indicated by its background color when it is displayed. you should look for the level that better fits your message, and use the lowest applicable level, to prevent the user from getting used to dismissing high-level notifications. the buttons are represented by simple js data objects. this is all explained in detail in the notificationbox page. notification boxe...
...we do this when we need to handle clicks on the alert box. the image can have any size, but it is recommended that you use a medium, fixed size. the main disadvantage of using alerts is that support for the alerts service is not guaranteed for all platforms and firefox versions. support for windows has existed since firefox 2. for mac os x, su...
Security best practices in extensions - Archive of obsolete content
the document to find out how to avoid such pitfalls. for more information, refer to the evalinsandbox section. the sidebar: a use case the sidebar in firefox is designed to hold both chrome (privileged) content and web (nonprivileged) content, the latter being in the form of web pages. these web pages can come from a server, or come from local html files bundled with the extension. for pages coming from the server, you need to take steps to ensure that the content can not call back into the web browser and run malicious code. the main way to do this is by creating an iframe or browser element in the sidebar, and loading your content there. give the element a type="content" attribute, which essentially sandboxes the code there and blocks callback rights into chrome. using eval() in an exte...
...his approach is preferable because it provides users with a familiar interface for interacting with logins, via the firefox password manager. when users clear logins using the "clear recent history" option, it will include your extension's data. apis and other data handling web content is more than just pages, and more and more add-ons are interacting with web services via an application programming interface (api). many of the items talked about so far in this document apply in this sphere, but here are some additional tips: api providers should use the https protocol, which provides better protection for data passed over the network. json has become a popular data format for return formats for web services. be sure to read using native json to find out the correct way to handle it. a...
Session store API - Archive of obsolete content
ion applies to firefox 3.6 and later. firefox 3.6 knows how to save session store data when the last browser window closes, even if there are still other windows open. similarly, it can now restore the user's session while in that state. in other words, it's now possible for sessions to be restored even without the browser quitting and being relaunched. this is something you may need to keep in mind if you rely on the behavior of the session store system. the session restore process the exact sequence of events that occurs when a session is being restored is: a session state is about to be restored. this can be on startup or in response to undo close tab, since closed tabs are restored as single-tab sessions. new windows are opened as required (one for each window that was saved in th...
...inished loading, text fields and scroll state are restored. finally, the sstabrestored event is sent. if you want to set permissions or otherwise manipulate a restored tab before the page is loaded into it, you should watch sstabrestoring. if you want to do something after the page is loaded, you should watch sstabrestored. both events are always sent for each tab being restored. you can determine which tab is being restored by looking at the event's originaltarget field. there's not really a way to determine when the last tab has been restored unless you determine how many tabs need to be restored then count the sstabrestored events. this section provides a few simple examples of how to make use of the session store api. saving a value with a tab the following code will attach a ke...
Promises - Archive of obsolete content
ronous reading and writing of add-on-specific json * data files. * * @param {string} the basename of the file. * @param {object} a json-compatible object which will be used in place * of the file's data, if the file does not already exist. * @optional * * @return {promise<jsonstore>} */ function jsonstore(name, default_={}) { return task.spawn(function* () { // determine the correct path for the file. let addon = yield aom.getaddonbyid(addon_id); let dir = yield addon.getdatadirectory(); this.path = os.path.join(dir, name + ".json"); // read the file's contents, or fall back to defaults. try { this.data = json.parse( yield os.file.read(this.path, { encoding: "...
...fall back to defaults. try { this.data = json.parse( yield os.file.read(this.path, { encoding: "utf-8" })); } catch (e if e.becausenosuchfile) { this.data = json.parse(json.stringify(default_)); } // create a saver to write our json-stringified data to our // path, at 1000ms minimum intervals. this.saver = new deferredsave(this.path, () => json.stringify(this.data), 1000); return this; }.bind(this)); } /** * immediately save the data to disk. * * @return {promise} a promise which resolves when the file's contents * have been written. */ jsonstore.prototype.flush = functi...
Index of archived content - Archive of obsolete content
ult preferences deploying a plugin as an extension developing add-ons displaying web content in an extension without security issues downloading json and javascript in extensions enhanced extension installation extension etiquette extension library extension packaging extension samples extension theming guidelines extension versioning, update and compatibility extensions support in seamonkey 2 firefox addons developer guide hiding browser chrome hotfix extension how to convert an overlay extension to restartless inline options install manifests installing extensions and themes from web pages inte...
...s tamarin-central rev 703:2cee46be9ce0 tamarin roadmap tamarin build documentation tamarin mercurial commit hook the download manager schema the life of an html http request the new nsstring class implementation (1999) tracevis transforming xml with xslt:mozilla xslt transforming xml with xslt:the netscape xslt treehydra treehydra build instructions treehydra manual tuning pageload urischeme uris and urls uriloader using addresses of stack variables with nspr threads on win16 using c...
Images, Tables, and Mysterious Gaps - Archive of obsolete content
acement of images within a line box, and the placement of a line box within a table cell. first a basic line box containing text, shown in figure 3. the most crucial part of figure 3 is the baseline (represented by the blue line), and its placement within the line box. the baseline's exact placement is dependent on the "default" font for the line box (represented by the red box), which is determined by the value of font-family for the element that contains the line box. it isn't possible for an author to change the baseline's position directly, so wherever it ends up is where it will be. the space below the baseline is referred to as "descender space" since that's where the descenders in lowercase letters like "j", "y", and "q" are drawn. figure 4 shows what happens when we add an image to...
...re going to go through two basic ways to address the problem in strict documents, and a number of ways to call on these "fixes." setting images to be blocks the first choice, and one that will work for most graphically-intense designs, is to convert the image from being an inline element to a block-level element. do that, and it no longer generates a line box, and so the problem goes away-- assuming that the image is the only thing that occupies that table cell. in the simplest case, we might add a style like this: td img {display: block;} consider this rule when applied to the following markup: <table cellspacing="0" cellpadding="0" border="0" width="500"> <tr><td><img src="nav1.gif"><img src="nav2.gif"><img src="nav3.gif"><img src="nav4.gif"><img src="nav5.gif"></td></tr> <tr><td styl...
Notes on HTML Reflow - Archive of obsolete content
s significant. contentchanged indicates that the content corresponding to the target frame has changed somehow; for example, the text associated with a text frame has been modified. in reality, the only frame that responds to this sort of reflow is the block frame. the block frame treats this sort of change as a `full reflow' (i.e., as a resize). this makes me believe that we could probably eliminate this class altogether. stylechanged indicates that the stylistic information corresponding to the target frame has changed; for example, the font size has increased. this causes the frame to mutate the reflow state's reason to stylechange, which is propagated recursively to the entire subtree beneath the target frame. reflowdirty indicates that container frame has decided to...
...the font size has increased. this causes the frame to mutate the reflow state's reason to stylechange, which is propagated recursively to the entire subtree beneath the target frame. reflowdirty indicates that container frame has decided to coalesce several incremental reflows targeted at its children into a single reflow. the container frame maintains the necessary state to determine which children must be reflowed. userdefined, for "special situations". currently, this is only used by the viewport frame to schedule a reflow to reflow all of the viewport's fixed-position frames. we should probably try to eliminate it. an incremental reflow may damage other parts of the frame hierarchy; for example, changing the size of the font used in a specific p...
Source Navigator - Archive of obsolete content
ion/definition of a method/function to look up... but on the other hand mxr can only allow you to type in the name for it to generate a long list of occurances. (as i understand. let me know if this is wrong..) it can generate a class hierarchy quite easily (unfortunately, not for classnames which are defined by macro.) installing source navigator in ubuntu execute the following line in a terminal window: sudo apt-get install sourcenav this should install source-navigator. one can check whether the installation is complete by executing: $ which snavigator /usr/bin/snavigator importing the source execute the following: snavigator. this triggers a splash screen, followed by a "source-navigator projects" dialog as the following: i've already created a new project bin.proj before docum...
...illa</tt> add directory (where your source files reside in -- i understand that the label here is not so self-explanatory...): <tt>~/moz1.9/mozilla</tt> (because i saved my source at ~/moz1.9/mozilla.) remember to ensure that "include subdirectories" and "build cross-reference database" are checked. then click "ok". the snavigator then begins to scan your source directories. this takes a few minutes. now you can enjoy searching the mozilla code in a faster speed. using source navigator (more later) opening a project open a terminal. type <tt>snavigator</tt> followed by striking enter. this shows the "source-navigator projects" dialog. choose the project file that you've just created and then click "open...". source navigator then loads the database and then display the following symb...
Autodial for Windows NT - Archive of obsolete content
lookup failure for example, the system will try to dial. however, if the user has both a modem and a lan card, the service will be less reliable for them. the only way the service will work in this case is if the internet address has been accessed some previous time via the modem. these addresses are stored in an os database, the ras autodial addresses db, and a set of heuristics are used to determine if an address is already in the database or not. essentially, if some address at domain.com is in the database, then any address at domain.com is considered to be in the database. also, if any address that starts with www is in the database, then any other address that begins with www is considered to be in the database. it is important to note that the function of this system service in no way ...
... which allows our interaction with the autodial service to work a little more reliably. i don't see a need to expose this pref in the ui, but perhaps it should be there. or pehaps we should assume mozilla users can configure the autodial service and disable the helper by default, but netscape users need a little more help, and enable it for them. original document information author(s): benjamin chuang last updated date: october 2, 2002 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creative commons license | details. ...
Creating a Firefox sidebar extension - Archive of obsolete content
the chrome manifest creates a lookup for all the resource types used by the extension. the manifest also tells firefox that the extension has an overlay that needs to be merged in...
...the chrome manifest creates a lookup for all the resource types used by the extension. the manifest also tells firefox that the extension has an overlay that needs to be merged into the browser. for...
In-Depth - Archive of obsolete content
isplayed top to bottom and left to right. this will flip it around so items inside of this box will be displayed bottom to top and right to left. this is useful for, say, putting the navigation controls (back button) on the right hand side of the toolbar. values: normal, reverse -moz-image-region this is useful for dividing up an image into multiple smaller images. it uses a rect() object to determine the clipping region. check out the section on organizing images for more information. example: -moz-image-region: rect(168px 69px 189px 46px); -moz-opacity makes boxes semi-transparent. it takes a decimal value, 0.00 is invisible and 1.00 is totally visible. how do i know what to modify? now that you've got everything extracted and you know how to modify items, you might be wondering, how do i ...
... -moz-image-region: rect(294px 46px 315px 23px); } #button-send:hover:active { -moz-image-region: rect(294px 69px 315px 46px); } #button-send[disabled="true"] { -moz-image-region: rect(294px 92px 315px 69px) !important; } the properties for rect are listed in a clockwise fashion - top, right, bottom, left. adding an image to the right of a toolbar this tutorial is done with mozilla 1.2 in mind. the layout of files can and probably will change over time, but the basics should remain the same. by default, mozilla 1.2 doesn't support images on the right hand side of the toolbars, but that can be changed with some xbl hacking. place this xml file in \classic\skin\classic\communicator\toolbar\toolbarbindings.xml (you will need to create the sub directory). what this file does, is it takes ...
Download Manager preferences - Archive of obsolete content
s run; 1 indicates that the downloads should be paused but will not automatically resume when the application is restarted; and 2 indicates that the downloads will be canceled on quit. default value is 0 (resume on next launch). browser.download.manager.resumeonwakedelay an integer value indicating the number of milliseconds to wait after the system wakes up from sleep before resuming downloads. default value is 10000. browser.download.manager.retention indicates how long downloads are retained in the download manager's queue after the download is completed successfully. 0 indicates that the download should be removed upon completion; 1 indicates that completed and canceled downloads should be removed on quit; 2 indicates that downloads should never be removed au...
...nce is missing, the value 0 is used. browser.download.manager.scanwhendone a boolean value that indicates whether or not to perform virus scans after downloads are complete. on windows xp sp2 and windows vista, this value also indicates whether downloaded files trigger a security warning upon launch. default value is true. browser.download.manager.showalertinterval the minimum number of milliseconds that must elapse between download complete alerts; if two downloads complete within this amount of time, only one alert is displayed. default value is 2000 (2 seconds). browser.download.manager.showalertoncomplete a boolean value that indicates whether or not an alert should be shown when downloads complete. default value is true. browser.do...
Drag and Drop JavaScript Wrapper - Archive of obsolete content
be defined when you want something to happen when an object is dropped. the first argument is the event object and the second is the data being dragged. the third argument is the drag session. getsupportedflavours() this function should return a list of flavors that the object being dragged over can accept. this function takes no arguments. this function is necessary so that the wrapper can determine the best flavour to pass to the other functions. for an observer that is observing an element that can start a drag, you should define at least the ondragstart function. for elements that can have objects dropped on them, you should define ondragover, ondrop and getsupportedflavours (and, if desired, ondragexit). the type of data being dragged is stored as a set of flavors. often, a dragged obj...
...ight use it to change the appearance of the element as it is being dragged over. in many cases the function can do nothing. it must be defined for elements that accept dragged data however. next, the ondrop function should be created. its second argument is the transfer data object that holds the data being dragged. by the time ondrop is called, the wrapper has called getsupportedflavours to determine the best flavour for the drop, so the transfer object only contains the data for the best matching flavour. the transfer object has two properties, data which holds the data and flavour which holds the flavour of the data. once you have the data, you can add it to the element is some way. for example, you might set the value of a textbox. var textobserver = { ondrop : function (event, transfer...
Block and Line Layout Cheat Sheet - Archive of obsolete content
e frame is to have a frame tree that is "too deep". (see nsframe::isframetreetoodeep().) ns_frame_has_dirty_children ns_frame_has_view ns_frame_independent_selection ns_frame_is_special nsblockframe mflags these flags are the private flags that are meaningful to block frames. ns_block_shrink_wrap causes the block to "shrink-wrap" around its content. this means the block will determine its children's width and make its content area that wide. finally, it will add padding and border to determine the final width. is this where the "tending towards zero width" stuff comes in? ns_block_no_auto_margins ns_block_margin_root indicates that this is a frame from which child margins can be calculated. the absence of this flag implies that child margin calculations should ignore the ...
...tate the current state of reflow, built up as reflow recursively descends the frame tree. this is "passed in" to a child frame from its parent, and provides the constraints in which the child frame must size itself; e.g. the width and height available to the child frame. mcomputedwidth mcomputedheight mcomputedmargin mcomputedborderpadding mcomputedpadding mcomputedoffsets mcomputedminwidth mcomputedmaxwidth mcomputedminheight mcomputedmaxheight given the current container frame and the style applied to the child, these values are the resolved values for the child frame's box. nshtmlreflowmetrics the structure that is "filled in" by a frame during reflow, and is used to communicate the frame's desired size information back to its container. mmaximumwidth the maximu...
Content states and the style system - Archive of obsolete content
t gecko uses to implement the various state-dependent in css (examples would be :hover, :active, :focus, :target, :checked). we will focus on describing how changes in content state are handled. generally, whenever a node's content state changes, style has to be reresolved (recomputed) for that node and all of its descendants. this is an expensive operation, however, so the style system tries to minimize the number of style reresolves it does. to this end, when a <code>contentstateschanged</code> notification is dispatched for a content node the first thing that's done is to is to check whether the content state change something could affect any styles. this is done by walking the list of all css2.1 simple selectors in all style sheets applied to the page that have a state-dependent pseudo-...
... sheets applied to the page that have a state-dependent pseudo-class as part of the selector. this list is created during the parsing of the stylesheets involved. for each selector in this list we check whether it might have stopped matching the node or started matching it. if that has happened, then the style could depend on the state that changed and we have to reresolve style. the way we determine whether the selector might have stopped or started matching the node is by just checking whether it matches with the caveat that all the state-dependent pseudo-classes corresponding to the states that changed must be treated as matching (whether they actually do and whether they're negated or not). this is needed to catch both selectors that now match and selectors that no longer match. for exa...
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
the section on stream converters). nsdocumentopeninfo implements nsistreamlistener and proxies the nsistreamlistener calls over to the "real" stream listener once one is chosen. this is the class that handles deciding where the data from the load should go. supporting roles necko this is the mozilla networking library. this handles actually going out and getting the data. it also handles determining the mime type of the data, which is used to decide who gets the data. category manager this is used in a last-ditch attempt to find a content listener. nsiuricontentlistener implementations we try to find one of these which can handle data of the type we're looking at (that is, it can give us an nsistreamlistener to pump data into). most often, the one we find is nsdsuricontentlistener, which ...
...the prose description below has been updated. the changes do not affect functionality and the step numbers in the diagram are still accurate. guided tour during startup and component initialization, components register themselves with the uriloader via registercontentlistener. these registered listeners are used later during content dispatch. api call...
Layout FAQ - Archive of obsolete content
is there a framework for this? if you're on linux, then you can try using jprof. instructions are available at jprof readme on more recent linux versions sysprof can also be used. also lists some profiles. how do you find out if there are any reflows that are pending and wait to show the view until afterwards, but if none are pending, show the view immediately? what is the best way to determine whether there are any pending changes? on the reflow branch you could check the dirty and dirty_children framestate flags. that won't help with pending style changes, but it'll work to detect cases when the popup or something in it needs to be reflown. what are the lowercase items called "line"? block(body)(1)@035ff490 {120,120,8820,600} [state=00000010] sc=035ff264(i=2,b=0)< line 035...
...g display:table in the style rule with the "#main" selector or adding clear:both to it. why does move movement disappear when i use mouse events to click and drag? since the dragging action is involved, you might need to disable it. try using event.preventdefault() what is the purpose of the ns_lossyconvertucs2toascii() function? this function converts an nsastring to an nsacstring by assuming that all the 16-bit units are ascii and just dropping the high byte on them all. ...
Gecko Coding Help Wanted - Archive of obsolete content
take a look through lxr, and you'll realize that mozilla's source code is a big place. huge, actually. overwhelmingly large. you could spend years in it and still get lost. you're up for some adventure, though, and you're set to take the plunge. but where? where's a good place to start? someplace easy and straightforward, so you can get a feel for the lay of the code. reports in bugzilla can be deceptive, deceptively hard... or deceptively easy. so we've compiled a list of pointers —from the experts. there's plenty to do, and we sure could use the help. here are some fixes that are straightforward; they just need some time and attention: decomtamination convert weird, ugly and inefficient method signatures to more natural c++ method signatures. it's really improved code readabi...
...duced code size, and sped up performance. it's kind of tedious but it's extremely valuable and will help you learn the way around the codebase. we've done a lot, but there's a lot more to do. roc is willing to work closely with anyone with reasonable c++ experience to get them started on this. just send him mail. not up for coding yet? join the gecko bugathon and help save gecko engineers from imminent doom! original document information author(s): fantasai last updated date: may 4, 2004 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creative commons license | details. ...
Introducing the Audio API extension - Archive of obsolete content
ozframebufferlength) gets filled with those samples. once the buffer is full, the event mozaudioavailable is triggered. this event therefore contains the raw samples of a period of time. those samples may or may not have been played yet at the time of the event and have not been adjusted for mute or volume settings on the media element. playing, pausing, and seeking the audio also affect the streaming of this raw audio data. the mozaudioavailable event has 2 attributes: framebuffer: framebuffer (i.e., an array) containing decoded audio sample data (i.e., floats) time: timestamp for these samples measured from the start in seconds the framebuffer contains an array of audio samples. it's important to note that the samples are not separated by channels; they are all delivered together. fo...
...e obtained with mozcurrentsampleoffset()), where "a little" means something on the order of 500 ms of samples. for example, if working with two channels at 44100 samples per second, a writing interval of 100 ms, and a pre-buffer equal to 500 ms, one would write an array of (2 * 44100 / 10) = 8820 samples, and a total of (currentsampleoffset + 2 * 44100 / 2). it's also possible to auto-detect the minimal duration of the pre-buffer, such that the sound is played without interruptions, and lag between writing and playback is minimal. to do this start writing the data in small portions and wait for the value returned by mozcurrentsampleoffset() to be greater than 0. var prebuffersize = samplerate * 0.020; // initial buffer is 20 ms var autolatency = true, started = new date().valueof(); ... // ...
JavaScript crypto - Archive of obsolete content
eratecrmfrequest) signing and encryption keys are generated encryption private key is wrapped with public key of key recovery authority (kra) (passed in in the form of a certificate as part of the script, and checked against a pre-installed certificate copy in the local certificate database) the public keys, wrapped encryption private key, and text string from the script (possibly containing naming or enrollment info) are signed by the user signed blob is returned to the script script submits signed blob and any other necessary info to the ca/ra ca/ra verifies signature on signed blob ca/ra validates identity of user ca/ra sends wrapped encryption private key to kra kra sends escrow verification back to ca ca creates and signs certificates ca sends certificates back to the user (im...
...ure. even so, it's highly discouraged. pkcs11_pub_readable_cert_flag: this is the only flag most smart tokens should turn on. you can turn this flag on if: the certs on your token can be read without authentication and, the public key on your token can be found by id, modulus, or value and all your private keys have the associated public key. turning this flag on will illuminate a large number of password prompts for your token when looking up certs in communicator. pkcs11_mech_rsa_flag = 0x1<<0; pkcs11_mech_dsa_flag = 0x1<<1; pkcs11_mech_rc2_flag = 0x1<<2; pkcs11_mech_rc4_flag = 0x1<<3; pkcs11_mech_des_flag = 0x1<<4; pkcs11_mech_dh_flag = 0x1<<5; //diffie-hellman pkcs11_mech_skipjack_f...
Scripting - Archive of obsolete content
d into the prism chrome window very much like a firefox extension is loaded into the browser chrome window. it can contain the following functions: startup when the app starts, before the user interface is displayed. since the web application has not yet loaded, the window object is still undefined. preload just before the user interface is displayed. returning false causes the application to terminate. load after the main application windows has finished loading. the window object has been initialized and can be used. error if there is an error loading the main app page (e.g. the server is not accessible). shutdown just before the application terminates. prism exposes desktop integration features through an property of the window object called platform. the platform property implements the...
...currently, the webapp script also has access to full xpcom functionality, just like a firefox extension. this level of functionality is commonly called chrome-level privileges. ...
Prism - Archive of obsolete content
operating system and desktop than a typical web application running through a web browser. applications running in an ssb are therefore able to benefit from many of the advantages of the desktop and of the web at the same time. benefits separate process: web apps can hog memory or processor cycles or even bring down the whole browser in extreme cases. by running each app in its own process, we minimize the impact of any mishaps. we can also benefit from operating system tools that lets us view the memory/cpu consumption of a specific application. minimal user interface: a general-purpose browser ui is not necessary or appropriate for most web apps. it is more efficient to provide a ui that is specific to the application. this also cuts down on ui clutter (hence the term distraction-free ...
... a webapp bundle should contain a webapp.ini configuration file. the configuration file is a simple, ini-style text file that specifies some parameters about a web application. styling one of prism's goals is to make web applications feel more like desktop applications. one way to make the illusion seem more real is to use styling (or theming). prism supports a simple styling system that allows the user to add css files to the webapp bundle. scripting prism allows for some client-side web application customization. some simple objects and utilities are exposed to webapp scripts. host window prism provides a simple, scaled down browser window f...
Reading textual data - Archive of obsolete content
is article describes how to read textual data from streams, files and sockets. in order to read textual data, you need to know which character encoding the data is in. files and network sockets contain bytes, not characters - to give these bytes a meaning, you need to know the character encoding. xxx: document nsiunicharstreamlistener (gecko 1.8) xxx: also document nsistreamlistener here? determining the character encoding of data if you have a network channel (nsichannel), you can try the contentcharset property of it. note that not all channels know the character encoding of the data. you can fallback to the default character encoding stored in preferences (intl.charset.default, a localized pref value) when reading from a file, the question is harder to answer. using the system charact...
...nents.interfaces.nsifileinputstream); fis.init(file, -1, -1, 0); var lis = fis.queryinterface(components.interfaces.nsilineinputstream); var linedata = {}; var cont; do { cont = lis.readline(linedata); var line = converter.converttounicode(linedata.value); // now you can do something with line } while (cont); fis.close(); see also writing textual data joel on software: the absolute minimum every software developer absolutely, positively must know about unicode and character sets ...
Same origin policy for XBL - Archive of obsolete content
the same origin policy used for xbl documents is different from the policy used for other content. this article provides a description of how the same origin policy for xbl works. when mozilla needs to decide whether or not xbl is allowed to be loaded, it looks at the nsiprincipal originating the load and the nsiuri to be loaded. 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. for inline stylesheets (<style> and style attributes), the principal of the element node involved (meaning the <style> element or the element whose style at...
... <style> element or the element whose style attribute is being looked at). for the nsidomdocumentxbl interface's nsidomdocumentxbl.addbinding() and nsidomdocumentxbl.loadbindingdocument() methods, the originating principal is the one of the script making the call, or the principal of the document the call is made on if there isn't a script. checks performed once the originating principal is determined, checks are done to make sure the load should be allowed. the checks performed are: if the principal originating the load is the system principal, the load is allowed. a call to checloaduriwithprincipal() is done to make sure the principal is able to link to the given uri in the first place. a content policy check is performed. if the uri is a chrome: uri, the load is allowed. note that step 2...
Space Manager High Level Design - Archive of obsolete content
wise clean lines, and the space manager facilitates the detection of this. data model class/component diagram nsspacemanager: the central point of management of the space taken up by floats in a block nsbanddata: provides information about the frames occupying a band of occupied or available space nsblockbanddata: a specialization of nsbanddata that is used by nsblockreflowstate to determine the available space, float impacts, and where floats are cleared. essentially a css-specific wrapper for generic nsbanddata. bandrect: keeps the bounds of a band, along with the frames associated with the band. bandrects are a linked list (provided by prcliststr super-class) and also provide some geometry-management methods (splitvertically, splithorizontally) and some methods that query or man...
...s setup in the blockreflowstate's constructor based on the space manager passed in and computed content area). blockbanddata then gets the band data from the space manager via a call to the space manager associated with the blockbanddata instance. the blockbanddata then walks the collection of trapezoids that were returned by the spacemanager method getbanddata (as nsbanddata wrappers) and determines the right-most edge of the available space. the blockreflowstate then stores this available space rect for use in the rest of the reflow chain. use case 4: propagation of float damage: detecting and handling float damage this process is driven by the block frame. a non-dirty line is encountered by the block frame in reflowdirtylines block frame calls its propagatefloatdamage method the ...
Supporting private browsing mode - Archive of obsolete content
ases are re-activated. the temporary cookie and local storage databases start out empty. extensions that may record potentially private information may wish to hook into the private browsing service so that they can avoid saving personal information when private browsing mode is enabled. doing this is quite easy, using the nsiprivatebrowsingservice interface. detecting private browsing mode determining whether or not the user is currently in private browsing mode is simple. just check the value of the privatebrowsingenabled attribute on the nsiprivatebrowsingservice service. var pbs = components.classes["@mozilla.org/privatebrowsing;1"] .getservice(components.interfaces.nsiprivatebrowsingservice); var inprivatebrowsingmode = pbs.privatebrowsingenabled; if (!inprivatebro...
...browsing mode may only be detected by chrome code, such as extensions; web content cannot detect whether or not private browsing is in effect. detecting whether private browsing mode is permanent requires gecko 2.0(firefox 4 / thunderbird 3.3 / seamonkey 2.1) firefox 4 added support for having private browsing mode permanently enabled. the theme looks different in this scenario. to determine whether or not the browser is permanently in private browsing mode, you can look at the privatebrowsingmode attribute on the document root. its value is "permanent" if private browsing is permanently enabled for the session, "temporary" if private browsing is temporarily enabled, or not defined at all if private browsing mode isn't active. let docroot = document.documentelement; if (docroot.has...
Actionscript Performance Tests - Archive of obsolete content
as 565 564 0.2 time sunspider/access-fannkuch.as 366 362 1.1 time ... ...
...65 564 0.2 time sunspider/access-fannkuch.as 366 362 1.1 time ... # compare 2 builds with > 2 iterations $ ./runtests.py --iterations=10 --avm2=build2/avmshell sunspider/*.as test avm avm2 min : max avg min : max avg %diff metric ----------------------- ----------------------- ----- sunspider/access-binary-trees.as [ 567.0 : 585] 575.9 [ 564.0 : 580] 572.0 0.5 time sunspider/access-fannkuch.as [ 363.0 : 386] 370.0 [ 362.0 : 399] 371.8 0.3 time ... ...
Tamarin build documentation - Archive of obsolete content
der under your sdk/ndk top folder. make sure its name is just "openssl". then build as follows: - replace the makefile in the main folder with the one attached to this page. - change the variable android_device in the makefile (near line 65) to point to your sdk/ndk top folder. - find the two instances of "android-ndk" and make sure they match your ndk's name (they should already). - in a terminal window change to your /openssl folder and run make build_libs to create the necessary 'libcrypto.a' and 'libssl.a' static libraries. alternatively, run make, in which case the process will complete with errors when it tries to create the shared lib crt0.o: $ /android-public/android-ndk/toolchains/arm-eabi-4.4.0/prebuilt/darwin-x86/bin/../lib/gcc/arm-eabi/4.4.0/../../../../arm-eabi/bin/ld: crt...
...or 64-bit builds. there is also an aggregate target that will build both targets. note that, whereas before when you selected the aggregate target you got a 'shell' 32-bit executable and a 'shell64' 64-bit executable in the same folder, now because of the fix to bug 478714 you will get an 'avm' executable in two separate folders, /debug and /debug64 respectively. the command to build from the terminal is: $ cd tamarin-redux $ xcodebuild archs=ppc -project platform/mac/avmshell/avmshell.xcodeproj for a debug build, add '-configuration debug' (note the capital d and no "="). additional configurations are: debug_debugger, release and release_debugger. the resulting debug executable for the command above would be built at /platform/mac/avmshell/build/debug/avm. intel macs build correc...
Tuning Pageload - Archive of obsolete content
rofile to change these. to best understand what the following preferences affect, there are a few things you should know. the data flows in gecko as follows: network -> necko -> parser -> content sink -> content model -> rendering model -> layout -> painting. nglayout.initialpaint.delay this is a preference that specifies a delay, in milliseconds, after the data from the server has started coming in. during this delay, the page that's coming in is not painted, unless it ends up fully loaded before the delay expires. the idea here is twofold.this reduces ugly visual jitter as the new page comes in by not starting painting till after we have a bunch of the data.this makes overall page load time shorter by not doing extra repaints very early on. content.interrupt.parsing this preference...
...ference is used to increase responsiveness, especially on cached loads (where data comes into the parser in large chunks) content.max.tokenizing.time controls how often the sink interrupts the parser. the parser is interrupted at least every content.max.tokenizing.time microseconds, if it can be interrupted at all; bug 76722 may have more details on this part. content.switch.threshold determines how often we switch content sink modes. there are two modes. in mode a we interrupt the parser every content.max.tokenizing.time microseconds. in mode b we interrupt the parser every 3000 microseconds. every content.switch.threshold microseconds, we decide whether we should be in mode a or mode b. the decision is based on whether there were any user events on the relevant widget in the last co...
Binding Attachment and Detachment - Archive of obsolete content
fier. in the following example, a binding is referenced that will be attached to all html checkbox elements. input[type="checkbox"] { -moz-binding: url("http://www.mozilla.org/xbl/htmlbindings.xml#checkbox"); } bindings attached through css will only remain on the bound element as long as the element continues to match the style rule. if at any time a resolution of style on the element determines that a different binding should be attached, the old binding (and all bindings that it explicitly extends in its inheritance chain) will be detached. no bindings will be attached to elements that match the style rule, but are inside an element that has style display:none set. see bug 307098. whenever an element is removed from a document, any bindings attached via css loaded by the document w...
...ey have no effect on any other bindings attached using the dom. those bindings will stay installed. if new bindings are attached through css, they are installed after the dom bindings in the inheritance chain. for example, given a bound element with a binding chain of d1->d2 ->d3 ->s1 ->s2 ->s3 withs1 representing the binding attached via css. if a resolution of style on the bound element determines that a new bindingt should be attached, then the following binding chain is detached: s1->s2 ->s3 and the new binding is attached. the final inheritance chain is: d1->d2 ->d3 ->t when bindings are detached using element.style.mozbinding, any base bindings that were attached through the extends attribute on the binding will also be removed. in other words, a removal of element.style.mozbindi...
Creating XPI Installer Modules - Archive of obsolete content
esponds to the directory mozilla/bin/chrome/barley/content, where the main xul file and the other resources live once they are installed. 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. all of the resources described in this article are in the xpi archive and can be adapted for use in your own development. developing the resources needless to say, one of the first things you will have to create is the actual software you wish to make redistributable. the barle...
...note also the use of resource attributes specified in the contents.rdf file in the jar. it is the correspondence of this installation script, the resources themselves, and the contents.rdf file that registers the package and makes it available. c...
Install.addDirectory - Archive of obsolete content
install.adddirectory the install object's adddirectory method queues an entire directory for installation once performinstall is called. ...
... install.adddirectory the install object's adddirectory method queues an entire directory for installation once performinstall is called. ...
Windows Install - Archive of obsolete content
windows install example this example shows the installation of a xpi in which user profile information is contained. note the disk space verification, the editing of the windows registry, the writing to the installation log, and the error checking before either performinstall or cancelinstall is called. // this function verifies disk space in kilobytes function verifydiskspace(dirpath, spacerequired) { var spaceavailable; // get the available disk space on the given path spaceavailable = filegetdiskspaceavailable(dirpath); // convert the available disk space into kilobytes spaceavailable = parseint(spaceavailable / 1024); // do the verification if(spaceavailable < spacerequired) { logcomment("insufficient disk space: " + dirpath); logcomment(" required : " + s...
... { setpackagefolder(fprogram); err = adddirectory("", "6.0.0.2000110801", "bin", // dir name in jar to extract fprogram, // where to put this file // (returned from getfolder) "", // subdir name to create relative to fprogram true); // force flag logcomment("adddirectory() returned: " + err); // check return value if(err == success) { err = performinstall(); logcomment("performinstall() returned: " + err); } else cancelinstall(err); } else cancelinstall(insufficient_disk_space); // end main ...
toString - Archive of obsolete content
summary converts an installversion init object to a string. method of installversion object syntax string version = installversion.tostring ( initobj ); parameters the tostring method has the following parameter: initobj initobj is an installversion object whose init method has been called. returns the major, minor, revision, and build numbers represented as a single string. ...
...minor, revision, and build numbers represented as a single string. the init() function can input the version number as a single string or as a series of parameters representing the version numbers of the installation. ...
Properties - Archive of obsolete content
build least siginificant element of the installversion object.e.g. ...
... build least siginificant element of the installversion object.e.g. ...
addFile - Archive of obsolete content
ing operating system. if this parameter is blank or null, xpisourcepath is used. flags an optional field; reserved for future use. pass 0 as the default value. returns an integer error code. for a list of possible values, see return codes. description the addfile method puts the file in a temporary location. to move this and all other files to their final location, call the performinstall method after you've successfully added all files. note: if you are installing binary files on a macintosh, be aware that the binary format for those files must be applesingle if the resource information is to be installed properly. some file transfer programs will convert apple binaries to this format on transfer if you transfer them from a macintosh to a unix/windows machine before zipping ...
...rly. ...
refreshPlugins - Archive of obsolete content
list. returns nothing. description refreshplugins lets you register new plug-ins without having to restart the browser. when you use this method in an installation script, as the example below demonstrates, you can install new plug-ins and use them to display the requested media in a web page without interrupting the experience of the user. note that refreshplugins must be called after the performinstall method that initiates the actual installation. example // install dll into plugins // install xpt into components var xpisrc = "npmcult3dp.dll"; var xpisrc2 = "nsic3dpscriptablepeer.xpt"; initinstall( "cult3d plugin file", "@cycore.com/cult3d;version=1.0.0", "1.0.0"); setpackagefolder(getfolder("plugins")); addfile(xpisrc); addfile("",xpisrc2,getfolder("components"),""...
...l into plugins // install xpt into components var xpisrc = "npmcult3dp.dll"; var xpisrc2 = "nsic3dpscriptablepeer.xpt"; initinstall( "cult3d plugin file", "@cycore.com/cult3d;version=1.0.0", "1.0.0"); setpackagefolder(getfolder("plugins")); addfile(xpisrc); addfile("",xpisrc2,getfolder("components"),""); var err = getlasterror(); if (err == success) { err = performinstall(); if (err == success) refreshplugins(); } else cancelinstall(err); ...
XTech 2006 Presentations - Archive of obsolete content
ood markup and appropriate layout. microsummaries in firefox and on the web - myk melez microsummaries are regularly-updated compilations of the most important and timely information on web pages. this talk demonstrates how firefox will incorporate microsummaries into its ui, starting with bookmark labels. ...
... svg and canvas: graphics for web apps - vladimir vukićević this presentation examines some of the strengths and weaknesses of the html 'canvas' and svg for adding rich graphical capabilities to web applications. future browser graphics capabilities, both 2d and 3d, are also discussed. 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. etna, a wysiwyg xml relax ng- and gecko-based editor - daniel glazman this presentation describes etna, a new wysiwyg xml editor based on gecko, the relax ng parser and validator disruptive innovations implemented for it and its q...
collapse - Archive of obsolete content
if this attribute is not specified, the splitter will not cause a collapse. you should put a grippy element inside the splitter when it is used for collapsing. none no collapsing occurs. before when the grippy is clicked, the element immediately before the splitter in the same parent is collapsed so that its width or height is 0. after when the grippy is clicked, the element immediately after the splitter in the same parent is collapsed so that its width or height is 0. ...
...the splitter in the same parent is collapsed so that its width or height is 0. after when the grippy is clicked, the element immediately after the splitter in the same parent is collapsed so that its width or height is 0. both either the element immediately before the splitter, or the element immediately after the splitter can be collapsed, if the size of that element would fall below the minimum size due to the position of the splitter. ...
sizetopopup - Archive of obsolete content
« xul reference home sizetopopup type: one of the values below indicates how the menu width and the menupopup width are determined. if the sizetopopup attribute is left out or set to none, the menu will be its preferred width and the popup may extend outside of this width, unaffected by the maximum width of the menu itself. otherwise, the menu will size itself to at least the size of the popup. if the menu has a maximum width, the popup will also be this width. none the width of the popup will not be constrained to the size of the menu. ...
...wise, the menu will size itself to at least the size of the popup. if the menu has a maximum width, the popup will also be this width. none the width of the popup will not be constrained to the size of the menu. pref the preferred width of the menu label or button will be the size needed for the popup contents. this is the default value for menulists. always both the preferred and minimum width of the menu label or button will be the same as that necessary for the menupopup. ...
wraparound - Archive of obsolete content
...
... ...
Attribute (XUL) - Archive of obsolete content
losure buttonlabelextra1 buttonlabelextra2 buttonlabelhelp buttonorient buttonpack buttons checked checkstate clicktoscroll class closebutton closemenu coalesceduplicatearcs collapse collapsed color cols command commandupdater completedefaultindex container containment contentcontextmenu contenttooltip context contextmenu control crop curpos current currentset customindex customizable cycler datasources decimalplaces default defaultbutton defaultset description dir disableautocomplete disableautoselect disableclose disabled disablehistory disablekeynavigation disablesecurity dlgtype dragging editable editortype element empty emptytext deprecated since gecko 2 enablecolumndrag enablehistory equalsize eventnode events expr firstdayo...
...omepage href icon id ignoreblurwhilesearching ignorecase ignoreincolumnpicker ignorekeys image inactivetitlebarcolor increment index inputtooltiptext insertafter insertbefore instantapply inverted iscontainer isempty key keycode keytext label lastpage lastselected last-tab left linkedpanel max maxheight maxlength maxpos maxrows maxwidth member menu menuactive min minheight minresultsforpopup minwidth mode modifiers mousethrough movetoclick multiline multiple name negate newlines next noautofocus noautohide noinitialfocus nomatch norestorefocus object observes onbeforeaccept onbookmarkgroup onchange onclick onclosetab oncommand oncommandupdate ondialogaccept ondialogcancel ondialogclosure ondialogextra1 ondialogextra2 ondi...
Building accessible custom components in XUL - Archive of obsolete content
<code> @namespace url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"); grid.spreadsheet { border: thin solid; } grid.spreadsheet label { border-bottom: 1px solid black; border-left: 1px solid black; margin: 0; padding: 3px; } grid.spreadsheet description { color: black; background-color: white; margin: 0p...
...m programmatically using javascript whenever the user clicks a specific cell. but since the individual cells are not in the tab order, clicking on a spreadsheet cell and tabbing off will move to the spreadsheet's next sibling control, which is what we want. the only remaining issue is that when the spreadsheet regains focus (by pressing shift-tab, or cycling all the way around the tab order and coming back into the spreadsheet), we need to programmatically reset the focus to the previously focused cell. this is handled in the spreadsheet_focus function, which is registered as a handler for the focus event. <code> var gfocuscell = null; function install_handlers() { var spreadsheet = window.document.getelementbyid('accjaxspreadsheet'); spreadsheet.addeventlistener('focus', spreadsheet...
Reading from Files - Archive of obsolete content
doesn't trigger an error, and the string will just be returned containing as many characters as are available. you can use the available method to check if data is available for reading: var file = io.getfile("home", "sample.txt"); var stream = io.newinputstream(file, "text"); var str = stream.readstring(stream.available()); stream.close(); in this example, the available method is called to determine the number of available bytes for reading. note that this method returns the number of bytes available, not the number of characters available, because the file hasn't been read and parsed yet, so the actual number of characters isn't known yet. fortunately as a character is always at least one byte long in the default utf-8 encoding, the number of characters will always be equal to or smaller t...
... method will return the value as a number. read32 will read four bytes and return this as a single 32-bit integer. readfloat will read four bytes and interpret them as a floating point value. readdouble will read eight bytes and interpret them as a double floating point value. in this next example, the read32 method is used to read a 32-bit length from the file. then, this length is used to determine how many additional bytes of data to read. var length = stream.read32(); var data = stream.readstring(length); all values are read in big endian form, which means that integers are stored in the file with their higher bits first. for both the read16 and read32 methods, the values are always interpreted as unsigned values. if you want the sign bit to be interpreted such that negative values can ...
Introduction to XUL - Archive of obsolete content
chrome description to be moved without affecting the xul source. so it's just an indirection. someday, there will be a complete description of this mechanism at packages, but for now there's a good but somewhat out of date document at configurable chrome available for more information. scripting a xul interface is only a collection of disconnected widgets until it has been programmed. "programming" can be as simple as some javascript to tie the widgets together and perhaps to give them extra functionality, or as complex as application (c++) code which is free to do ... anything. this paper will concentrate on javascript, deeming application programming to be beyond its scope. javascript xul can contain html content, including javascript. javascript functions may be added in a fashion si...
... "*" is a wildcard signifying all elements with the attribute. xulelement xulelement extends element. interface xulelement : element { nodelist getelementsbyattribute(in domstring name, in domstring value); }; getelementsbyattribute functions as does its namesake in xuldocument, though this version returns only those elements which match the criteria and are descendants (in css selector terminology) of the given element. xulelement also supports other methods for hooking up broadcasters; a function performed automatically by the xul document loader and therefore not normally used in javascript. xul elements as mentioned above, a xul file is mostly an html file with xml syntax. a xul file may contain nothing but html elements and be completely functional. but xul defines several elem...
Extensions - Archive of obsolete content
n the popup is about to be shown. this function retrieves the menuitem with the id 'thumbnail-show' that was added by the extension and hides it if an image was not the target of the context menu. the popupnode property of the document holds the target of the context menu. for more details about hiding and showing items on a context menu, see hiding and showing menu items based on context. determining what element was context clicked for general information about how to determine which element was the target of the context menu, that is, the element that was context clicked, see determining what was context clicked firefox uses its own popupshowing event listener to adjust the items on the context menu. this allows the menu to have different commands for different types of targets. while ...
...extmenu global variable is set to an object which handles all of the functionality specific to the firefox context menu. specifically, this object is initialized with a set of properties that indiciate the type of object that was the target of the context menu. for instance, the 'onlink' property is set to true when a link was context-clicked. you may wish to use these properties instead of determining the type yourself, as the code already handles various special and complex cases that would take a lot of code to deal with manually. the following are the most common properties that you can check. an example follows. target the element that was context clicked. if the keyboard was used to open a context menu, this will be the focused element. ontextinput true if the ...
OpenClose - Archive of obsolete content
resized if necessary. closing a popup with the hidepopup method a popup menu is closed by the user pressing the escape key or by clicking somewhere outside the popup. for closing menupopups that use the menu tag, the button tag and the toolbarbutton tag, see closing menus above. to close a popup with a script, use the popup's hidepopup method. it takes no arguments. popup.hidepopup(); determining if a popup is open for menus, you can check the open property of the menu, button or toolbarbutton. if true, the menu is open. for other types of popups, the state property may be examined to determine whether a popup is open or not. this property is available for all types of popups, including menus, panels and tooltips. when a popup is closed, the state property has the value closed, where...
...er values, used while a popup is transitioning from being closed to open and vice versa. when a popup is about to be shown, the state property has a value of showing while it has the value hiding when the popup is about to be hidden. the former will occur during the popupshowing event, while the latter will occur during the popuphiding event. for example, you could use the state property to determine if a panel is already open. if the panel is open, you might want to avoid manipulating the user interface within the main window, as the user won't be directly interacting with it. ...
Property - Archive of obsolete content
« xul reference accessible accessibletype accesskey align allnotifications allowevents alwaysopenpopup amindicator applocale autocheck autofill autofillaftermatch boxobject browsers builder builderview buttons canadvance cangoback cangoforward canrewind checked checkstate child children classname clickselectsall clientheight clientwidth collapsed color columns command commandmanager completedefaultindex container contentdocument contentprincipal contenttitle contentview contentvieweredit contentviewerfile contentwindow contextmenu control controller controllers crop current currentindex currentitem currentnotification currentpage currentpane currentset currenturi custo...
...onmatches homepage hour hourleadingzero id ignoreblurwhilesearching image increment inputfield inverted is24hourclock ispm issearching iswaiting itemcount label labelelement lastpermanentchild lastselected left linkedpanel listboxobject locked markupdocumentviewer max maxheight maxlength maxrows maxwidth menu menuboxobject menupopup min minheight minresultsforpopup minwidth minute minuteleadingzero mode month monthleadingzero name next nomatch notificationshidden object observes onfirstpage onlastpage open ordinal orient pack pagecount pageid pageincrement pageindex pagestep parentcontainer palette persist persistence placeholder pmindicator popup popupboxobject ...
Actions - Archive of obsolete content
te. the id attribute of the new element will be set to the same value of the member variable, ?relateditem. you could think of this as changing the uri attribute to the id attribute, and replacing the variable. since the first result has a value of 'http://www.xulplanet.com/rdf/b' for the ?relateditem variable, the id will be set to this value. then, the remaining attributes on the element are examined and any variables are replaced in place. that is, the text ?relateditem in the label attribute will be replaced with the string 'http://www.xulplanet.com/rdf/b' for the first result. in the image, you can see that the label for the first button does indeed have this value. processing is now complete for the first result, so the builder moves on to the next result. for result b, the builder woul...
...emplate action will be ignored. however, you may use ids on the other parts of the template, such as within the query statements, if you wish to change the statements and rebuild the template. you can use getelementbyid to get at particular results, for instance document.getelementbyid("http://www.xulplanet.com/rdf/c") would retrieve the second generated button. ...
Additional Navigation - Archive of obsolete content
d the unknown variable should be placed in the triple's subject variable. <query> <content uri="?start"/> <triple subject="?relateditem" predicate="http://www.xulplanet.com/rdf/relateditem" object="?start"/> </query> the triple is evaluated in the same manner except that the value of the object can be filled in with the value of the ?start variable. the rdf graph is examined for an arrow pointing in to the node instead of out. in the photos example, we might wish to categorize each photo into several categories. one possibility is to just add another predicate for each photo with a literal value set to the category. or, we could use a resource for each category. this will allow us to associate additional properties to each category and more easily navigate the grap...
...planet.com/rdf/country" object="?start"/> <triple subject="?photo" predicate="http://purl.org/dc/elements/1.1/title" object="?title"/> </query> the first triple is used to get the title for the country. there is only one potential result at this point, the starting node which is 'http://www.daml.org/2001/09/countries/iso#it'. after the first triple is examined, the data network will look like the following: (?start = http://www.daml.org/2001/09/countries/iso#it, ?countrytitle = italy) only one result is present since there is only one title available. the second triple is the more interesting one. it is used to look up nodes that have a country predicate pointing in. it may be difficult to tell whether the builder will look for arcs pointing out f...
Attribute Substitution - Archive of obsolete content
the attribute value will be 'my name is jake'. you can include multiple variables in one attribute if desired: <label value="my name is ?name and my age is ?age"/> this technique will work for any variable replacement in the action body, except for the uri attribute since that wouldn't be meaningful. note that variable names must have a space after them as this is how the end of variable is determined. that is '?name?age' is considered to be a single variable with that name, not two variables together. to use two variables, place a space between them. it is sometimes useful though, to concatenate two values together without a space. this can be done simply by putting two variables next to each other in an attribute value separated by a caret (^). <label value="?name" class="?gender^?national...
... <description>view from the top of the tower looking east of the doges palace</description> note that the textnode has been replaced with the substituted value attribute. note that in firefox 2 and earlier, a bug can make this appear to not work at times. recall that the template builder doesn't load the datasource before processing a template. as the datasource loads, the query and rules are examined with the new data as it arrives. this causes rules to create matches as the data loads. however, variables determined from a binding are evaluated using a much simpler process. the bug is that this code path for bindings doesn't handle the textnode element properly. thus, if you use a variable set in a binding, you must ensure the datasource is loaded before the template is built, or just rebui...
Bindings - Archive of obsolete content
scription" object="?description"/> <action> ... </action> </rule> </template> the description triple has been changed to a binding element, but the attributes are the same. this allows a match to occur even if the description is not specified. note that when bindings are used, the bindings and the action must be enclosed inside a rule element. ...
... </action> </rule> </template> the description triple has been changed to a binding element, but the attributes are the same. this allows a match to occur even if the description is not specified. note that when bindings are used, the bindings and the action must be enclosed inside a rule element. the template builder examines bindings after the query has generated results. it has already determined, in this example, that three matches have been found. the builder continues by filling in the values for any bindings. they are evaluated in a similar though simpler manner than the triples. the value of the ?photo variable is known for each match, the datasource is examined for the description, and the value of the ?description variable is filled in. the effect is three matches, only one of wh...
Building Trees - Archive of obsolete content
could also be used. when using the tree builder, the uri attribute must be declared on the treeitem element. here, the simple rdf query syntax is used, so the member variable is rdf:*. the remaining tags have a similar syntax to a tree, but have only a single row. this row is used as the template data by the tree builder. instead of generating content, the builder uses the cell attributes to determine what to display. the tree builder implements the nsitreeview interface, so it becomes the tree’s view—in other words, the tree’s view and the tree’s builder are the same object. when the tree is displayed, it asks the view for the contents of each cell. the builder looks at the label for the corresponding cell, translates any variables or predicates into values, and returns the value. in...
...> </tree> features of the tree builder besides the label of a cell, there are several other cell properties you can set when using the tree builder. the supported properties are: label, mode, properties, src and value. the label attribute is used to set the label for a cell. the mode is used for progress meter columns. it may be set to either “normal” for a normal progress meter or “undetermined” for an undetermined progress meter. the value attribute is used to set the current progress value for normal progress meters. the value attribute may also be used for checkbox columns by setting it to either true or false. whether a cell is a normal labeled value, a progress meter or a checkbox is determined by the type attribute on the column the cell is in. for cells in normal columns, you...
Filtering - Archive of obsolete content
riple from the query. this example only adds one triple, but you could add others, or add <member> elements. whether a triple or member is added or removed, the template must be rebuilt by calling the rebuild method. this method will remove all of the existing generated content, delete all of the internal information pertaining to the results, and start again as if the template were just being examined for the first time. the template will be parsed again and the data examined for new results. you can view a complete example of this in action. a menulist is used to allow one to select either a specific country, or select all to show all of the photos. when a choice is made, the applyfilter function as shown above is called and the template content gets rebuilt with the desired filter applied.
...menulist datasources="template-guide-photos4.rdf" ref="http://www.daml.org/2001/09/countries/country-ont#country"> remember that the only requirement is that the starting point be a resource, but it doesn't matter what resource is used. the query statements will need to iterate over the arcs pointing into the type resource. since we want the arcs pointing into the type, we need to determine the source or subject of a triple. look at the resulting rdf triples above again if this is unclear. the starting node is 'http://www.daml.org/2001/09/countries/country-ont#country'. we need to iterate over the 'type' predicate to find the individual countries. a second triple is used to get the title for the country. <query> <content uri="?start"/> <triple subject="?country" pred...
Multiple Rule Example - Archive of obsolete content
since the second rule doesn't refer to these variables, they will not be filled in. although the canal photo has a date, the second rule doesn't use it, so you cannot refer to the ?date variable in this rule. but, you could use a <binding> to get the date without requiring it to match the conditions. of course, the variable doesn't have to be ?date in the second rule. you mig...
...results listed above, the palace photo appears twice so the second one will be removed, leaving only three matches. although the builder actually generates mutliple matches for one resource, in many cases it isn't necessary to be aware of this detail when creating templates. it is usually sufficient to assume that earlier rules are used to filter results much like an if-else construct in a programming language. if the last rule has no specific conditions (for example a simple rule with no attributes on the <rule> element), it could be considered to be the final else block that matches all data. since results generated by earlier rules override those of later results, you will want to ensure that the rules are placed in the right order. the rules should be ordered from most specific to least s...
Multiple Rules - Archive of obsolete content
« previousnext » all of the examples shown so far have used only a single rule. the builder supports the use of multiple rules as well. this involves using additional rule elements after the first. in addition, conditions may be applied to each rule. only those results that match the conditions have content generated for them. for each result, the conditions associated with each rule are examined to see if they match. the first rule that matches causes content to be generated for that result. for example, the first rule might match directories or folders, whereas the second rule might match files. in this situtation, you would want to use different output for each type. if a result from the query doesn't match any of the rules, it is ignored and no content is generated for it. note that...
...n add multiple where elements if we want to check additional conditions. when multiple conditions are present, they must all match for the rule to apply. adding to the previous example, here we check for people with a space in their name, and a total number of letters less than 15. note the assign element in the example above, used to calculate the '?letters' variable from the length of the name, minus one for the space character. naturally, this won't work for people with more than two names (joan of arc for instance), but rule conditions allow a number of useful ways to filter results. <rule> <where subject="?name" rel="contains" value=" "/> <where subject="?letters" rel="less" value="15"/> <action> <label uri="?" value="?name has two names for a total length of ?letters"/> </a...
Rule Compilation - Archive of obsolete content
the following on the hidden vbox above will start off the template builder. var length = vbox.childnodes.length; this request to return the number of children of the vbox will make the template builder process the query and output content. once done, the correct length can be returned. all of this is transparent to the xul developer. when the template builder decides to start generation is determined automatically, and you don't need to do anything special to get this to happen. however, there are two cases where content is not generated automatically: menus and child tree items. content inside a menu is not generated until the menu is opened. this makes sense since the user can't see the contents of the menu until it is open. however, it also means that the dom api usage, such as an attemp...
... that you will not be able to rely on being able to retrieve the generated menu items until the menu is opened. a similar rule applies for child tree items. the children are not generated until the user presses the twisty to open the container or when a script opens a row. lazy generation comes in handy for menus and trees especially when dealing with recursive items. it would be rather time consuming to generate output for every item in a tree, even for those not displayed, so the template builder doesn't do so. the template builder is even lazier. if the generated content itself contains hidden elements, those child elements will not be generated until necessary. when building content, the builder iterates down the node tree, copying and building only when needed. « previousnext » ...
Sorting Results - Archive of obsolete content
data. when using a tree, sorting may be performed on each column of the tree. for instance, if a list of photos was displayed in a two column tree showing the title and description, you could sort by either title or description. the user can change the sort column and direction by clicking the column headers, however, you can programmatically change the sort as well. sorting tree results we'll examine sorting of trees first since trees are the most common element used with sorted items. using a tree builder, you can sort the results in a tree by a column. to do this, place a sort attribute on a treecol element referring to the variable to sort by for that column. <treecol id="name" label="name" sort="?name" flex="1"/> <treecol id="date" label="date" sort="?date" flex="1"/> in this example, t...
...n="ascending" ref="http://www.xulplanet.com/rdf/myphotos"> <template> <vbox class="box-padded" uri="rdf:*"> <image src="rdf:*"/> <label value="rdf:http://purl.org/dc/elements/1.1/title"/> </vbox> </template> </hbox> in this example, the generated items will be sorted by title. when sorting, the predicate specified in the sort attribute for the result is used to determine where in the content the generated output should be inserted. the is similar to using a variable but any predicate may be used, not just one that is used in the template. changing the sort to change the sorting for a template's generated contents, you can either change the sort related attributes and rebuild the template, or you can call the sort method of the sort service: var listbox = documen...
Static Content - Archive of obsolete content
<menuitem uri="?country" label="?countrytitle" value="?country"/> </menupopup> </action> </template> </menulist> the only difference between the previous example and this one is that the menulist element has some additional content added before the template. the content will be displayed just like it would be as if the template wasn't present. that is, before the template is examined, the menulist would have one item in it, with the label 'all'. the template generates two results as before, one for each country, and appends a menuitem for each one. one interesting thing about this example is that only one menupopup will be created, even though there are two in the code, one outside the template and another one inside the action body. this demonstrates how the template build...
...on here is that the xul parser first creates the outer menulist element. the static content outside the template will also be created. the result will be a xul display that looks just like the code above, except that the template and its content is hidden. at this point, the menulist will have a menupopup as a child, and the menupopup will in turn have one menuitem child. next, the template is examined and two results are generated. remember that only the content at the uri attribute or below inside the action are copied for each result. when processing the action body, the builder looks at the first element inside the action, in this case, the menupopup. this element doesn't have a uri attribute, so the builder knows that this element should only be created once. you might think that the bui...
Tree Widget Changes - Archive of obsolete content
it should return true if a drop is allowed on a row. checkbox columns tree columns now implement the checkbox type. previ...
...it should return true if a drop is allowed on a row. checkbox columns tree columns now implement the checkbox type. previously the value existed but was not im...
Adding HTML Elements - Archive of obsolete content
the tags must be entered in lowercase. "quotes" must be placed around all attribute values. xml requires a trailing slash at the end of tags that have no content. this may be clearer from the examples below. using html elements you can use any html tag although some s...
... the tags must be entered in lowercase. ...
Anonymous Content - Archive of obsolete content
croll bar. all of the elements inside the content tag will be added inside the element that the binding is bound to. presumably this binding would be bound to a scroll bar, although it doesn't have to be. any element that has its css -moz-binding property set to the uri of the binding will use it. 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 anonymously. although anonymous content is displayed on screen, you cannot get to it thr...
...ntain a field for entering text, followed by a browse button. this inner content is created anonymously and cannot be seen using the dom. override the bound element the anonymous content is created automatically whenever a binding is attached to an element. if you place child elements inside the xul, they will override the elements provided by the binding. for example, take this xul fragment, assuming it is bound to the scrollbar xbl earlier: <scrollbar/> <scrollbar> <button label="overridden"/> </scrollbar> the first scroll bar, because it has no content of its own, will have its content generated from a binding definition declared in an xbl file. the second scroll bar has its own content so it will use that instead of the xbl content, resulting in something that isn't much of a scroll b...
Document Object Model - Archive of obsolete content
« previousnext » the document object model (dom) can be used with xul elements to get information about them or modify them. dom introduction the document object model (dom) is used to store the tree of xul nodes. when an xul file is loaded, the tags are parsed and converted into a hierarchical document structure of nodes, one for each tag and block of text. the dom structure may be examined and modified using various methods provided for this purpose. specific xul elements also provide additional functions which may be used. each xul file that is loaded will have its own document displayed in a window or frame. 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 ...
...ith which namespace is meant. this causes an xhtml button to be created for this case. the fourth button is a little confusing, but might clarify that it is the uri that is important and not the prefix. the fourth example is a xul button, not an html button, despite what the prefix might say. this is an important distinction. in fact, the actual text used for the prefix is irrelevant when determining what kind of element is used. the dom provides a number of namespace related functions similar to the non-namespace ones. for example, the getattributens() function is similar to the the getattribute() function except an additional argument may be supplied to specify an attribute in a specific namespace. many xul elements have their own properties that are unique to that element. refer to th...
Features of a Window - Archive of obsolete content
height you should have noticed that whenever elements were added to a window, the window's width expanded to fit the new elements. the window is really just a box which is flexible and defaults to vertical orientation. you can also specify the width and height directly on the window tag. this, of course, causes the window to be displayed in a specific size. if you leave it out, the size is determined by the elements that are in it. 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. that means the next time the window is opened, it will still open in the saved location. <window id="findfile-window" title="find files" width="400" height="450"...
...u should also consider that a user might be using a different theme or locale. note that you must specify both the width and the height. if you only specify one, the other will be set to 0. to have the window set its size automatically, leave both the width and height out. the width and height only specify the initial size of the window. the user may still resize the window to another size, assuming that the window is resizable. other window features the flags below can be passed as part of the third argument to the window.open function. your operating system may not support all of them. you can also use any of the pre-existing flags, which you should find in a javascript reference. you may disable a feature by setting it to 'no', for example 'dialog=no'. alwayslowered the window will...
Grids - Archive of obsolete content
Archive › Mozilla › XUL › Tutorial › Grids
uld add additional nested boxes or even another grid inside a single cell. if you resize the window of the last example, you will see that the textboxes resize, but no other elements do. this is because of the flex attributes added to the textboxes and the second column. the first column does not need to be flexible as the labels do not need to change size. the initial width of a column is determined by the largest element in the column. similarly, the height of a row is determined by the size of the elements in a row. you can use the minwidth and maxwidth and related attributes to further define the size. column based organization you can also place the elements inside the column elements instead of the rows. if you do this, the rows are just declared to specify how many rows there are. ...
...n. the first element inside each column element is placed in the first row, the second element in the second row and the third element is placed in the third row. if you put content in both the columns and the rows, the content will overlap each other, although they will align in a grid properly. it creates an effect much like a grid of stack elements. the order of the elements in the grid determines which is displayed on top and which is placed underneath. if the rows element is placed after the columns element, the content within the rows is displayed on top. if the columns element is placed after the rows element, the content within the columns is displayed on top. similarly, events such as mouse buttons and keypresses are sent only to the set on top. this is why the columns were declare...
Install Scripts - Archive of obsolete content
"locale")); the delayed_chrome flag is used to indicate that the chrome should be installed the next time mozilla is run. installation completion the adddirectory() and addfile() functions don't copy any files. they only state which files should be installed. similarly, registerchrome() only states that chrome should be registered. to complete the process and begin copying files, call the performinstall() function. it takes no arguments. the final script for installing the find files component is shown below: source initinstall("find files","/xulplanet/find files","0.5.0.0"); finddir = getfolder("chrome","findfile"); setpackagefolder(finddir); adddirectory("findfile"); registerchrome(install.content | install.delayed_chrome, getfolder(finddir, "content")); registerchrome(install.ski...
... « previousnext » ...
Manifest Files - Archive of obsolete content
ges may be installed into mozilla and referenced with chrome urls. a package can contain any kinds of files and may be split into subdirectories for different parts of the package. a package can be stored either as a directory or as a jar archive. manifest files a manifest file describes a package and maps its location on disk to a chrome url. the manifest files in the chrome directory will be examined when a mozilla application starts up to see what packages are installed. that means that all you need to do to install a new package is add a new manifest file either into the application chrome directory or the user specific chrome directory. this latter chrome directory is normally the one used since the application directory might not have sufficient permissions to write into it. note: sta...
...ith a blank line. on windows, file urls are of the form file:///c:/files/app/, where c is the drive letter. make sure the contents.rdf file is in the right directory and is well-formed. open the contents.rdf file in mozilla to see if it parses as well-formed xml. if not, you will see an error on a yellow background. if you are using a debug build of mozilla, some info will be printed to the terminal when starting up indicating what chrome applications are being checked. check if your application is listed. the error message "xml parsing error: undefined entity" in your xul file can be caused by an error in the manifest or in the jar file referenced by the manifest. for example, in <!doctype window system "chrome://fireclipse/locale/fireclipse.dtd"> the dtd file must exist and its director...
Stack Positioning - Archive of obsolete content
top="5"/> <button label="trolls" left="60" top="20"/> <button label="vampires" left="10" top="60"/> </stack> the stack here contains three elements, each positioned at the coordinates given by the left and top attributes. here, all three children are buttons, but the elements do not have to be same type. they may be any element, including boxes and other stacks. the size of a stack is determined by the positions of the child elements. it is always sized so that all of the child elements are visible (excluding any children with -moz-stack-sizing: ignore). so if you set a left attribute to 400, the stack will have a width around 400 pixels plus the width of the element. you can override this size with the various style properties such as width and max-width. you can use a script to adju...
...h, both "left" and "right" must be set. in this example, the resulting width of the top-most hbox will be 400px: <stack width="600"> <hbox flex="1"> <!-- content --> </hbox> <hbox left="0" right="200" > <!-- some content here. --> </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. the next section describes tabboxes which are like decks but provide their own navigation. « previousnext » ...
Tabboxes - Archive of obsolete content
al tab pages should go inside each tabpanel element. they do not go in the tab elements, as that is where the contents of the tabs along the top go. each tabpanel element becomes a page on the tabbed display. the first panel corresponds to the first tab, the second panel corresponds to the second tab, and so on. there is a one-to-one relationship between the tab and tabpanel elements. when determining the size of the tabbox, the size of the largest page is used. that means that if there are ten textboxes on one tab page and only one on another, the tab page will be sized to fit the one with the ten on it as this takes up more room. the area taken up by the tab area does not change when the user switches to a new tab page. tabbox example example 1 : source view <tabbox> <tabs> <ta...
...you can see the two tabs, search and options. clicking on ea...
Templates - Archive of obsolete content
sources="rdf:bookmarks" ref="nc:bookmarksroot" flex="1"> <template> <label uri="rdf:*" value="rdf:http://home.netscape.com/nc-rdf#name rdf:http://home.netscape.com/nc-rdf#url"/> </template> </vbox> how templates are built when an element has a datasources attribute, it indicates that the element is expected to be built from a template. note that it isn't the template tag that determines whether content is built, it is the datasources attribute. when this attribute is present, an object called a builder is added to the element which is responsible for building the content from the template. in javascript you can access the builder object with the builder property, although usually you would only need to do this to have the builder regenerate the content in situations where it i...
...separator resources. that means that we want to have two different types of content be created, one type for regular bookmarks and a second type for separators. we can do this by using the rule element. we define a rule for each variation of elements that we want to have created. in our case, we would need a rule for bookmarks and a rule for separators. attributes placed on the rule element determine which rules apply to which rdf resource. when scanning for which rule applies to the data, each rule element is checked in sequence for a match. that means that the order in which you define rules is important. earlier rules will override later rules. rule example the following example demonstrates the earlier example with two rules: example 4 : source <window id="example-window" title=...
Tree Box Objects - Archive of obsolete content
h() function which returns the number of rows in a page. in the scrolling example above, getpagelength() would return four. note that in firefox 1.0 and mozilla 1.7 and earlier, the getpagelength() function is called getpagecount() instead. 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. you could determine the number of pages by dividing the total number of rows by the page length. the ensurerowisvisible() function will scroll to a row just as scrolltorow() does, but does not scroll if the row is already visible. cell coordinates some of the most interesting functions of the tree box object are several functions which may be used to get the parts of the tree at specific coordinates and vice ve...
...us example, you might notice the label change between 'text' and 'cell'. the value 'text' indicates the area where the text would be drawn and the value 'cell' indicates the area around the text, for example, the margin on the left side where the open and close twisties are normally drawn. if there was a twisty, however, the value would be 'twisty' instead. this is convenient since you could determine whether the user clicked on a twisty instead of another part of the row. in fact, this is what the underlying tree code does when the user double clicks the twisty. the final value that may be returned is 'image' if there is an image in the tree cell and the coordinate corresponds to a location where the image is. of course, in many cases you may not care what part of the cell the coordinate is ...
Trees - Archive of obsolete content
Archive › Mozilla › XUL › Tutorial › Trees
of the tree consists only of a single widget which draws all of the data in the tree. this contrasts with the listbox, where individual listitem and listcell tags are used to specify the rows in the listbox. in a tree, all of the data to be displayed is supplied by a separate object, called a tree view. when it comes time to display a cell, the tree widget will call out to this tree view to determine what to display, which in turn will be drawn by the tree. the tree is smart enough to only ask for information from the view for those rows that need to be displayed. this allows the view to be optimized such that it only needs to load the data for displayed content. for instance, a tree might have thousands of rows, yet most of them will be scrolled off the border of the tree, hidden from view.
...ow elements. the treerow element surrounds all of the cells in a single row, while a treeitem element would surround a row and all of its children. trees with nested rows are described in the next section. inside the rows, you will put individual tree cells. these are created using the treecell element. you can set the text for the cell using the label attribute. the first treecell in a row determines the content that will appear in the first column, the second treecell determines the content that will appear in the second column, and so on. the user can select the treeitems by clicking on them with the mouse, or by highlighting them with the keyboard. the user can select multiple items by holding down the shift or control keys and clicking additional rows. to disable multiple selection, pl...
Trees and Templates - Archive of obsolete content
are not duplicated whereas the element with the uri attribute and the elements inside it are duplicated for each resource. as the tree builder is used and not the content builder, the structure of the elements in the above example must be as shown, with the treechildren element inside the rule. although the tree builder doesn't build these elements, it does require this structure in order to determine what to generate correctly. note in the image that additional child elements below the top-level elements have been added automatically. xul knows how to add child elements when the templates or rules contain tree elements or menu elements. it will generate tree elements as nested as necessary based on the available rdf data. an interesting part of rdf datasources is that the resource values...
...ate correctly. note in the image that additional child elements below the top-level elements have been added automatically. xul knows how to add child elements when the templates or rules contain tree elements or menu elements. it will generate tree elements as nested as necessary based on the available rdf data. an interesting part of rdf datasources is that the resource values are only determined when the data is needed. this means that values that are deeper in the resource hierarchy are not determined until the user navigates to that node in the tree. this becomes useful for certain datasources where the data is determined dynamically. sorting columns if you try the previous example, you might note that the list of files is not sorted. trees which generate their data from a datasource...
Using Remote XUL - Archive of obsolete content
e mozilla.org home page by default so that page loads into the iframe when we first load the xul document. the iframe's flex attribute tells the browser to stretch the iframe to fill the space available to it. without it, the iframe's size would be a fixed default and wouldn't change when the user resized their window. [optionally show what this looks like] the value of the flex attribute determines the extent to which the element will stretch relative to other flexible elements. an element with a flex of "2" is twice as flexible as an element with a flex of "1", so the first element might show up as twice as wide as the second. in our case, the iframe will be the only flexible element in our document, so we don't have to worry about its value and give it a standard value of 1. [optionall...
...menu item and button. source | rendered conclusion it works! basic global web site navigation. what we've built is just a start, however. ...
Using the standard theme - Archive of obsolete content
f the base application (the so called "global skin"), you have to add the following line to your xul file: <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> this imports the styles found in the <tt>global/skin</tt> chrome directory and will make the standard xul widgets of your application use the selected chosen theme. you do not have to specify a specific file; mozilla will determine by its own which files in the directory it needs to use. if you are only going to use these global style sheets, you of course do not need a <tt>skin</tt> directory in your extension package, and also do not have to register a style in the <tt>chrome.manifest</tt>. adding custom styles in order to provide custom styling for some of your widgets (apart from the standard global skin) you can take...
...y the user. that is, depending on the theme currently selected by the user, you can provide different custom style sheets for your extensions. for this to work, you need to create an approriate directory structure, with directory names corresponding to the names of the themes you want to extend, and of course, your adapted custom style sheets. for more information on how to do this, read about theming a custom toolbar button. note that both approaches described above work with this automatic style selection. ...
Accessibility/XUL Accessibility Reference - Archive of obsolete content
tton image="images/img.xbm" tooltiptext="<!--button text-->"/> note that in the third example, only the first label is read browser jaws 7.10 issues to use a browser element with html, the type="content" attribute should be specified. however, this attribute causes any xul loaded in the browser to have issues with jaws 7.10. 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. therefore, with jaws 7.10, to use xul inside of a browser, the type attribute cannot not be used. caption see groupbox checkbox <checkbox label='<!--label text-->' /> colorpicker <colorpicker type="button" palettename="standard" /> colorpicker app...
...upopup> </menulist> menupopup see menulist and menubar popup see popupset popupset be careful regarding keyboard access of popups. i don't see a means of accessing a popup brought up via the popup attribute. using context="popupid" allows access via shift+f10 on windows and linux. ...
XUL controls - Archive of obsolete content
rc="happy.png"/> </richlistitem> <richlistitem> <image src="sad.png"/> </richlistitem> <richlistitem> <image src="angry.png"/> </richlistitem> </richlistbox> richlistbox reference related elements: richlistitem <scale> a scale displays a bar with a thumb that may be slid across the bar to select between a range of values. <scale min="1" max="10"/> scale reference <splitter> allows the user to adjust the division of space between elements. <splitter collapse="before"> <grippy/> </splitter> splitter reference related elements: grippy <tab> description goes here. <tab label="firefox"/> tab reference related elements:...
...s a dropdown showing matches that would complete what the user types. the user can select one to have it filled into the textbox. <textbox type="autocomplete" autocompletesearch="history"/> textbox reference <textbox type="number"> a textbox for entering numbers. two arrow buttons are displayed for cycling through values. <textbox type="number" min="1" max="20"/> textbox reference <textbox type="password"> a textbox that hides the characters typed, used for entering passwords. <textbox type="password"/> textbox reference <textbox type="search"> a textbox for searching. <textbox type="search"/> textbox reference <textb...
box - Archive of obsolete content
Archive › Mozilla › XUL › box
box orient="horizontal"> <label value="three"/> <label value="four"/> </box> </box> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextme...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
button - Archive of obsolete content
ent behavior for how the states are adjusted, set the autocheck attribute to false and adjust the state with a script. the type attribute must be set to checkbox for buttons with a check state. constants for the possible values for this attribute are in the nsidomxulbuttonelement interface. checked type: boolean indicates whether the element is checked or not. use hasattribute() to determine whether this attribute is set instead of getattribute(). for buttons, the type attribute must be set to checkbox or radio for this attribute to have any effect. command type: id set to the id of a command element that is being observed by the element. crop type: one of the values below if the label of the element is too big to fit in its given space, the tex...
...-back, properties, select-font, select-color, network. if you are using a button that matches one of these common usages, use the icon attribute to indicate this. see the appearance of the different icons on some available platforms. image type: uri the uri of the image to appear on the element. if this attribute is empty or left out, no image appears. the position of the image is determined by the dir and orient attributes. label type: string the label that will appear on the element. if this is left out, no text appears. for an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. open type: boolean for the menu type buttons, the open attribute is set to true when the menu is open...
command - Archive of obsolete content
content still receives these key events, even though it can't override them. in future releases, it won't receive them. see bug 1173061 for details. ...
...ill receives these key events, even though it can't override them. in future releases, it won't receive them. see bug 1173061 for details. ...
commandset - Archive of obsolete content
ecified, or you set it to the value '*', all elements are valid. the command update will only occur when the event occurs to one of the specified elements. ...
... you set it to the value '*', all elements are valid. the command update will only occur when the event occurs to one of the specified elements. ...
dialogheader - Archive of obsolete content
on type: string descriptive text to appear in addition to the dialog title. title type: string the text to appear in the title bar of the window. ...
...tring descriptive text to appear in addition to the dialog title. title type: string the text to appear in the title bar of the window. ...
grid - Archive of obsolete content
Archive › Mozilla › XUL › grid
"/> </menupopup> </menulist> </row> </rows> </grid> </groupbox> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextme...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
hbox - Archive of obsolete content
Archive › Mozilla › XUL › hbox
--> <hbox> <spacer flex="1"/> <button label="connect"/> <button label="ping"/> </hbox> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextme...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
iframe - Archive of obsolete content
esults in the iframe's background being transparent. ...
...he iframe's background being transparent. this can be used to workaround things like bug 540911 inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the element. ...
image - Archive of obsolete content
Archive › Mozilla › XUL › image
type type: integer a value indicating the type of accessibility object for the element. src type: url gets and sets the value of the src attribute. ...
... type: integer a value indicating the type of accessibility object for the element. src type: url gets and sets the value of the src attribute. ...
key - Archive of obsolete content
Archive › Mozilla › XUL › key
o the value capturing to indicate during the event capturing phase or target to indicate at the target element or left out entirely for the bubbling phase. ...
... capturing to indicate during the event capturing phase or target to indicate at the target element or left out entirely for the bubbling phase. ...
listcol - Archive of obsolete content
stitem> <listcell label="john"/> <listcell label="painter"/> </listitem> </listbox> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextme...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
listcols - Archive of obsolete content
stitem> <listcell label="john"/> <listcell label="painter"/> </listitem> </listbox> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextme...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
listitem - Archive of obsolete content
item label="sapphire" selected="true"/> <listitem label="diamond"/> </listbox> attributes accesskey type: character this should be set to a character that is used as a shortcut key. this should be one of the characters that appears in the label attribute for the element. checked type: boolean indicates whether the element is checked or not. use hasattribute() to determine whether this attribute is set instead of getattribute(). for buttons, the type attribute must be set to checkbox or radio for this attribute to have any effect. command type: id set to the id of a command element that is being observed by the element. crop type: one of the values below if the label of the element is too big to fit in its given space, the text ...
... to enable the element, leave this attribute out entirely. visible controls have a disabled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. image type: uri the uri of the image to appear on the element. if this attribute is empty or left out, no image appears. the position of the image is determined by the dir and orient attributes. label type: string the label that will appear on the element. if this is left out, no text appears. for an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. preference type: id connects the element to a corresponding preference. this attribute only has any eff...
menu - Archive of obsolete content
Archive › Mozilla › XUL › menu
an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. menuactive type: boolean this attribute is set on an item in a menu when it is being hovered over. typcially, the theme will use this to highlight the item. a dommenuitemactive event will be sent to the item when the item is hovered over, and a dommenuiteminactive event will be sent to the item when the selection moves away. open type: boolean for the menu type buttons, the open attribute is set to true when the menu is open. the open attribute is not present if the menu is closed. sizetopopup type: one of the values below indicates how the menu width and the menupopup width are determined. if the sizetopopup attribute is left out or ...
...wise, the menu will size itself to at least the size of the popup. if the menu has a maximum width, the popup will also be this width. none the width of the popup will not be constrained to the size of the menu. pref the preferred width of the menu label or button will be the size needed for the popup contents. this is the default value for menulists. always both the preferred and minimum width of the menu label or button will be the same as that necessary for the menupopup. value type: string the string attribute allows you to associate a data value with an element. it is not used for any specific purpose, but you can access it with a script for your own use. be aware, however, that some elements, such as textbox will display the value visually, so in order to mer...
menubar - Archive of obsolete content
a value indicating the type of accessibility object for the element. statusbar type: id of statusbar element gets and sets the value of the statusbar attribute. ...
...indicating the type of accessibility object for the element. statusbar type: id of statusbar element gets and sets the value of the statusbar attribute. ...
menupopup - Archive of obsolete content
ned. this handler is usually used to dynamically set the contents when the user requests to display it. returning false from this event handler prevents the popup from appearing. onpopupshown type: script code this event is sent to a popup after it has been opened, much like the onload event is sent to a window when it is opened. position type: string the position attribute determines where the popup appears relative to the element the user clicked to invoke the popup. this allows you to place the popup on one side of a button. note that a context menu will never respect this attribute, always appearing relative to the mouse cursor. this value can be specified either as a single word offering pre-defined alignment positions, or as 2 words specifying exactly which part of...
...used to further control where the popup appears relative to the element. the anchor argument corresponds to the popupanchor attribute on the element. the align argument corresponds to the popupalign attribute on the element. the anchor and align arguments are ignored if either x or y are not -1. 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. the popuptype should be one of the strings popup, context, or tooltip. each type of popup is intended to be displayed only temporarily; they are not expected to be displayed permanently. sizeto( wi...
notification - Archive of obsolete content
ributes image, label, priority, persistence, type, value properties accessibletype, control, image, label, priority, persistence, type, value methods close examples <notification label="this is a warning"/> attributes image type: uri the uri of the image to appear on the element. if this attribute is empty or left out, no image appears. the position of the image is determined by the dir and orient attributes. label type: string the label that will appear on the element. if this is left out, no text appears. for an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. persistence type: integer the persistence may be set to a non-zero value so that the notificationbox'...
...not remove them. this may be used to close a set of notifications as a group without affecting other notifications. priority type: integer numeric value that specifies the order in which the notifications appear. should be one of the constants described in the notificationbox's appendnotification method. type type: one of the values below indicates the type of notification, determined from the priority. info a notification that is of lesser importance. warning a normal warning notification. critical a critical notification. value type: string the string attribute allows you to associate a data value with an element. it is not used for any specific purpose, but you can access it with a script for your own use. be aware, however, that some elements...
popupset - Archive of obsolete content
paste"/> </menupopup> </popupset> <label value="right click for popup" context="clipmenu"/> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextme...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
rule - Archive of obsolete content
Archive › Mozilla › XUL › rule
with different tags. parsetype type: string if this attribute is set to integer, the rule will only match rdf nodes with a parse type of integer. ...
...rent tags. parsetype type: string if this attribute is set to integer, the rule will only match rdf nodes with a parse type of integer. ...
scrollbar - Archive of obsolete content
ay of the scroll bar (the area in which the scroll bar thumb moves) is clicked, or when the page up or page down keys are pressed. the default value is 10. ...
...croll bar (the area in which the scroll bar thumb moves) is clicked, or when the page up or page down keys are pressed. the default value is 10. ...
spacer - Archive of obsolete content
xamples <box> <button label="left"/> <spacer flex="1"/> <button label="right"/> </box> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextme...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
stringbundle - Archive of obsolete content
ed) attributes src type: uri the uri of the property file that contains the localized strings. ...
...utes src type: uri the uri of the property file that contains the localized strings. ...
tab - Archive of obsolete content
Archive › Mozilla › XUL › tab
of appearing or disappearing. first-tab type: boolean this attribute will be set to true for the first tab. this attribute should not be set manually, but is useful in a theme if the first tab should be styled differently. image type: uri the uri of the image to appear on the element. if this attribute is empty or left out, no image appears. the position of the image is determined by the dir and orient attributes. label type: string the label that will appear on the element. if this is left out, no text appears. for an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. last-tab type: boolean this attribute will be set to true for the last tab. this attribute should not...
...: script code this event handler is called when the command is activated. this occurs when a user selects a menu item or presses a keyboard shortcut attached to the command. pending type: boolean this attribute is set to true if the tab is currently in the process of being restored by the session store service. once the tab is restored, this attribute is removed. you can determine if a tab is being restored by checking to see if hasattribute("pending") is true. if the user has turned on the "don't load tabs until selected" preference, the pending attribute is set on tabs until they get loaded. pinned type: boolean this attribute is set to true if the tab has been pinned (that is, if it's an app tab). the tabbrowser element's pintab and unpintab methods handle pinnin...
tabbrowser - Archive of obsolete content
e: string home page url this property holds the value of the user's home page setting. markupdocumentviewer type: nsimarkupdocumentviewer this read-only property contains the nsimarkupdocumentviewer which is responsible for drawing the document. securityui type: nsisecurebrowserui the read-only property holds an object which may be used to determine the security level of the loaded document. selectedbrowser type: browser element this read-only property returns the currently displayed browser element. selectedtab type: tab element a reference to the currently selected tab, which will always be one of the tab elements in the tabs element. assign a value to this property to modify the currently selected tab. sessionhistory...
... tabs element that contains the tabs. this is useful for add-ons that need to use events related to tabs in the browser window. tabs type: array a nodelist containing the tab objects for each tab in the tabbrowser. this is a shortcut for looking at the tabs in the tabcontainer. visibletabs type: array an array containing tab objects for each visible tab in the tabbrowser. this lets you determine which tabs are visible in the current tab set. webbrowserfind type: nsiwebbrowserfind this read-only property contains an nsiwebbrowserfind object which can be used to search for text in the document. webnavigation type: nsiwebnavigation this read-only property contains the nsiwebnavigation object for the document. most of its methods are callable di...
toolbaritem - Archive of obsolete content
oolbarbutton id="myext-button2" class="toolbarbutton-1" label="labe2l" /> </toolbaritem> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextme...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
toolbarpalette - Archive of obsolete content
tooltiptext="&mytiptext;" oncommand="somefunction()"/> </toolbarpalette> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextme...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
toolbox - Archive of obsolete content
...
... customtoolb...
tooltip - Archive of obsolete content
boolean setting the page attribute to true will result in the tooltip being filled automatically as appropriate for a browser content area tooltip, i.e. the tooltip text is set according to the dom element in the browser that the user hovered over. example <tooltip id="pagetooltip" page="true"/> <browser tooltip="pagetooltip"/> position type: string the position attribute determines where the popup appears relative to the element the user clicked to invoke the popup. this allows you to place the popup on one side of a button. note that a context menu will never respect this attribute, always appearing relative to the mouse cursor. this value can be specified either as a single word offering pre-defined alignment positions, or as 2 words specifying exactly which part of...
...used to further control where the popup appears relative to the element. the anchor argument corresponds to the popupanchor attribute on the element. the align argument corresponds to the popupalign attribute on the element. the anchor and align arguments are ignored if either x or y are not -1. 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. the popuptype should be one of the strings popup, context, or tooltip. each type of popup is intended to be displayed only temporarily; they are not expected to be displayed permanently. sizeto( wid...
treecol - Archive of obsolete content
s wider than the available space. properties accessibletype type: integer a value indicating the type of accessibility object for the element. ...
...n the available space. properties accessibletype type: integer a value indicating the type of accessibility object for the element. ...
treeitem - Archive of obsolete content
elements that appear inside the element with the attribute will be repeated for each node in the rdf datasource. elements outside will appear only once. ...
... that appear inside the element with the attribute will be repeated for each node in the rdf datasource. elements outside will appear only once. ...
vbox - Archive of obsolete content
Archive › Mozilla › XUL › vbox
bottom --> <vbox> <spacer flex="1"/> <label value="one"/> <label value="two"/> </vbox> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextme...
...erytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
wizardpage - Archive of obsolete content
identifer in the wizard. this is used with the next attribute. the wizard always starts with the wizardpage that appears first in the wizard child list. ...
...in the wizard. this is used with the next attribute. the wizard always starts with the wizardpage that appears first in the wizard child list. ...
Creating XULRunner Apps with the Mozilla Build System - Archive of obsolete content
-f client.mk build so if you are building xulrunner as well as your app, this will cause both to be built in sequence. just walking the mozilla tree to build xulrunner can take a fair amount of time, even if it has already been built and the sources haven't changed. so you'll probably find it convenient to use two .mozconfig files, one for building both and one just for your app. ...
...thanks also to dave townsend for the many hours of trial-and-error he doubtless put into figuring this all out when writing mccoy. he suffered so that we don't have to. ...
XULRunner Hall of Fame - Archive of obsolete content
can embed xul application. mockery mockery is a gui design tool for creating and editing mockups, prototypes, and wireframes for web and desktop software. latest release august 2010 plain old webserver google warns that this link is unsafe. a fully-functioning webserver that runs server-side javascript. latest release june 2009 prism (formerly known as webrunner) a simple, minimal web browser shell or "single site browser." useful for running web applications such as gmail in a separate browser process. songbird songbird™ is a desktop web player, a digital jukebox and web browser mashup. build instructions spicebird a collaboration suite - e-mail, calendaring and instant messaging. latest release: june 2010 - build instructions utilities / prototypes...
...ongbird™ is a desktop web player, a digital jukebox and web browser mashup. build instructions spicebird a collaboration suite - e-mail, calendaring and instant messaging. latest release: june 2010 - build instructions utilities / prototypes ajax toolkit framework (atf) a part of the eclipse web tools platform (wtp) aliwal geocoder geocode addresses onto a map benjamin's xulrunner examples "mybrowser is a very simple example browser", xulmine. 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. you can use the firefox extension or the stand...
Using LDAP XPCOM with XULRunner - Archive of obsolete content
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. create a subdirectory extensions/ldapstub in the mozilla source code directory, containing two files, makefile.in and ldapstubloader.cpp: makefile.in: # copyright (c) 2005 benjamin smedberg <benjamin@smedbergs.us> depth = ../.. srcdir = @srcdir@ topsrcdir = @top_srcdir@ vpath = @srcdir@ include $(depth)/config/autoconf.mk module = mozldapstub library_name = mozldap_stub is_component = 1 force_shared_lib = 1 requires = \ xpcom \ string \ $(null) cppsrcs = ldapstubloader.cpp extra_dso_ldopts += \ $(dist)/lib/$(lib_prefix)xpcomglue_s.$(lib_suffix) \ $(xpcom_frozen_l...
...y_name = mozldap_stub is_component = 1 force_shared_lib = 1 requires = \ xpcom \ string \ $(null) cppsrcs = ldapstubloader.cpp extra_dso_ldopts += \ $(dist)/lib/$(lib_prefix)xpcomglue_s.$(lib_suffix) \ $(xpcom_frozen_ldopts) \ $(nspr_libs) \ $(null) include $(topsrcdir)/config/rules.mk defines += -dmoz_dll_prefix=\"$(dll_prefix)\" ldapstubloader.cpp: // copyright (c) 2005 benjamin smedberg <benjamin@smedbergs.us> #include "nscore.h" #include "nsmodule.h" #include "prlink.h" #include "nsilocalfile.h" #include "nsstringapi.h" #include "nscomptr.h" static char const *const kdependentlibraries[] = { #ifdef ns_win32 moz_dll_prefix "nsldap32v50" moz_dll_suffix, moz_dll_prefix "nsldappr32v50" moz_dll_suffix, #endif //ns_win32 #ifdef ns_unix moz_dll_prefix "ldap50" moz_dll...
toolkit.singletonWindowType - Archive of obsolete content
if such a window is found, it will be re-used, otherwise a new window will be opened. ...
...if such a window is found, it will be re-used, otherwise a new window will be opened. more information on this can be found in bug 317811. ...
xulauncher - Archive of obsolete content
#!/bin/bash -e # a simple bash script to create a minimal xulrunner dir structure and # needed meta files in /tmp, copy the xul-file over and start it # usage: # xulauncher xulfile.xul [options] ############################################################################## # check if theres atleast one parameter ############################################################################## if [ $# -lt 1 ] then echo "you need to give the xul file as first parameter" exit fi # check if 1st parameter is a file ############################################################################## if [ ! -f "$1" ] then echo "\"$1\" is not a file" exit fi # define some variables ############################################################################## wd=/tmp ext=".xul" xulfile=`bas...
...some variables ############################################################################## wd=/tmp ext=".xul" xulfile=`basename $1` xulname=${xulfile%$ext} xuldir="$wd/$xulname/chrome/$xulname/" xulprefdir="$wd/$xulname/defaults/preferences" xulappini="$wd/$xulname/application.ini" xulmanifest="$wd/$xulname/chrome/chrome.manifest" xulprefs="$wd/$xulname/defaults/preferences/prefs.js" # make minimal directory structure ############################################################################## mkdir -p $xuldir mkdir -p $xulprefdir # create application.ini file ############################################################################## echo " [app] vendor=xulauncher.sh name=$xulname version=0.0.1 buildid=`date +%y%m%d` [gecko] minversion=1.8 maxversion=1.9 ">$xulappini # create c...
application/http-index-format specification - Archive of obsolete content
number: data where number is at least a three digit number (note that more digits are possible in the future) and data is separated from number by a colon and a space. the syntax of data is defined by the syntax spec for every number type. if a number is encountered that a parser does not understand the parser is required to ignore that line. there is no line length limit. all lines must be terminated by a carriage return followed by a line feed. number codes 100 a human readable comment line. machine parsers should ignore this data. this data is not intended for display to the end user and is only meant as a comment to make the file format clear to a human interpreter. 101 pre formatted human readable information line. this data is intended for the end user of the file format data...
...be escaped via the url escaping syntax defined by rfc 1738. note that multiple 200 lines override previous 200 lines. 201 data whose definition stems from a prior 200 line. a valid 201 line consists of one or more white space separated tokens that represent data described by a previous 200 line. tokens may be quoted or unquoted. unquoted tokens may not contain white space. quoted tokens are terminated by the next quote but may not contain carrage returns or new lines. any illegal characters must be escaped via the url escaping syntax defined by rfc 1738. note that a 201 line encountered before a 200 line should be ignored. 300 a url pointing to the directory represented by the index if there is one. a valid path token must be url escaped. valid 200 tokens note that all tokens are cas...
calICalendarView - Archive of obsolete content
date shown by the view enddate returns a calidatetime corresponding to the last date shown by the view. note that this date is typically not immediately useful for querying for the events and tasks shown in the calicalendarview. typically, one more day must be added to it, in order to make it exclusive. supportsdisjointdates consumers of calicalendarview should check this attribute to determine whether or not the implementation allows for calls to setdatelist. if an implementation returns true for this attribute, it must allow for any arbitrary set of dates to be displayed. hasdisjointdates returns false if the dates being displayed represent a continuous list, and true if certain dates in between startdate and enddate may not be displayed. selecteditem returns a caliitembase cor...
...date void showdate(in calidatetime adate); ensures that the passed in adate is visible in the view. the view is free to show other days as well. setdaterange void setdaterange(in calidatetime astartdate, in calidatetime aenddate); ensures that the entire range of dates from astartdate to aenddate is visible. the view is free to show other dates as well, although this should be kept to a minimum. (for instance, calendar-month-view will show all dates from the start of the week of astartdate to the end of the week of aenddate.) setdatelist void setdatelist(in unsigned long acount, [array,size_is(acount)] in calidatetime adates); this function can only be called if supportsdisjointdates is true and will throw an error if it is not. if supported, the dates in the adates array will...
nsIContentPolicy - Archive of obsolete content
1.8 control_tag 6 obsolete since gecko 1.8 raw_url 7 obsolete since gecko 1.8 document 8 obsolete since gecko 1.8 methods shouldload() called to let your content policy implementation decide whether or not the resource at a given location should be loaded. this method is called before loading the resource specified by acontentlocation to determine whether or not to start loading the requested resource. shouldload() can be called while the dom and layout of the document involved is in an inconsistent state. this means that implementers of this method must not do any of the following: modify the dom in any way (e.g., setting attributes is a no-no). query any dom properties that depend on layout (e.g., offset* properties). query any do...
...stprincipal optional. defines the principal that caused the load. this is optional only for non-gecko code: all gecko code should set this argument. for navigation events, this is the principal of the page that caused this load. return value accept or reject_* shouldprocess() should the resource be processed? shouldprocess() will be called once all the information passed to it has been determined about the resource, typically after part of the resource has been loaded. "processing" means handling by the application. for instance, shouldprocess could be used to allow a response from a server to be handled or ignored depending on the mime type of the response. note: shouldprocess() can be called while the dom and layout of the document involved is in an inconsistent state. see the note ...
2006-10-13 - Archive of obsolete content
of it. no responses as of yet. firefox browser problem: width:30ex does not respect font discussion about a font rendering problem with firefox print on the firefox context menu user would like discussion about why the bug https://bugzilla.mozilla.org/show_bug.cgi?id=204519 is a wontfix. (user feels print belongs on the context menu along with back, reload, etc.) questions about programming for firefox a student questions how to create an extension that changes fonts, and how to capture website content before it is displayed. firefox add-on wanted user is inquiring if there is such an application to automatically save pieces of a webpage everytime is it updated. firefox 2.0 should re-implement modal window.open to support web 2.0 user would like the option to show pop-up w...
... to automatically save pieces of a webpage everytime is it updated. ...
2006-10-20 - Archive of obsolete content
myk will be paying close attention to features dealing with content filtering, manipulation and control in ff3. to contribute visit the wiki discussions i wanna make an addon for firefox a commonly asked question in many newsgroups. ...
... add images next to urls ? ...
2006-10-20 - Archive of obsolete content
den responded christopher finke's question. jeff provided this link as an answer to christopher finkes' question. nsis and my extension jan vávra is wondering how he could create a win32 installer of thunderbird that when executed, it would also install his extensions of choice. he has already "studied" the makefiles but has had no success in achieving his goal. on october 20th benjamin smedberg responded jan vávra's question. benjamin smedberg mentioned in his post that jan vávra needs to add the extension files to the packaging manifest, which is used to create the installer. in jan vávra's case he is modifying the thunderbird installer so he needs to modify "mail/installer/windows/packages-static" announcements decommissioning sparky on friday on october 17th j. p...
...he linux performance test machine for the 1.8 branchs, is being decommissioned. he also added that the linux performance test data is now being provided by bl-bldlnx01. paul would like to hear from anyone who is against this decision. he can be contacted via: email: preed@mozilla.com irc: preed on irc.mozilla.org phone: 650.903.0800 x256 uploading language packs to amo on october 17th benjamin smedberg brought the following to the attention of the localizers and the build team: that he is planning to upload the firefox 2 language packages currently located at http://releases.mozilla.org/pub/mozi...rc3/win32/xpi/ to addons.mozilla.org in the next few days. this will make the language packages available to everyone. if you anyone has questions please feel free to ask benjamin smedberg. ...
2006-11-03 - Archive of obsolete content
he has also created a bug entry on bugzilla with the bug id of opened bug #344854. problem compiling with vs 2003 .net phil is trying to compile firefox for the first time and is g...
...he has also created a bug entry on bugzilla with the bug id of opened bug #344854. ...
2006-10-20 - Archive of obsolete content
attention dictionary providers, or: warning, amo sucks there was at amo (addons.mozilla.org), which has been being fixed. people who want to upload dictionaries should be advised and check #amo at irc.mozilla.org. feedback from localizers regarding sunbird/lightning 0.3 release the sunbird/lightning developers are requesting feedback on release 0.3. uploading language packs to amo benjamin smedberg is ready to upload languange packs from here to addons.mozilla.org. if there are issues or questions, contact mozilla.dev.builds. firefox rc 3 is there, staging servers, too firefox rc3 build is located here. community was encouraged to do testing. discussions how to file a legal approval for a dictionary? discussion about how to file a legal approval for a dictionary. there...
...ommunity was encouraged to do testing. discussions how to file a legal approval for a dictionary? discussion about how to file a legal approval for a dictionary. there is no xpi file instructions on how to find xpi files. meetings sign off deadline is this thursday there was a status meeting on tuesday, october 17, 2006. sign off deadline was on thursday, october 19, 2006. meeting minutes is located here. authors paul yanchun gu (gpaul) aditya nanda kuswanto(vipers101) ...
2006-10-06 - Archive of obsolete content
announcements firefox 2 release candidate 2 is now available for download beltzner announced ff2 rc2 is availabe for all 3 major platforms in some 40 langauges. rc2 testing update tim riley announced minimum tests for rc2 have been run and that rc2 is go for the final staging of the release. preed followed up and said that the checker was run and "build is go for launch". re: sunbird and lightning 0.3rc1 available sunbird and lightning 0.3rc1 is announced. this launches a (misguided?) discussion and comparison of sunbird and lightning to outlook. extension compatibility for firefox 2 chris hofmann reminds about the push to have extensions work with ff2. also invites people to file bugs about extensions that don't work. also invites people to help extension developers test for...
... about the gecko 1.8.0.8 schedule. dbaron and chris ilias respond with relative dates but still no schedule. rc2 status schrep asks for any final things standing in the way of rc2. rc2 starts spinning and en-us builds are annoucned. beltzner says that (as per bon echo status meeting) that rc2 is going to be re-spun to fix some final bugs that were regressed and patches that were just landed. reminder - ff2 rc2 code freeze 9/29/2006 at 9am pdt schrep started a discussion of bugs that need to be fixed for the ff2 rc2 code freeze to go ahead. meetings weekly status meeting - 10/02/2006 - (last meeting notes) bon echo status meeting - 10/03/2006 - (last meeting notes) ...
2006-10-20 - Archive of obsolete content
summary: mozilla.dev.platform - october 14th to october 20th 2006 announcements no announcements this week. traffic october 14, 2006, 6:53pm - ed notes that, on windows, composer 0.1's reccomended install directory needs to be different than those noted in the release notes. this is a xulrunner 1.8.0.4 application. benjamin smedberg would like to know what paths were used. ...
... directory needs to be different than those noted in the release notes. this is a xulrunner 1.8.0.4 application. benjamin smedberg would like to know what paths were used. started wed, oct 18 2006 9:38 am - a xulrunner developer, frank, discusses his desire to make xul/browser based applications. he wants to be able to build applications that will run inside the browser. nickolay ponomarev, benjamin smedberg, axel hecht clarify some misconceptions about front-end and back-end programming with xulrunner, including the difficulty of writing the backends in c++ (since that would require a recompilation on every platform frank wanted to support). meetings no meetings this week ...
2006-11-10 - Archive of obsolete content
summary: mozilla.dev.platform - november 4th - november 10th, 2006 announcements no announcements this week traffic beaufour moves the discussion about xulrunner unit-tests like xpcshell from mozilla.dev.platform to mozilla.dev.quality. benjamin smedberg crossposted a notice about unit testing for the mozilla toolkit, letting developers know about the importance of testing for the improvement of mozilla 2, and asks for complete coverage. several community members comment, backing up benjamin's post. william vanderpol asks, regarding remote xul applications, if is it possible (or does it exist?) to have an extension that will allow chrome access to certain specified url's? james leigh points out that resources are available at o'reily, in the creating applications with mozilla secti...
...he is looking for xptcall port maintainers to submit patches to bug 349002. ...
2006-10-06 - Archive of obsolete content
there were a few problems found where ff was hanging on shutdown and some weird behaviors in the download manager. update checker was run; all failures found were expected. build is go for launch. vista testers - needed to test firefox and thunderbird in vista. any test case ideas specific to vista are welcomed. check posting for details. firefox 2 rc2 testing - tim riley announced the l10n builds were completed last night. to help out with testing meet in irc chat room #qa. ...
...ing - tim riley announced the l10n builds were completed last night. to help out with testing meet in irc chat room #qa. test results will be posted here. 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. bug day - in irc chat room #bugday on oct 3rd. reminder from tracy. check posting for times in your region. authors mark d'souza (mdsouza) mohamed attar (mojo) ...
2006-09-29 - Archive of obsolete content
although the w3 validation accepted the generated xhtml as valid, a bug identified within the html working group ignored the invalid elements. ...
...p (e.g., * it's floating, absolutely positioned, or * inline-block). */ virtual nssize computesize(nscoord aavailwidth, nscoord amargin, nscoord aborder, nscoord apadding, prbool ashrinkwrap) = 0; details can be located at refactoring some of nshtmlreflowstate. discussion on how to determine whether there is pending layout changes or reflows when using a popup. it was concluded that a frame model change is utilized within a popup, not a layout change. on the reflow branch, check the dirty and dirty_children framestate flags. that won't help with pending style changes, but it'll work to detect cases when the popup or something in it needs to be reflown. details can be located at fram...
NPFullPrint - Archive of obsolete content
-specific information used during full-page mode printing. syntax typedef struct _npfullprint { npbool pluginprinted; /* true: print fullscreen */ npbool printone; /* true: print one copy */ /* to default printer */ void* platformprint; /* platform-specific */ } npfullprint; fields the data structure has the following fields: pluginprinted determines whether the plug-in prints in full-page mode. values: true: plug-in takes complete control of the printing process and prints full-page. false: (default) plug-in renders its area of the page only (for embedded plug-in). printone not currently in use. should always be false. true: print single copy of page to the default printer. false: display print dialogs so user can choose printer, oth...
... choose printer, other options. platformprint platform-specific printing information. mac os: thprint ms windows: printer's device context description the npp_print function passes the plug-in a pointer to an npprint object (previously allocated by the browser). the npfullprint structure is used when the mode field of npprint is set to np_full. the pluginprinted field of this structure determines whether the plug-in prints in full-page mode or not. if you want the plug-in to take complete control of the printing process, it should print the full page and set the field pluginprinted to true before returning. if you want an embedded plug-in to simply render its area of the page, set pluginprinted to false and return immediately; the browser calls npp_print again with the npembedprint subs...
NPP_NewStream - Archive of obsolete content
type of the stream is provided by the type parameter. the data in the stream can be the file specified in the src attribute of the embed tag, for an embedded instance, or the file itself, for a full-page instance. a plug-in can also request a stream with the function npn_geturl. the browser calls npp_destroystream when the stream completes (either successfully or abnormally). the plug-in can terminate the stream itself by calling npn_destroystream. the parameter stype defines the mode of the stream. values: np_normal (default): delivers stream data to the instance in a series of calls to npp_writeready and npp_write. the plug-in can process the data progressively as it arrives from the network or file system. np_asfileonly: the browser saves stream data to a file in the local cache. wh...
...as an optimization to extract the maximum benefit from existing network connections, the browser continues to read data sequentially out of the stream (as in mode np_normal) until the first npn_requestread call is made. note: in any mode other than np_seek, the application should call npp_destroystream once all data in the stream has been written to the plug-in. the plug-in can also request termination of the stream at any time by calling npn_destroystream. see also npn_newstream, npp_streamasfile, npp_write, npp_writeready, npp_destroystream, npn_requestread, npstream, npn_geturl ...
NPP_WriteReady - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary determines maximum number of bytes that the plug-in can consume. syntax #include <npapi.h> int32 npp_writeready(npp instance, npstream* stream); parameters the function has the following parameters: instance pointer to the current plug-in instance. stream pointer to the current stream. returns returns the maximum number of bytes that an instance is prepared to accept from the stream. description the browser calls npp_writeready before each call to npp_write to determine whether a plug-in can receive data and how many bytes it can receive. this function allows the browser to send only as much data to the instance as it can handle at one time, making resource use more efficient for both the browser and plug-in. t...
...larger buffer, but the plug-in is required to consume only the amount of data returned by npp_writeready. the browser can write a smaller amount of data if desired or necessary; for example, if only 8k of data is available in a network buffer. if the plug-in is allocating memory for the entire stream at once (an as_file stream), it can return a very large number. because it is not processing streaming data, the browser can pass as much data to the instance as necessary in a single npp_write. if the browser receives a value of zero, the data flow temporarily stops. the browser checks to see if the plug-in can receive data again by resending the data at regular intervals. see also npp_write, npstream, npp ...
NPAPI plugin reference - Archive of obsolete content
er to create a stream for the specified url. npn_geturlnotify requests creation of a new stream with the contents of the specified url; gets notification of the result. npn_getvalue allows the plug-in to query the browser for information. npn_getvalueforurl provides information to a plugin which is associated with a given url, for example the cookies or preferred proxy. npn_hasmethod determines whether or not the specified npobject has a particular method. npn_hasproperty determines whether or not the specified npobject has a particular property. npn_identifierisstring determines whether or not an identifier is a string. npn_intfromidentifier returns the integer value corresponding to the given integer identifier. npn_invalidaterect invalidates the specified portion of the plu...
...r. npp_setwindow tells the plug-in when a window is created, moved, sized, or destroyed. npp_streamasfile provides a local file name for the data from a stream. npp_urlnotify notifies the plug-in instance of the completion of a url request. npp_write delivers data to a plug-in instance. (remark: hence the name "npp_write" is misleading - just think of:"data_arrived") npp_writeready determines maximum number of bytes that the plug-in can consume. npprint contains information the plug-in needs to print itself in full-page or embedded mode. npprintcallbackstruct contains information required by the platformprint field of the npembedprint structure during embedded mode printing on unix systems. nppvariable see npn_setvalue. nprect represents a rectangular area of a plug-in's con...
Plugins - Archive of obsolete content
that may be helpful. more information about these tools can be found on the external resources page. plugins are different from extensions, which modify or enhance the functionality of the browser itself. plugins are also different from search plugins, which plug additional search engines in the search bar. gecko plugin api reference (npapi) this reference describes the application programming interfaces for npapi plugins and provides information about how to use these interfaces. site author guide for click-to-activate plugins these guidelines will help website authors use plugins when they are blocked by default with the firefox click-to-activate feature. scripting plugins (npruntime) this reference describes the new cross-browser npapi extensions that let plugins be scriptab...
...bugging for multi-process plugins how to create a plugin log to aid in debugging problems with multi-process plugins. writing a plugin for mac os x learn how to write a plugin for mac os x; a template xcode project is provided. monitoring plugins use an observer service notification to monitor the amount of time spent executing calls in plugins. this can be useful when trying to determine if a plug-in is consuming too many resources. scripting plugins: macromedia flash this article explains how javascript can be used to access methods from within the flash plugin, as well as how a feature called fscommands can be used to access javascript functions from within the flash animation. plugins: the first install problem the first install problem is the name given to the cond...
What is RSS - Archive of obsolete content
s 2.0 was changed from its original specification by userland. and although these are each different, they all label themselves as rss 2.0 on the <rss> element. so now, at this point, we still have netscape's rss 0.91 (since netscape never deprecated it) although most people don't use it anymore. most people use either the rdf-based rss 1.0 or the xml-based rss 2.0, with the xml-based rss 2.0 seeming to be the most popular. (this tutorial uses rss 2.0.) how rss is used today today, rss is mostly used for syndication. syndication is the process of telling others that you have content for them to consume. in other words, when you syndicate, you are telling everyone something like: "hey everyone, i've got articles that i want everyone to come and read. just subscribe to my rss feed and you wi...
...ss. in fact, the only real difference between the news/blogger rss and the internet radio/internet television rss is that the news/blogger rss uses the <link> element and the internet radio/internet television rss uses the <enclosure> element. note: these rss examples are very very simple. and were designed to give you an idea about what rss basically looks like. all these rss examples are very minimal. when you create your own rss feeds, you will likely want to make them more complex than these and include additional rss elements and make use of the various rss modules. ...
SAX - Archive of obsolete content
starting with firefox 2, a sax parser is available to xul applications and extensions. for more information, please see sax homepage. quick start the sax parser functionality is available through the xml reader component. ...
...)) throw components.results.ns_error_no_interface; return this; } }; start parsing the xml reader component can parse xml from a string, an nsiinputstream, or asynchronously via the nsistreamlistener interface. ...
Digital Signatures - Archive of obsolete content
signed. if they don't match, the data may have been tampered with since it was signed, or the signature may have been created with a private key that doesn't correspond to the public key presented by the signer. if the two hashes match, the recipient can be certain that the public key used to decrypt the digital signature corresponds to the private key used to create the digital signature. confirming the identity of the signer, however, also requires some way of confirming that the public key really belongs to a particular person or other entity. for a discussion of the way this works, see "introduction to public-key cryptography." the significance of a digital signature is comparable to the significance of a handwritten signature. once you have signed some data, it is difficult to deny doi...
...this quality of digital signatures provides a high degree of nonrepudiation; that is, digital signatures make it difficult for the signer to deny having signed the data. in some situations, a digital signature may be as legally binding as a handwritten signature. ...
TCP/IP Security - Archive of obsolete content
works can be protected at this layer without modifying any applications on the clients or the servers. in some environments, network layer controls such as internet protocol security (ipsec) provide a much better solution than transport or application layer controls because of the difficulties in adding controls to individual applications. network layer controls also provide a way for network administrators to enforce certain security policies. another advantage of network layer controls is that since ip information (e.g., ip addresses) is added at this layer, the controls can protect both the data within the packets and the ip information for each packet. however, network layer controls provide less control and flexibility for protecting specific applications than transport and applicati...
...red, it can provide any combination of the following types of protection: confidentiality. ssl can ensure that data cannot be read by unauthorized parties. this is accomplished by encrypting data using a cryptographic algorithm and a secret key—a value known only to the two parties exchanging data. the data can only be decrypted by someone who has the secret key. integrity. ssl can determine if data has been changed (intentionally or unintentionally) during transit. the integrity of data can be assured by generating a message authentication code (mac) value, which is a keyed cryptographic checksum of the data. if the data is altered and the mac is recalculated, the old and new macs will differ. peer authentication. each ssl endpoint can confirm the identity of the other ssl endp...
Threats - Archive of obsolete content
plaining what they are and how they can affect network traffic. a threat is any circumstance or event with the potential to adversely impact data or systems via unauthorized access, destruction, disclosure, or modification of information, and/or denial of service. threats may involve intentional actors (e.g., attacker who wants to access information on a server) or unintentional actors (e.g., administrator who forgets to disable user accounts of a former employee.) threats can be local, such as a disgruntled employee, or remote, such as an attacker in another geographical area. a threat source is the cause of a threat, such as a hostile cyber or physical attack, a human error of omission or commission, a failure of organization-controlled hardware or software, or other failure beyond the ...
...or software, or other failure beyond the control of the organization. a threat event is an event or situation initiated or caused by a threat source that has the potential for causing adverse impact. many threats against data and resources are possible because of mistakes—either bugs in operating system and applications that create exploitable vulnerabilities, or errors made by end users and administrators. network traffic typically passes through intermediate computers, such as routers, or is carried over unsecured networks, such as wireless hotspots. because of this, it can be intercepted by a third party. threats against network traffic include the following: eavesdropping. information remains intact, but its privacy is compromised. for example, someone could learn your credit car...
Sunbird Theme Tutorial - Archive of obsolete content
change the next six lines to describe your theme. ensure that the internal name is a single word. note: if your theme is for a version of sunbird later th...
...ou made. developing your theme to develop your theme, make further changes to the theme files. you might prefer to do some design work in an image editor first, so that you have a clear design concept to implement. understanding sunbird's user interface to understand sunbird's user interface, go to sunbird's program directory, then to the <tt>chrome/content/calendar</tt> directory there. examine the files there to understand how sunbird's user interface is constructed. the basic interface is written in xul, but some parts are constructed using xbl or javascript. to discover details of the interface, you can also use the dom inspector tool in firefox. install a compatible test build of the calendar extension in firefox 1.5, and examine its interface. the details are mostly the same as in...
Table Reflow Internals - Archive of obsolete content
ses a reflow state (in) and a reflow metrics (in/out) review of reflow the reflow state: is a node in a tree structurally equivalent to the frame tree of reflow participants contains: reflow type, avail size, various computed values, resolved style structs possible request for preferred size and more. review of reflow the reflow metrics contains: max element size (if requested) - the minimum size it can be preferred size (if requested) - the size it would like to be given no size constraints. desired size - the size it would like to be given the avail size. this is equivalent to preferred size if the avail size is not constrained. review of reflow the reflowee sets various sizes in the reflow metrics after (possibly) reflowing some or all of its children which reflows it chil...
...en there is a height on the table, the table doesn't allocate extra height to rows until after it does a pass 2 reflow and then it is too late this can be fixed by doing a special 3rd pass reflow special reflow example <table border=2 width=300> <tr> <td> this cell's width is constrained by the table and image widths. its exact height is hard to determine. </td> <td> <img src=raptor.jpg width=200 height=100%> </td> </tr> </table> this cell's width is constrained by the table and image widths. its height is hard to determine. the image needs to be as high as the cell. special height reflow the reflow state holds an observer and initiator observer is the table cell used as the height basis set by fram...
Common Firefox theme issues and solutions - Archive of obsolete content
with "boilerplate" copy and paste review notes for common theme issues. this document was started on july 27, 2012 so it will take some time to completely fill in and some issues still need to have solutions written for them. operating system specific issues windows 7 windows 7 aero missing right-hand title bar buttons when tabs are on top and the menu bar is disabled, firefox is missing the min/max/restore/close button on the right side of the title bar. please see the following threads on mozillazine for solutions to this issue: http://forums.mozillazine.org/viewtopic.php?f=18&t=2131121 http://forums.mozillazine.org/viewtopic.php?f=18&t=1953371&start=60 windows 7 aero not going into full screen mode properly on win7 with aero glass support firefox doesn't always go to full screen m...
... web console close button is missing the web console (tools > web developer > web console) is missing its close button, which makes it impossible to close. web console close button sprite mapping is messed up on the web console (tools > web developer > web console) the sprite mapping for the close button is messed up. style inspector style inspector is missing but...
Create Your Own Firefox Background Theme - Archive of obsolete content
re of the right-hand side of the image. submitting your theme images to get started submitting your images, go to the theme submission page: name your theme — pick a unique name for your theme. duplicate names are not allowed, so you may need to try a few times to find a unique name. pick a category and tags — select a category and enter some tags that best describe your theme. keep in mind that a reviewer may reject your theme if it is obvious that your category and/or tags are unrelated to your theme. describe your theme — write a short description of your theme. keep in mind that a reviewer may reject your theme if your description is not an accurate representation of your theme. select a license for your theme — decide on a copyright license for your work. read more about...
... ...
Theme changes in Firefox 4 - Archive of obsolete content
nce in the toolbar customization palette anymore. the theme can now override the value by setting a special css property on the toolbar. the iconsize attribute of the toolbox element in the main browser window (#navigator-toolbox) still reflects the user preference in the toolbar customization palette. use of the iconsize attribute on toolbar elements add-ons use the iconsize attribute to determine which icon they should display when a button is placed in a specific toolbar. iconsize value actual add-on toolbar button icon dimensions (assuming correct stylesheet and images) small 16x16 pixels large 24x24 pixels note: for stock buttons, the theme is free to use icons of any size. however, the theme should be designed in such a way that the above ...
... ...
Using the W3C DOM - Archive of obsolete content
del (dom) standards and may cause javascript errors in standards-compliant browsers. the w3c document object model provides interfaces dom elements to scriptable objects. w3c dom standards are well supported by modern browsers, however the standards are moving target so support for newer features should be tested before use. 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. unsupported dom-related properties the following ie proprietary document object properties are not supported in the w3c document object model: document.layers[] id_attribute_value document.all document.all.id_attribute_value document.all[id...
...therefore, if you wish to read and write these properties from javascript through the dom2, use one of these two approaches: place all of ...
-ms-content-zoom-limit-max - Archive of obsolete content
the -ms-content-zoom-limit-max css property is a microsoft extension that specifies the selected elements' maximum zoom factor. initial value400%applies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednopercentagesthe largest allowed zoom factor. a zoom factor of 100% corresponds to no zooming. larger values zoom in. ...
...nheritednopercentagesthe largest allowed zoom factor. a zoom factor of 100% corresponds to no zooming. larger values zoom in. smaller values zoom out.computed valueas specifiedanimation typediscrete syntax values <percentage> the maximum zoom factor. formal syntax <percentage> specifications not part of any specification. remarks this property constrains the limit for touch zooming as well as values of the mscontentzoomfactor property. this property has no effect on non-zoomable elements. see -ms-content-zooming for details on zoomable elements. starting with windows 8.1, this property is also supported for touchpad interaction. this property requires windows 8 or later. ...
-ms-content-zoom-snap-points - Archive of obsolete content
be placed. the second percentage specifies the distance between subsequent snap-points, both zoomed in and zoomed out from the initial snap-point. snaplist( <percentage># ) specifies the position of individual snap-points as a comma-separated list of percentages, each of which represents a zoom factor. if any value specified is less than that specified by the -ms-content-zoom-limit-min property, the value of -ms-content-zoom-limit-min is used. if any value specified is greater than that specified by the -ms-content-zoom-limit-max property, the value of -ms-content-zoom-limit-max is used. formal syntax snapinterval( <percentage>, <percentage> ) | snaplist( <percentage># ) examples this example demonstrates both types of values for the -ms-content-zoom-snap-points p...
.... in the second selector, each snap-point is listed separately—100%, 200%, 300%, and so on. .snappy1 { -ms-content-zoom-snap-points: snapinterval(0%, 100%); ... } .snappy2 { -ms-content-zoom-snap-points: snaplist(100%, 200%, 300%, 400%, 500%); ... } specifications not part of any specification. remarks this property has no effect on non-zoomable elements. see -ms-content-zooming for details on zoomable elements. when a user pans or scrolls and then lifts his or her contact (for instance, a finger), the content can continue to move with inertia. snap-points can change the animation that runs when the user lifts his or her finger so that you can adjust where the content will stop. by placing snap-points, you can make it easy for your users to manipulate your content and ...
-ms-hyphenate-limit-chars - Archive of obsolete content
the -ms-hyphenate-limit-chars css property is a microsoft extension that specifies one to three values indicating the minimum number of characters in a hyphenated word. if the word does not meet the required minimum number of characters in the word, before the hyphen, or after the hyphen, then the word is not hyphenated. initial valueautoapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete syntax values auto corresponds to a value of 5 2 2, indicating a 5-character word limit, 2 characters required before a hyphenation break, and 2 characters required following a hyphenation break. ...
...enated. initial valueautoapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete syntax values auto corresponds to a value of 5 2 2, indicating a 5-character word limit, 2 characters required before a hyphenation break, and 2 characters required following a hyphenation break. <integer>{1,3} one to three integer values, corresponding to the word limit, the minimum number of characters required before a hyphenation break, and the minimum number of characters required following a hyphenation break, respectively. if the third value is missing it is equal to the second. if the second and third values are missing they are given a value of auto. negative values are not allowed. formal syntax auto | <integer>{1,3} specifications not part of an...
-ms-scroll-snap-points-x - Archive of obsolete content
pecifies where the first snap-point will be placed. the second value specifies the distance between subsequent snap-points both to the left and the right of the initial snap-point. snaplist( <length-percentage># ) specifies the position of individual snap-points as a comma-separated list of values, each of which represents a zoom factor. if any value is less than -ms-scroll-limit-x-min , then -ms-scroll-limit-x-min is used. if any value is greater than -ms-scroll-limit-x-max, then -ms-scroll-limit-x-max is used. formal syntax snapinterval( <length-percentage>, <length-percentage> ) | snaplist( <length-percentage># )where <length-percentage> = <length> | <percentage> examples this example demonstrates both types of values for the -ms-scroll-snap-points-x property. ...
.... (the -ms-scroll-snap-points-x property behaves identically to the -ms-scroll-snap-points-y property, but along the x-axis.) .container { overflow-x: auto; overflow-y: hidden; -ms-scroll-snap-type: mandatory; -ms-scroll-snap-points-x: snapinterval(0%, 100%); width: 480px; height: 270px; } .imagecontainer { -ms-scroll-chaining: chained; -ms-overflow-style: none; -ms-content-zooming: zoom; -ms-scroll-rails: none; -ms-scroll-limit-x-min: 100%; -ms-scroll-limit-x-max: 500%; -ms-scroll-snap-type: proximity; -ms-scroll-snap-points-x: snaplist(100%, 200%, 300%, 400%, 500%); -ms-overflow-style: none; width: 480px; height: 270px; overflow: auto; } specifications not part of any specification. remarks this property requires windows 8 or later. this property ...
-ms-scroll-snap-points-y - Archive of obsolete content
first value specifies where the first snap-point will be placed. the second value specifies the distance between subsequent snap-points both above and below the initial snap-point. snaplist( <length-percentage># ) specifies the position of individual snap-points as a comma-separated list of values, each of which represents a zoom factor. if any value is less than -ms-scroll-limit-y-min , then -ms-scroll-limit-y-min is used. if any value is greater than -ms-scroll-limit-y-max, then -ms-scroll-limit-y-max is used. formal syntax snapinterval( <length-percentage>, <length-percentage> ) | snaplist( <length-percentage># )where <length-percentage> = <length> | <percentage> examples this example demonstrates both types of values for the -ms-scroll-snap-points-y property. ...
.... (the -ms-scroll-snap-points-y property behaves identically to the -ms-scroll-snap-points-x property, but along the y-axis.) .container { overflow-x: auto; overflow-y: hidden; -ms-scroll-snap-type: mandatory; -ms-scroll-snap-points-y: snapinterval(0%, 100%); width: 480px; height: 270px; } .imagecontainer { -ms-scroll-chaining: chained; -ms-overflow-style: none; -ms-content-zooming: zoom; -ms-scroll-rails: none; -ms-scroll-limit-y-min: 100%; -ms-scroll-limit-y-max: 500%; -ms-scroll-snap-type: proximity; -ms-scroll-snap-points-y: snaplist(100%, 200%, 300%, 400%, 500%); -ms-overflow-style: none; width: 480px; height: 270px; overflow: auto; } specifications not part of any specification. remarks this property requires windows 8 or later. this property ...
Function.prototype.isGenerator() - Archive of obsolete content
it was part of an early harmony proposal, but has not been included in the ecmascript 2015 specification. ...
...it was part of an early harmony proposal, but has not been included in the ecmascript 2015 specification. ...
New in JavaScript 1.3 - Archive of obsolete content
bals nan infinity undefined new methods isfinite() function.prototype.call() function.prototype.apply() date.utc() date.prototype.getfullyear() date.prototype.setfullyear() date.prototype.getmilliseconds() date.prototype.setmilliseconds() date.prototype.getutcfullyear() date.prototype.getutcmonth() date.prototype.getutcdate() date.prototype.getutchours() date.prototype.getutcminutes() date.prototype.getutcseconds() date.prototype.getutcmilliseconds() date.prototype.toutcstring() date.prototype.setutcfullyear() date.prototype.setutcmonth() date.prototype.setutcdate() date.prototype.setutchours() date.prototype.setutcminutes() date.prototype.setutcseconds() date.prototype.setutcmilliseconds() other new features strict equality operators unicode support a j...
...ototype.setutcdate() date.prototype.setutchours() date.prototype.setutcminutes() date.prototype.setutcseconds() date.prototype.setutcmilliseconds() other new features strict equality operators unicode support a javascript console was introduced. changed functionality in javascript 1.3 changes to date to conform with ecma-262 new constructor date(year, month, day, [,hours [, minutes [, seconds [, milliseconds ]]]]) additional method parameters: setmonth(month[, date]) sethours(hours[, min[, sec[, ms]]]) setminutes(min[, sec[, ms]]) setseconds(sec[, ms]) the length of an array (property length) is now an unsigned, 32-bit integer. array.prototype.push(): in javascript 1.2, the push method returned the last element added to an arr...
New in JavaScript - Archive of obsolete content
rn more about the ecmascript standards on which the javascript language is based on. ecmascript 5 support implementation status for the current standard ecma-262 edition 5.1 in mozilla-based engines and products. ecmascript 2015 support implementation status for the draft ecma-262 edition 6 (es2015) in mozilla-based engines and products. ecmascript next support implementation status for upcoming ecma-262 features as per the yearly (es2016/es2017/es2018/...) release schedule in mozilla-based engines and products. javascript versions deprecated ( ). the explicit versioning and opt-in of language features was mozilla-specific and are in process of being removed. firefox 4 was the last version which referred to a javascript version (1.8.5). with new ecma standards, javascript language fe...
...ns, and destructuring assignment. javascript 1.8 version shipped in firefox 3. released in june 2008. includes expression closures, generator expressions and array.reduce() javascript 1.8.1 version shipped in firefox 3.5. released on june 30, 2009. includes the tracemonkey jit and supports native json. javascript 1.8.2 version shipped in firefox 3.6. released june 22, 2009. includes only minor changes. javascript 1.8.5 version shipped in firefox 4. released july 27, 2010. includes many new features for ecma-262 edition 5 compliance. this is the last javascript version. ...
Writing JavaScript for XHTML - Archive of obsolete content
in focus (e.g., there is a document.createelementns method). of course, you can still use strings like in document.write(), but it takes a little more effort. ...
...ring(string, "text/xml"); body.appendchild(documentfragment); // assuming 'body' is the body element but be aware that if your string is not well-formed xml (e.g., you have an & where it should not be), then this method will crash, leaving you with a parser error. problem: i want to remain forward compatible! given the direction away from formatting attributes and the possibility of xhtml becoming eventually more prominent (or at least the document author having the possibility of later wanting to make documents available in xhtml for browsers that support it), one may wish to avoid features which are not likely to stay compatible into the future. solution: avoid html-specific dom the html dom , even though it is compatible with xhtml 1.0, is not guaranteed to work with future versions ...
XForms API Reference - Archive of obsolete content
this page is the beginning of the xforms api reference. ...
... this page is the beginning of the xforms api reference. ...
XForms Submit Element - Archive of obsolete content
in the bound node. however, the relevant model item property on the bound node has an effect on a submit. if the bound node is irrelevant, then the submit will be hidden. ...
...ble text - used when appearance = 'minimal' (xhtml only) button displaying a button is the default presentation (xhtml/xul). characteristics analogous widgets are <html:input type="submit"/> and <xul:button/> link/clickable text xforms authors can use this representation if they want to have a widget like a xhtml anchor (xhtml only). characteristics appearance attribute contains the value minimal analogue widget is <html:a onclick="form.submit();"/>. ...
XForms Trigger Element - Archive of obsolete content
in the bound node. however, relevant model item property on the bound node has an effect on a trigger. if the bound node is irrelevant, then the trigger will be hidden. ...
...text - used when appearance = 'minimal' (xhtml only) button displaying a button is the default presentation (xhtml/xul). characteristics analogous widgets are <html:input type="button"/> and <xul:button/> link/clickable text xforms authors can use this representation if they want to have a widget like a xhtml anchor (xhtml only). characteristics appearance attribute contains the value minimal analogue widget is <xhtml:a/>. ...
Choosing Standards Compliance Over Proprietary Practices - Archive of obsolete content
standards so they are able to operate efficiently. they may also incorporate external procedural and/or technical standards. technical standards have traditionally been pioneered through consortiums or standards bodies. the technical standards can be either public, standards-based or a proprietary de facto standard. the purpose of this document is to discuss and emphasize the importance of conforming to open technology standards that are external to the organization. let’s begin the discussion, however, by looking inward to internal procedures, processes and standards. why should organizations have standard procedures at every level? following standards is certainly not a new organizational phenomenon; organizations require their employees to follow common rules, or a common set of standa...
... support staff costs, but also in respect to customer dissatisfaction. that is why organizations also need to apply standards to quality testing. by adopting a set of standards, the qa organization can produce a set of test suites that they can use across multiple projects. by having a standardized set of test suites, the qa organization can easily maintain, verify, and certify the tests, and eliminate redundant testing databases to ensure consistency and reliability. like the engineers, standardization also helps the qa engineers become highly proficient and capable of shifting from project to project. summary as organizations expand product development across multiple devices and product families, integration and compatibility must be a key requirement. adhering to a set of future-focuse...
Fixing Table Inheritance in Quirks Mode - Archive of obsolete content
e the same size as the user's default settings, regardless of the css assigned to ancestor elements such as body. this represented a violation of css inheritance rules, and led many authors to create workarounds such as: <style type="text/css"> body, table, td {font-size: 11px;} </style> recreating legacy behavior to avoid "breaking" older pages that were authored with old-browser behaviors in mind, mozilla and related browsers will mimic old browsers when in "quirks" mode. to do this, the gecko rendering engine uses the following rule in the quirk.css user agent file: /* quirk: cut off all font inheritance in tables and captions except for family. */ table, caption { font-size: -moz-initial; font-weight: -moz-initial; font-style: -moz-initial; font-variant: -moz-initial; } this ...
...inheritance is not desired, authors can use gecko's standards support to overcome the table-font rule shown above. the value -moz-initial is a proprietary value used to apply the user's (or browser's) default setting for a given property to an element. because it is not actually part of css, it is marked with the prefix -moz- in order to avoid confusion about what is or isn't part of css. overcoming legacy behavior all that is needed is a rule that overrides the -moz-initial values with the css2 value inherit. this value is used to force an element to use the same value as its parent element for a given property. /* rule to fix quirks-mode inheritance behavior */ table, caption { font-size: inherit; font-weight: inherit; font-style: inherit; font-variant: inherit; } this rule wil...
Mozilla's DOCTYPE sniffing - Archive of obsolete content
3 / seamonkey 2.1) this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. this page describes behavior of the old html parser in firefox 3.6 and older. it has been replaced by a new html 5 parser in firefox 4 and newer. this document describes how mozilla uses the doctype declaration to determine strict mode vs. quirks mode. the code that makes this determination is currently in determineparsemode() in nsparser.cpp. see bug 1312 and bug 55264 for some of the history of the mode determination. see bug 153032 for the creation of the almost-standards mode around mozilla 1.0. the goals that led to choosing this behavior were the following: almost all existing text/html pages on the web th...
...splayed using quirks mode. (almost all, rather than all, to allow for the following points as well.) authors writing web pages to current standards should be able to trigger strict mode. pages written using any public identifiers in doctype declarations that appear in the future should be displayed using strict mode. in other words, the algorithm is the best approximation we can find for determining which pages were written after mozilla became a known important user-agent on the web. full standards mode the following trigger full standards mode: any document sent with an xml mime type such as text/xml, application/xml, or application/xhtml+xml (since sniffing only occurs for documents sent as text/html). any "doctype html system" as opposed to "doctype html public", except for the ...
Obsolete: XPCOM-based scripting for NPAPI plugins - Archive of obsolete content
hitecture allows xpcom components be scriptable via a different mechanism called xpconnect. we leverage some of these ideas to help you make your netscape communicator 4.x plugins exposed to javascript in mozilla based browsers. in order to make it still possible to script plugins, some changes have been made to the mozilla code. the changes allow to make existing 4.x plugins scriptable with only minor modifications in their code. the present document describes the steps of what should be done to the plugin code to turn it scriptable again. what's in the mozilla code? a couple of lines have been added to the dom code asking a plugin to return a scriptable iid and a pointer to a scriptable instance object. the old plugin api call npp_getvalue is used to retrieve this information from the plugi...
... { // these flags are used by the dom and security systems to signal that // javascript callers are allowed to call this object's scritable methods. ns_imethod getflags(pruint32 *aflags) {*aflags = nsiclassinfo::plugin_object | nsiclassinfo::dom_object; return ns_ok;} ns_imethod getimplementationlanguage(pruint32 *aimplementationlanguage) {*aimplementationlanguage = nsiprogramminglanguage::cplusplus; return ns_ok;} // the rest of the methods can safely return error codes... ns_imethod getinterfaces(pruint32 *count, nsiid * **array) {return ns_error_not_implemented;} ns_imethod gethelperforlanguage(pruint32 language, nsisupports **_retval) {return ns_error_not_implemented;} ns_imethod getcontractid(char * *acontractid) {return ns_error_not_impleme...
XQuery - Archive of obsolete content
ort, extract, and remold data. it offers powerful and yet intuitive searching based on xpath, has sql-like syntax for the query portion, and has scripting features such as function and variable definitions, xml-inclusion, etc. while xquery is currently not supported in firefox (whether through javascript to developers or to browser users), at least one extension has been developed to give a preliminary support for xquery for browser users (and serving as a simple model for how xquery can be implemented within extensions). xquseme is a working proof-of-concept (so far tested on windows and linux with java installed; mac does not work) extension which allows one to perform xqueries on external urls, the currently loaded webpage (even if originally from poorly formed html), and/or xml (includi...
...be used to turn the above extension concept into an xpcom component (giving it access to all open windows), and for berkeley db xml, possibly implementing it in c++ instead, which is that database's original language of development. however, the extension demonstrates a technique which does not depend on using xpcom, while still giving full privileges. tutorials w3schools learn xquery in 10 minutes an introduction to xquery ...
Archive of obsolete content
nk there are many dark matter projects that we don't know about. if you have information about a new project or extra information about an existing project, please feel free to update this page. localizing an extension this article expands upon the previous samples on extension writing by adding localization support to our stock watcher extension. performing a few simple steps makes your extension much easier to localize into various languages without having to edit the xul or javascript files themselves. makefile - .mk files misc top level these pages were moved from the top level of mdn in a spate of furious reorganization. mmgc mmgc is the tamarin (née macromedia) garba...
... based on rdf, but most only being based on xml.) nonetheless, rss is an extremely popular format that is used for syndicating news, blog posts, ipradio, and iptv, with an amazing amount of momentum. sax sax, short forsimple api for xml, is a parsing api. sax was the first widely adopted api for xml in java, and later implemented in several other programming language environments. starting with firefox 2, a sax parser is available to xul applications and extensions. for more information, please see sax homepage. security relying on these obsolete security articles is highly discouraged. doing so may put your systems at risk. solaris 10 build prerequisites sunbird theme tutorial ...
Introduction to game development for the Web - Game development
db a powerful data storage api for maintaining user data on their own computer or device. a great way to save game state and other information locally so it doesn't have to be downloaded every time it's needed. also useful to help make your game playable even when the user isn't connected to the web (such as when they're stuck on an airplane for hours on end). javascript javascript, the programming language used on the web, is blazing fast in modern browsers and getting faster all the time. 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. pointer lock api the pointer lock api lets you lock the mouse or other pointing device within your game's interface so that instead of absolute cursor positioning ...
...you the power to control audio and video data, including teleconferencing and transmitting other application data back and forth between two users. want your players to be able to talk to each other while blowing up monsters? this is the api for you. websockets the websocket api lets you connect your app or site to a server to transmit data back and forth in real-time. perfect for multiplayer gaming action, chat services, and so forth. web workers workers give you the ability to spawn background threads running their own javascript code, to take advantage of modern, multi-core processors. xmlhttprequest and file api the combination of xmlhttprequest and the file api lets you send and receive any kind of data you want (don't let the "xml" throw you!) from a web server. this is a great wa...
Game monetization - Game development
when you've spent your time building a game, distributing it and promoting it you should consider earning some money out of it. if your work is a serious endeavour on the path to becoming an independent game developer able to make a living, read on and see what your options are. the technology is mature enough; now it's just about chosing the right approach. paid games the first, most obvious choice that may come to your mind might be selling the games the way it is done for huge aaa titles — with a fixed, up front price. even though the digital market is key and you don't need to print covers and put your game in a physical store in boxes, to earn decent money on selling your games for a fixed price you have to invest your time and money in marketing. only the best games will bre...
...but only if the player knows you and feels that it will help you in your situation. that's why carefully managing your community is so important. it worked with the js13kgames competition — every participant got a free t-shirt, and some even gave back a few bucks to help keep it going in years to come. summary there are many ways to earn money — everything that applies to the "normal" aaa gaming world can be, more or less, applied to casual html5 games. you might however also focus on selling licenses, doing branding, or earning on a revenue share basis from the advertisements. it's totally up to you which path you're going to follow. ...
2D collision detection - Game development
+ rect1.height > rect2.y) { // collision detected! } // filling in the values => if (5 < 30 && 55 > 20 && 5 < 20 && 55 > 10) { // collision detected! } rect code <div id="cr-stage"></div> <p>move the rectangle with arrow keys. ...
... circles. this algorithm works by taking the centre points of the two circles and ensuring the distance between the centre points are less than the two radii added together. playable code <div id="cr-stage"></div> <p>move the circle with arrow keys. ...
Explaining basic 3D theory - Game development
a color or an image. if we connect the geometry with the material we will get a mesh. rendering pipeline the rendering pipeline is the process by which images are prepared and output onto the screen. 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. terminology used in the diagram above is as follows: a primitive: an input to the pipeline — it's built from vertices and can be a triangle, point or line. a fragment: a 3d projection of a pixel, which has all the same attributes as a pixel. a pixel: a point on the screen arranged in the 2d grid, which holds an rgba color. vertex and fragment processing are programmable — you can write your o...
...ments are combined from pixels. applying textures onto objects during the fragment processing stage of the rendering pipeline allows us to adjust it by wrapping and filtering it if necessary. texture wrapping allows us to repeat the 2d image around the 3d object. texture filtering is applied when the original resolution or the texture image is different from the displayed fragment — it will be minified or magnified accordingly. lighting the colors we see on the screen is a result of the light source interacting with the surface colors of the object's material. light might be absorbed or reflected. the standard phong lighting model implemented in webgl has four basic types of lighting: diffuse: a distant directional light, like the sun. specular: a point of light, just like a light bu...
Building up a basic demo with Three.js - Game development
any other webgl library available, and you should feel free to try another library, such as copperlicht, glge, or playcanvas. environment setup to start developing with three.js, you don't need much. you should: make sure you are using a modern browser with good webgl support, such as the latest firefox or chrome. create a directory to store your experiments in. save a copy of the latest minimized three.js library inside your directory. open the three.js documentation in a separate tab — it is useful to refer to. html structure here's the html structure we will use: <!doctype html> <html> <head> <meta charset="utf-8"> <title>mdn games: three.js demo</title> <style> body { margin: 0; padding: 0; } canvas { width: 100%; height: 100%; } </style> </head> <body> <script src...
...hree.js library inside your directory. open the three.js documentation in a separate tab — it is useful to refer to. html structure here's the html structure we will use: <!doctype html> <html> <head> <meta charset="utf-8"> <title>mdn games: three.js demo</title> <style> body { margin: 0; padding: 0; } canvas { width: 100%; height: 100%; } </style> </head> <body> <script src="three.min.js"></script> <script> var width = window.innerwidth; var height = window.innerheight; /* all our javascript code goes here */ </script> </body> </html> it contains some basic information like the document <title>, and some css to set the width and height of the <canvas> element, that three.js will insert on the page to 100% to fill the entire available viewport space. the first <script> ele...
3D games on the Web - Game development
webgl is basically an opengl es 2.0 for the web — it's a javascript api providing tools to build rich interactive animations and of course, also games. you can generate and render dynamic 3d graphics with javascript that is hardware accelerated. documentation and browser support the webgl project documentation and specification is maintained by the khronos group, not the w3c as with most of the web apis. support on modern browsers is very good, even on mobile, so you don't have to worry about that too much. the main browsers are all supporting webgl and all you need to focus on is optimizing the performance on the devices you use. ...
.... you should definitely check out glsl shaders article to learn more about them. collision detection it's hard to imagine a game without collision detection — we always need to work out when something is hitting something else. we have information available for you to learn from: 2d collision detection 3d collision detection webxr the concept of virtual reality is not new, but it's storming onto the web thanks to hardware advancements such as the oculus rift, and the (currently experimental) webxr api for capturing information from vr and ar hardware and making it available for use in javascript applications. for more, see webxr device api. 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 t...
Desktop mouse and keyboard controls - Game development
keyboard the whole game can be controlled with just the keyboard and nothing else. the built in this.game.input.keyboard object manages the input from the keyboard and has a few helpful methods like addkey() and isdown(). there's also the ...
... this hides the intro and starts the actual game, without us having to set up another new key control just for this. pause and game over screens to make the game fully playable with keyboard it should be possible to go back to the main menu, continue playing, or restart the game from the pause and game over screens. it can be done exactly the same as before — by capturing key codes and performing actions. for example, by specifying phaser.keycode.backspace or phaser.keycode.delete you can hook up an action to fire when the delete/backspace button is pressed. summary ok, we've dealt with touch, keyboard and mouse controls. now let's move on to look at how to set up the game to be controlled using a console gamepad, using the gamepad api. previous overview: control mechanisms next...
Implementing game control mechanisms - Game development
like this: as you can see there are folders for images, javascript files, fonts and sound effects. the src folder contains the javascript files split as a separate states — boot.js, preloader.js, mainmenu.js and game.js — these are loaded into the index file in this exact order. the first one initializes phaser, the second preloads all the assets, the third one controls the main menu welcoming the player, and the fourth controls the actual gameplay. every state has its own default methods: preload(), create(), and update(). the first one is needed for preloading required assets, create() is executed once the state had started, and update() is executed on every frame. for example, you can define a button in the create() function: create: function() { // ... var buttonenclave = thi...
...there's also a small online demo with full source code available on github where the basic support for the control mechanisms described in the articles is implemented in pure javascript. it will be explained in the given articles themselves below, but you can play with it already, and use the code however you want for learning purposes. the articles javascript is the perfect choice for mobile gaming because of html5 being truly multiplatform; all of the following articles focus on the apis provided for interfacing with different control mechanisms: mobile touch controls — the first article will kick off with touch, as the mobile first approach is very popular. desktop mouse and keyboard controls — when playing on a desktop/laptop computer, providing keyboard and mouse controls is es...
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. it features a case study game — hungry fridge, created by enclave games. controls for web games historically playing games on a console connected to your tv was always a totally different experience to gaming on the pc, mostly because of the unique controls. eventually, extra drivers and plugins allowed us to use console gamepads with desktop games — either native games or those running in the browser. 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. the gamepad api achieves this by providing a...
... native games or those running in the browser. 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. the gamepad api achieves this by providing an interface exposing button presses and axis changes that can be used inside javascript code to handle the input. these are good times for browser gaming. api status and browser support the gamepad api is still at the working draft stage in the w3c process, which means its implementation might still change, but saying that the browser support is already quite good. firefox 29+ and chrome 35+ support it out of the box. opera supports the api in version 22+ (not surprising given that they now use chrome's blink engine.) and microsoft implemented...
Tiles and tilemaps overview - Game development
out of small, regular-shaped images called tiles. this results in performance and memory usage gains — big image files containing entire level maps are not needed, as they are constructed by small images or image fragments multiple times. 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. some popular games that use this technique are super mario bros, pacman, zelda: link's awakening, starcraft, and sim city 2000. think about any game that us...
...re located in the level or game world) and screen coordinates (the actual position where those elements are rendered on the screen). the world coordinates can be expressed in terms of tile position (row and column of the map) or in pixels across the map, depending on the game. to be able to transform world coordinates into screen coordinates, we need the coordinates of the camera, since they determine which section of the world is being displayed. here are examples showing how to translate from world coordinates to screen coordinates and back again: // these functions assume that the camera points to the top left corner function worldtoscreen(x, y) { return {x: x - camera.x, y: y - camera.y}; } function screentoworld(x,y) { return {x: x + camera.x, y: y + camera.y}; } rendering a t...
Mouse controls - Game development
hat. add the following function to your code, below the previous line you added: function mousemovehandler(e) { var relativex = e.clientx - canvas.offsetleft; if(relativex > 0 && relativex < canvas.width) { paddlex = relativex - paddlewidth/2; } } in this function we first work out a relativex value, which is equal to the horizontal mouse position in the viewport (e.clientx) minus the distance between the left edge of the canvas and left edge of the viewport (canvas.offsetleft) — effectively this is equal to the distance between the canvas left edge and the mouse pointer. if the relative x pointer position is greater than zero and lower than the canvas width, the pointer is within the canvas boundaries, and the paddlex position (anchored on the left edge of the paddle)...
...t edge of the canvas and left edge of the viewport (canvas.offsetleft) — effectively this is equal to the distance between the canvas left edge and the mouse pointer. if the relative x pointer position is greater than zero and lower than the canvas width, the pointer is within the canvas boundaries, and the paddlex position (anchored on the left edge of the paddle) is set to the relativex value minus half the width of the paddle, so that the movement will actually be relative to the middle of the paddle. the paddle will now follow the position of the mouse cursor, but since we're restricting the movement to the size of the canvas, it won't disappear completely off either side. compare your code this is the latest state of the code to compare against: exercise: adjust the boundaries o...
Initialize the framework - Game development
vas> element generated by the framework. ...
...t, we need to go through the process of downloading the phaser source code and applying it to our html document. this tutorial uses phaser v2 — it won't work with the current version on phaser (v3). the v2 library is still available on the phaser download page, below the links for the v3 download. go to the phaser download page. choose an option that suits you best — i would recommend the min.js option as it keeps the source code smaller, and you are unlikely need to go through the source code anyway. save the phaser code inside a /js directory in the same location as your index.html file. update the src value of the first <script> element as shown above. walking through what we have so far at this point we have a charset defined, <title> and some basic css in the header to reset...
Visual-js game engine - Game development
1) click create application 2) enter new application name in input prompt 3) select folder for server part of application (important : www is not secure place) 4) select folder for client part of application ( any path in www) 5) new app name will appear in project list , select and click open application 6) open your server fold...
... now you can use on-page-editor (nice for visual setup , checking positions and dimensions - not for logic ) . manual start from cmd : server_folder/node editor.js after starting...
Asynchronous - MDN Web Docs Glossary: Definitions of Web-related terms
once. and both sides can continue to send and receive messages whenever they wish, instead of having to schedule them around each other. when software communicates asynchronously, a program may make a request for information from another piece of software (such as a server), and continue to do other things while waiting for a reply. 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. software design asynchronous software design expands upon the concept by building code that allows a program to ask th...
...sign expands upon the concept by building code that allows a program to ask that a task be performed alongside the original task (or tasks), without stopping to wait for the task to complete. when the secondary task is completed, the original task is notified using an agreed-upon mechanism so that it knows the work is done, and that the result, if any, is available. there are a number of programming techniques for implementing asynchronous software. see the article asynchronous javascript for an introduction to them. learn more technical reference fetching data from the server (learning area) synchronous ...
Bézier curve - MDN Web Docs Glossary: Definitions of Web-related terms
web related graphics and animations use cubic béziers, which are curves with four control points p0, p1, p2, and p3. to draw the curve, two imaginary lines are drawn, one from p0 to p1 and the other from p1 to p2. ...
...adily on the first helper line and the end point on the second helper line. ...
Constructor - MDN Web Docs Glossary: Definitions of Web-related terms
essentially, a constructor in javascript is usually declared at the instance of a class. ...
... to call the constructor of the class in javascript, use a new operator to assign a new object reference to a variable. function default() { } // a new reference of a default object assigned to a // local variable defaultreference var defaultreference = new default(); learn more general knowledge constructor on wikipedia technical reference the constructor in object oriented programming for javascript on mdn new operator in javascript on mdn ...
Continuous Media - MDN Web Docs Glossary: Definitions of Web-related terms
css can be used in a variety of contexts, including print media and some css, in particular, that used for layout behaves differently depending on the context it is in. continuous media, therefore, identifies a context where the content is not broken up, it flows continuously. ...
... css can be used in a variety of contexts, including print media and some css, in particular, that used for layout behaves differently depending on the context it is in. continuous media, therefore, identifies a context where the content is not broken up, it flows continuously. ...
First-class Function - MDN Web Docs Glossary: Definitions of Web-related terms
but it won't affect the way we invoke it. ...
...signed as a value to a variable. 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. even if your function was named, you can use the variable name to invoke it. naming it will be helpful when debugging your code. but it won't affect the way we invoke it. example | pass a function as an argument javascript function sayhello() { return "hello, "; } function greeting(hellomessage, name) { console.log(hellomessage() + name); } // pass `sayhello` as an argument to `greeting` function greeting(sayhello, "javascript!"); we are passing our sayhello() functi...
Grid Lines - MDN Web Docs Glossary: Definitions of Web-related terms
late-rows: 100px 100px; } lines can be addressed using their line number. in a left-to-right language such as english, column line 1 will be on the left of the grid, row line 1 on the top. lines numbers respect the writing mode of the document and so in a right-to-left language for example, column line 1 will be on the right of the grid. the image below shows the line numbers of the grid, assuming the language is left-to-right. lines are also created in the implicit grid when implicit tracks are created to hold content positioned outside of the explicit grid, however these lines cannot be addressed by a number. placing items onto the grid by line number having created a grid, you can place items onto the grid by line number. in the following example the item is positioned from colum...
...when placing an item, you can then use these names instead of the line number, as demonstrated below. * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; display: grid; ...
Intrinsic Size - MDN Web Docs Glossary: Definitions of Web-related terms
element is the size it would be based on its content, if no external factors were applied to it. for example, inline elements are sized intrinsically: width, height, and vertical margin and padding have no impact, though horizontal margin and padding do. how intrinsic sizes are calculated is defined in the css intrinsic and extrinsic sizing specification. ...
...xternal factors were applied to it. for example, inline elements are sized intrinsically: width, height, and vertical margin and padding have no impact, though horizontal margin and padding do. how intrinsic sizes are calculated is defined in the css intrinsic and extrinsic sizing specification. intrinsic sizing takes into account the min-content and max-content size of an element. 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. for a box containing a string of text, the min-content size would be defined by the longest word. the keyword value of min-content for the width property will size an element according to the min-content size. the max-content size is the oppos...
OOP - MDN Web Docs Glossary: Definitions of Web-related terms
oop (object-oriented programming) is an approach in programming in which data is encapsulated within objects and the object itself is operated on, rather than its component parts. javascript is heavily object-oriented. it follows a prototype-based model (as opposed to class-based). ...
... oop (object-oriented programming) is an approach in programming in which data is encapsulated within objects and the object itself is operated on, rather than its component parts. javascript is heavily object-oriented. it follows a prototype-based model (as opposed to class-based). ...
Object - MDN Web Docs Glossary: Definitions of Web-related terms
object refers to a data structure containing data and instructions for working with the data. objects sometimes refer to real-world things, for example a car or map object in a racing game. ...
... object refers to a data structure containing data and instructions for working with the data. objects sometimes refer to real-world things, for example a car or map object in a racing game. ...
RTCP (RTP Control Protocol) - MDN Web Docs Glossary: Definitions of Web-related terms
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. ...
... 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. ...
RTP (Real-time Transport Protocol) and SRTP (Secure RTP) - MDN Web Docs Glossary: Definitions of Web-related terms
rtp is rarely used alone; instead, it is used in conjunction with other protocols like rtsp and sdp. ...
... rtp is rarely used alone; instead, it is used in conjunction with other protocols like rtsp and sdp. ...
Round Trip Time (RTT) - MDN Web Docs Glossary: Definitions of Web-related terms
round trip time (rtt) is the length time it takes for a data packet to be sent to a destination plus the time it takes for an acknowledgment of that packet to be received back at the origin. the rtt between a network and server can be determined by using the ping command. ...
... see also time to first byte (ttfb) latency ...
SQL Injection - MDN Web Docs Glossary: Definitions of Web-related terms
can gain unauthorized access to a database or to retrieve information directly from the database. many data breaches are due to sql injection. how it works after entering username and password, behind the gui the sql queries work as follows: "select count(*) from users where username=' " + txt.user.text+" ' and password=' "+ txt.password.text+" ' "; now suppose user enters the username: admin and password: passwd123, so after clicking on the log in button, sql query will run as follows: "select count(*) from users where username=' admin ' and password=' passwd123 ' "; if the credentials are correct, then the user is allowed to log in, so it's a very simple (and therefore insecure) mechanism. hackers use this insecurity to gain unauthorized access. hackers use a simple string call...
...the log in button, sql query will run as follows: "select count(*) from users where username=' admin ' and password=' passwd123 ' "; if the credentials are correct, then the user is allowed to log in, so it's a very simple (and therefore insecure) mechanism. hackers use this insecurity to gain unauthorized access. hackers use a simple string called a magical string, for example: username: admin password: anything 'or'1'='1 after clicking on the login button, the sql query will work as follows: "select count(*) from users where username=' admin ' and password=' anything 'or'1'='1 ' "; just take a closer look at the above query's password section. password=' anything 'or'1'='1 ' the password is not 'anything', hence password=anything results in false, but '1'='1' is a true statem...
Semantics - MDN Web Docs Glossary: Definitions of Web-related terms
would you need to look at the code to understand what the function did if it was called build('peach'), or createliwithcontent('peach')? semantics in css in css, consider styling a list with li elements representing different types of fruits. ...
...sider its contents as important keywords to influence the page's search rankings (see seo) screen readers can use it as a signpost to help visually impaired users navigate a page finding blocks of meaningful code is significantly easier than searching though endless divs with or without semantic or namespaced classes suggests to the developer the type of data that will be populated semantic naming mirrors proper custom element/component naming when approaching which markup to use, ask yourself, "what element(s) best describe/represent the data that i'm going to populate?" for example, is it a list of data?; ordered, unordered?; is it an article with sections and an aside of related information?; does it list out definitions?; is it a figure or image that needs a caption?; should it have...
State machine - MDN Web Docs Glossary: Definitions of Web-related terms
stem waiting to execute a transition. a transition is a set of actions to execute when a condition is fulfilled or an event received. in a state diagram, circles represent each possible state and arrows represent transitions between states. looking at the final state, you can discern something about the series of inputs leading to that state. ...
...he final state, you can discern something about the series of inputs leading to that state. there are two types of basic state machines: deterministic finite state machine this kind allows only one possible transition for any allowed input. this is like the "if" statement in that if x == true then dothis else dothat is not possible. the computer must perform one of the two options. non-deterministic finite state machine given some state, an input can lead to more than one different state. . figure 1: deterministic finite state machine in figure 1, the state begins in state 1; the state changes to state 2 given input 'x', or to state 3 given input 'y'. figure 2: non-deterministic finite state machine in figure 2, given input 'x', the state can persist or change to state 2. no...
Symbol - MDN Web Docs Glossary: Definitions of Web-related terms
guaranteed to be unique. // even if we create many symbols with the same description, // they are different values. note: if you are familiar with ruby's (or another language) that also has a feature called "symbols", please don’t be misguided. javascript symbols are different. symbol type is a new feature in ecmascript 2015. there is no ecmascript 5 equivalent for symbol. in some programming languages, the symbol data type is referred to as an "atom." symbols don't "auto-convert" to strings most values in javascript support implicit conversion to a string. for instance, we can alert almost any value, and it will work. symbols are special. they don’t auto-convert. for example: let sym = symbol("sym") alert(sym) // typeerror: cannot convert a symbol value to a string that’s...
...ascript's run-time infrastructure, except through these reflective methods. ...
Syntax - MDN Web Docs Glossary: Definitions of Web-related terms
pply to writing it, such as indentation requirements in python. syntax varies from language to language (e.g., syntax is different in html and javascript). although languages can share few similarities in terms of their syntaxes for example "operand operator operand" rule in javascript and python. this does not mean the two langauges share similarities with syntax. syntax applies both to programming languages (commands to the computer) and markup languages (document structure information) alike. syntax only governs ordering and structure; the instructions must also be meaningful, which is the province of semantics. code must have correct syntax in order to compile correctly, otherwise a syntax error occurs. even small errors, like a missing parenthesis, can stop source code from compiling...
... to compile correctly, otherwise a syntax error occurs. ...
TCP slow start - MDN Web Docs Glossary: Definitions of Web-related terms
ppearance of network congestion whose capabilities are initially unknown, and slowly increases the volume of information diffused until the network's maximum capacity is found. to implement tcp slow start, the congestion window (cwnd) sets an upper limit on the amount of data a source can transmit over the network before receiving an acknowledgment (ack). the slow start threshold (ssthresh) determines the (de)activation of slow start. when a new connection is made, cwnd is initialized to one tcp data or acknowledgment packet, and waits for an acknowledgement, or ack. when that ack is received, the congestion window is incremented until the cwnd is less than ssthresh. slow start also terminates when congestion is experienced. congestion control congestion itself is a state that happens with...
... the user's client then confirms delivery by returning acknoledgements, or acks. the connection has a limited capacity depending on hardware and network conditions. if the server sends too many packets too quickly, they will be dropped. meaning, there will be no acknowledgement. the server registers this as missing acks. congestion control algorithms use this flow of sent packets and acks to determine a send rate. see also populating the page: how browsers work http overview ...
Tree shaking - MDN Web Docs Glossary: Definitions of Web-related terms
t and export statements in es2015 to detect if code modules are exported and imported for use between javascript files. ...
...orted for use between javascript files. in modern javascript applications, we use module bundlers (e.g., webpack or rollup) to automatically remove dead code when bundling multiple javascript files into single files. ...
Time to first byte - MDN Web Docs Glossary: Definitions of Web-related terms
t receives the first byte of information from the server. ...
...t byte of information from the server. ...
CSS and JavaScript accessibility best practices - Learn web development
y for the right job! think carefully about whether you need that shiny javascript-powered 3d information box, or whether plain old text would do. think carefully about whether you need a complex non-standard form widget, or whether a text input would do. and don't generate all your html content using javascript if at all possible. keeping it unobtrusive you should keep unobtrusive javascript in mind when creating your content. the idea of unobtrusive javascript is that it should be used wherever possible to enhance functionality, not build it in entirely — basic functions should ideally work without javascript, although it is appreciated that this is not always an option. but again, a large part of it is using built-in browser functionality where possible. good example uses of unobtrusiv...
...without a page reload (screen readers won't pick this up or alert users to it by default): <div class="errors" role="alert" aria-relevant="all"> <ul> </ul> </div> we will explain these attributes in our next article, which covers wai-aria in much more detail. note: some of you will probably be thinking about that fact that html5 forms have built-in validation mechanisms like the required, min/minlength, and max/maxlength attributes (see the <input> element reference for more information). we didn't end up using these in the demo because cross-browser support for them is patchy (for example ie10 and above only). note: webaim's usable and accessible form validation and error recovery provides some further useful information about accessible form validation. other javascript accessi...
Handling different text directions - Learn web development
his as part of the nature of css. the web is not just for languages that are displayed left-to-right! due to the fact that writing mode and direction of text can change, newer css layout methods do not refer to left and right, and top and bottom. instead they will talk about start and end along with this idea of inline and block. don't worry too much about that right now, but keep these ideas in mind as you start to look at layout; you will find it really helpful in your understanding of css. logical properties and values the reason to talk about writing modes and direction at this point in your learning however, is because of the fact we have already looked at a lot of properties which are tied to the physical dimensions of the screen, and make most sense when in a horizontal writing mode...
...ke a lot of sense once you start also dealing with layout methods such as flexbox and grid. test your skills! we have covered a lot in this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: writing modes. summary the concepts explained in this lesson are becoming increasingly important in css. an understanding of the block and inline direction — and how text flow changes with a change in writing mode — will be very useful going forward. it will help you in understanding css even if you never use a writing mode other than a horizontal one. in the next module we will take a good look at overflow in css. previous overview: building blocks next ...
Overflowing content - Learn web development
eywords are specified, the first applies to overflow-x and the second applies to overflow-y. otherwise, both overflow-x and overflow-y are set to the same value. for example, overflow: scroll hidden would set overflow-x to scroll and overflow-y to hidden. if you only want scrollbars to appear when there is more content than can fit in the box, use overflow: auto. this allows the browser to determine if it should display scrollbars. in the example below, remove content until it fits into the box. you should see the scrollbars disappear. overflow establishes a block formatting context when you use a value of overflow such as scroll or auto, you create a block formatting context (bfc). the content of the box that you have changed the value of overflow for acquires a self-contained layout.
...ainers to align bottoms of boxes. these boxes may otherwise have no relationship to each other. this was fragile. in a legacy application, you may encounter a box where content is overlaying other content on the page. now you can recognize that this happens with overflow. ideally, you will refactor the layout to not rely on fixed-height containers. when developing a site, always keep overflow in mind. test designs with large and small amounts of content. increase the font sizes of text. generally ensure that your css works in a robust way. changing the value of overflow to hide content, or to add scrollbars, is likely to be reserved for a few select use cases. (for example, where you intend to have a scrolling box) test your skills! there is a lot to absorb from this lesson! can you rememb...
Sizing items in CSS - Learn web development
his is not the case! when you use margin and padding set in percentages, the value is calculated from the inline size — therefore the width when working in a horizontal language. in our example, all of the margins and padding are 10% of the width. this means you can have equal-sized margins and padding all around the box. this is a fact worth remembering if you do use percentages in this way. min- and max- sizes in addition to giving things a fixed size, we can ask css to give an element a minimum or a maximum size. if you have a box that might contain a variable amount of content, and you always want it to be at least a certain height, you could set the min-height property on it. the box will always be at least this height, but will then grow taller if there is more content than the box...
... in the example below you can see two boxes, both with a defined height of 150 pixels. the box on the left is 150 pixels tall; the box on the right has content that needs more room, and so it has grown taller than 150 pixels. ...
The box model - Learn web development
previous overview: building blocks next everything in css has a box around it, and understanding these boxes is key to being able to create layouts with css, or to align items with other items. in this lesson, we will take a proper look at the css box model so that you can build more complex layout tasks with an understanding of how it works and the terminology that relates to it. prerequisites: basic computer literacy, basic software installed, basic knowledge of working with files, html basics (study introduction to html), and an idea of how css works (study css first steps.) objective: to learn about the css box model, what makes up the box model and how to switch to the alternate model. block and inline boxes in css we broadly have two typ...
...rgin. the alternative css box model you might think it is rather inconvenient to have to add up the border and padding to get the real size of the box, and you would be right! for this reason, css had an alternative box model introduced some time after the standard box model. using this model, any width is the width of the visible box on the page, therefore the content area width is that width minus the width for the padding and border. the same css as used above would give the below result (width = 350px, height = 150px). by default, browsers use the standard box model. if you want to turn on the alternative model for an element you do so by setting box-sizing: border-box on it. by doing this you are telling the browser to take the border box as the area defined by any size you set. .
CSS building blocks - Learn web development
to more specific disciplines like text styling and css layout. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites before starting this module, you should have: basic familiarity with using computers, and using the web passively (i.e. just looking at it, consuming the content.) a basic work environment set up as detailed in installing basic software, and an understanding of how to create and manage files, as detailed in dealing with files. basic familiarity with html, as discussed in the introduction to html module. an understanding of the basics of css, as discussed in the css first steps module. note: if you are working on a computer/tablet/anothe...
...rs pseudo-classes and pseudo-elements combinators the box model everything in css has a box around it, and understanding these boxes is key to being able to create layouts with css, or to align items with other items. in this lesson, we will take a proper look at the css box model, in order that you can move onto more complex layout tasks with an understanding of how it works and the terminology that relates to it. backgrounds and borders in this lesson we will take a look at some of the creative things you can do with css backgrounds and borders. from adding gradients, background images, and rounded corners, backgrounds and borders are the answer to a lot of styling questions in css. handling different text directions in recent years, css has evolved in order to better support ...
Floats - Learn web development
font: .9em/1.2 arial, helvetica, sans-serif } .wrapper { background-color: rgb(79,185,227); padding: 10px; color: #fff; overflow: auto; } .box { float: left; margin: 15px; width: 150px; height: 150px; border-radius: 5px; background-color: rgb(207,232,220); padding: 1em; } this example works by creating what is known as a block formatting context (bfc). this is like a mini layout inside your page, inside which everything is contained, therefore our floated element is contained inside the bfc and the background runs behind both items. this will usually work, however, in certain cases you might find unwanted scrollbars or clipped shadows due to unintended consequences of using overflow. display: flow-root the modern way of solving this problem is to use the value ...
...nd unwanted scrollbars or clipped shadows due to unintended consequences of using overflow. display: flow-root the modern way of solving this problem is to use the value flow-root of the display property. this exists only to create a bfc without using hacks — there will be no unintended consequences when you use it. remove overflow: auto from your .wrapper rule and add display: flow-root. assuming you have a supporting browser, the box will clear. .wrapper { background-color: rgb(79,185,227); padding: 10px; color: #fff; display: flow-root; } float example 7 <h1>simple float example</h1> <div class="wrapper"> <div class="box">float</div> <p>lorem ipsum dolor sit amet, consectetur adipiscing elit. nulla luctus aliquam dolor, eu lacinia lorem placerat vulputate. </p> </div>...
Positioning - Learn web development
tion: absolute; background: yellow; top: 30px; left: 30px; } the positioned element now sits relative to the <body> element. note: you can see the example at this point live at 4_positioning-context.html (see source code). introducing z-index all this absolute positioning is good fun, but there is another thing we haven't considered yet — when elements start to overlap, what determines which elements appear on top of which other elements? in the example we've seen so far, we only have one positioned element in the positioning context, and it appears on the top, since positioned elements win over non-positioned elements. what about when we have more than one? try adding the following to your css, to make the first paragraph absolutely positioned too: p:nth-of-type(1) { pos...
... note: you can see this example live at 7_sticky-positioning.html (see source code). test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: positioning. summary i'm sure yo...
Supporting older browsers - Learn web development
dea of how css works (study introduction to css and styling boxes.) objective: to understand how to provide support for your layouts on older browsers that might not support the features you want to use. what is the browser landscape for your site? every website is different in terms of target audience. 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. if you have no analytics or this is a brand new site, then there are sites such as statcounter that can provide statistics filtered by location. you should also consider the t...
...eature phone might not get much of your css, but the content will flow in a way that makes reading easy. therefore, a well-structured html document should always be your starting point. if you remove your stylesheet, does your content make sense? one option is to leave this plain view of the site as the fallback for people using very old or limited browsers. if you have a tiny number of people coming to the site in these browsers it may not make commercial sense to pour time into trying to give them a similar experience to people on modern browsers. it would be better to spend the time on things which make the site more accessible, thus serving far more users. there is a middle ground between a plain html page and all the bells and whistles, and css has actually made creating these fallbacks...
What is CSS? - Learn web development
hey are not linked to a member organization. new css features are developed, or specified, by the css working group. sometimes because a particular browser is interested in having some capability, other times because web designers and developers are asking for a feature, and sometimes because the working group itself has identified a requirement. ...
...many experienced developers would much rather refer to mdn documentation or other tutorials. ...
CSS FAQ - Learn web development
Learn › CSS › Howto › CSS FAQ
e declaration in common use before 2001 will be rendered in quirks mode. standards mode: the browser attempts to follow the w3c standards strictly. new html pages are expected to be designed for standards-compliant browsers, and as a result, pages with a modern doctype declaration will be rendered with standards mode. gecko-based browsers, have a third almost standards mode that has only a few minor quirks. this is a list of the most commonly used doctype declarations that will trigger standards or almost standards mode: <!doctype html> /* this is the html5 doctype. given that each modern browser uses an html5 parser, this is the recommended doctype */ <!doctype html public "-//w3c//dtd html 4.0 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> <!doctype html...
..."section"> nys: <span class="corpname"><span class="stockup">ge</span></span> +1.0 ... </div> in this example the body * selector applies the rule to all elements inside body, at any hierarchy level, including the .stockup class. so font-weight: bold; applied to the .corpname class is overridden by font-weight: normal; applied to all elements in the body. the use of the * selector should be minimized as it is a slow selector, especially when not used as the first element of a selector. its use should be avoided as much as possible. specificity in css when multiple rules apply to a certain element, the rule chosen depends on its style specificity. inline style (in html style attributes) has the highest specificity and will override any selectors, followed by id selectors, then class se...
Learn to style HTML using CSS - Learn web development
ls of html, we recommend that you learn html and css at the same time, moving back and forth between the two topics. this is because html is far more interesting and much more fun to learn when you apply css, and you can't really learn css without knowing html. 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). you should have a basic work environment set up as detailed in installing basic software and understand how to create and manage files, as detailed in dealing with files — both of which are parts of our getting started with the web complete beginner's module. it is recommended that you work through getting started with the web before proceeding with this topic. however, doing so...
...s; and add and define borders on elements. but there's not much you can't do once you have a solid understanding of even the basics of css. one of the best things about learning css is that once you know the fundamentals, usually you have a pretty good feel for what can and can't be done, even if you don't actually know how to do it yet! "css is weird" css works a bit differently to most programming languages and design tools you'll come across. why does it work the way it does? in the following video, miriam suzanne provides a useful explanation of why css works like it does, and why it has evolved like it has: ...
How do you make sure your website works properly? - Learn web development
ctrl+c sends an “interrupt” signal to the runtime and tells it to stop. if you don't stop the runtime, ping will ping the server indefinitely. a simple checklist check for 404s make sure all webpages are behaving as you expect check your website in several browsers to make sure it r...
...cmp_seq=0 ttl=44 time=148.741 ms 64 bytes from 63.245.215.20: icmp_seq=1 ttl=44 time=148.541 ms 64 bytes from 63.245.215.20: icmp_seq=2 ttl=44 time=148.734 ms 64 bytes from 63.245.215.20: icmp_seq=3 ttl=44 time=147.857 ms ^c --- mozilla.org ping statistics --- 4 packets transmitted, 4 packets received, 0.0% packet loss round-trip min/avg/max/stddev = 147.857/148.468/148.741/0.362 ms just keep in mind a handy keyboard shortcut: ctrl+c. ctrl+c sends an “interrupt” signal to the runtime and tells it to stop. if you don't stop the runtime, ping will ping the server indefinitely. a simple checklist check for 404s make sure all webpages are behaving as you expect check your website in several browsers to make sure it renders consistently next steps congratulations, your website is u...
How do I use GitHub Pages? - Learn web development
the same work, if you feel uncomfortable with the command line. every operating system comes with a command line tool: windows: command prompt can be accessed by pressing the windows key, typing command prompt, and choosing it from the list that appears. note that windows has its own command conventions differing from linux and os x, so the commands below may vary on your machine. os x: terminal can be found in applications > utilities. linux: usually you can pull up a terminal with ctrl + alt + t. if that doesn't work, look for terminal in an app bar or menu. this may seem a bit scary at first, but don't worry — you'll soon get the hang of the basics. you tell the computer to do something in the terminal by typing in a command and hitting enter, as seen above. creating a repo fo...
...t remote add origin https://github.com/chrisdavidmills/my-repository.git next, type the following two commands, pressing enter after each one. these prepare the code for uploading to github, and ask git to manage these files. git add --all git commit -m 'adding my files to my repository' finally, push the code up to github by going to the github web page you're on and entering into the terminal the second of the two commands we saw the …or push an existing repository from the command line section: git push -u origin master now you need to turn github pages on for your repository. to do this, from the homepage of your repository choose settings, then scroll down until you get to the github pages section. underneath source, choose master branch. the page should refresh. go to t...
CSS basics - Learn web development
etting started with the web next css (cascading style sheets) is the code that styles web content. css basics walks through what you need to get started. we'll answer questions like: how do i make text red? how do i make content display at a certain location in the (webpage) layout? how do i decorate my webpage with background images and colors? what is css? like html, css is not a programming language. it's not a markup language either. css is a style sheet language. css is what you use to selectively style html elements. for example, this css selects paragraph text, setting the color to red: p { color: red; } let's try it out! using a text editor, paste the three lines of css (above) into a new file. save the file as style.css in a directory named styles. to make the code work,...
... positioning and styling the main page title h1 { margin: 0; padding: 20px 0; color: #00539f; text-shadow: 3px 3px 1px black; } you may have noticed there's a horrible gap at the top of the body. that happens because browsers apply default styling to the <h1> element (among others). that might seem like a bad idea, but the intent is to provide basic readability for unstyled pages. to eliminate the gap, we overwrite the browser's default styling with the setting margin: 0;. next, we set the heading's top and bottom padding to 20 pixels. following that, we set the heading text to be the same color as the html background color. finally, text-shadow applies a shadow to the text content of the element. its four values are: the first pixel value sets the horizontal offset of the sha...
HTML basics - Learn web development
started with the web next html (hypertext markup language) is the code that is used to structure a web page and its content. for example, content could be structured within a set of paragraphs, a list of bulleted points, or using images and data tables. as the title suggests, this article will give you a basic understanding of html and its functions. so what is html? html is not a programming language; it is a markup language that defines the structure of your content. html consists of a series of elements, which you use to enclose, or wrap, different parts of the content to make it appear a certain way, or act a certain way. the enclosing tags can make a word or image hyperlink to somewhere else, can italicize words, can make the font bigger or smaller, and so on. for example, take...
...eload the page, you should see something like this in place of the image: the keywords for alt text are "descriptive text". the alt text you write should provide the reader with enough information to have a good idea of what the image conveys. in this example, our current text of "my test image" is no good at all. a much better alternative for our firefox logo would be "the firefox logo: a flaming fox surrounding the earth." try coming up with some better alt text for your image now. find out more about accessibility in our accessibility learning module. marking up text this section will cover some of the essential html elements you'll use for marking up the text. headings heading elements allow you to specify that certain parts of your content are headings — or subheadings. in ...
Publishing your website - Learn web development
lp from colleagues in a different office), and free (for basic features). they host your rendered page at a unique web address. however, the features are limited, and these apps usually don't provide hosting space for assets (like images). try playing with some of these examples to find out which one works best for you: jsfiddle glitch js bin codepen publishing via github now let's examine how to easily publish your site via github pages. first of all, sign up for github and verify your email address. next, you need to create a repository to store files. on this page, in the repository name box, enter username.github.io, where username is your username. for example, our friend bob smith would enter bobsmith.github.io. check the "initialize this repository with a readme" box...
...ith a readme" box. then click create repository. drag and drop the content of your website folder into your repository. then click commit changes. note: make sure your folder has an index.html file. navigate your browser to username.github.io to see your website online. for example, for the username chrisdavidmills, go to chrisdavidmills.github.io. note: it may take a few minutes for your website to go live. if your website does not display immediately, wait a few minutes. try again. to learn more, see github pages help. further reading what is a web server understanding domain names how much does it cost to do something on the web? deploy a website: a nice tutorial from codecademy that goes a bit further and shows some additional techniques. cheap or f...
The web and web standards - Learn web development
d to apply styles to your html, for example setting text and background colors, adding borders, animating things, or laying out a page in a certain way. as a simple example, the following code would turn our html paragraph red: p { color: red; } in the house analogy, css is like the paint, wallpaper, carpets and paintings you'd use to make the house look nice. javascript is the programming language we use to add interactivity to web sites, from dynamic style switching, to fetching updates from the server, right through to complex 3d graphics. the following simple javascript will store a reference to our paragraph in memory and change the text inside it: let pelem = document.queryselector('p'); pelem.textcontent = 'we changed the text!'; in the house analogy, javascript is lik...
...o debug your code. testing tools that can be used to run tests to show whether your code is behaving as you intended it to. libraries and frameworks built on top of javascript that allow you to build certain types of web site much more quickly and effectively. so-called "linters", which take a set of rules, look at your code, and highlight places where you haven't followed the rules properly. minifiers, which remove all the whitespace from your code files to make it so that they are smaller and therefore download from the server more quickly. server-side languages and frameworks html, css, and javascript are front-end (or client-side) languages, which means they are run by the browser to produce a website front-end that your users can use. there are another class of languages called ...
Add a hitmap on top of an image - Learn web development
p, properly step 1: the image not just any image is acceptable. the image must make it clear what happens when people follow image links. alt text is mandatory, of course, but many people never see it. the image must clearly indicate where hotspots begin and end. hotspots must be large enough to tap comfortably, at any viewport size. how large is large enough? 72 × 72 css pixels is a good minimum, with additional generous gaps between touch targets. the map of the world at 50languages.com (as of time of writing) illustrates the problem perfectly. it’s much easier to tap russia or north america than albania or estonia. you insert your image much the same way as always (with an <img> element and alt text). if the image is only present as a navigation device, you may write alt="", pr...
...ed <area> elements. an <area> element corresponds to a single hotspot. to keep keyboard navigation intuitive, make sure the source order of <area> elements corresponds to the visual order of hotspots. <area> elements are empty elements, but do require four attributes: shape coords shape takes one of four values: circle, rect, poly, and default. (a default <area> occupies the entire image, minus any other hotspots you’ve defined.) the shape you choose determines the coordinate information you’ll need to provide in coords. for a circle, provide the center's x and y coordinates, followed by the length of the radius. for a rectangle, provide the x/y coordinates of the upper-left and bottom-right corners. for a polygon, to provide the x/y coordinates of each corner (so, at lea...
Creating hyperlinks - Learn web development
o" in the link text — it's just noise. screen readers tell people there's a link. visual users will also know there's a link, because links are generally styled in a different color and underlined (this convention generally shouldn't be broken, as users are used to it). keep your link label as short as possible — this is helpful because screen readers need to interpret the entire link text. minimize instances where multiple copies of the same text are linked to different places. this can cause problems for screen reader users, if there's a list of links out of context that are labeled "click here", "click here", "click here". use relative links wherever possible from the description above, you might think that it's a good idea to just use absolute links all the time because they don'...
...e that includes the names of the pages to link to. a navigation menu is usually just a list of links, so this is semantically ok. change each page name into a link to that page. copy the navigation menu across to each page. on each page, remove just the link to that same page — it's confusing and unnecessary for a page to include a link to itself. and, the lack of a link acts a good visual reminder of which page you are currently on. the finished example should look similar to the following page: note: if you get stuck, or aren't sure if you have got it right, you can check the navigation-menu-marked-up directory to see the correct answer. e-mail links it's possible to create links or buttons that, when clicked, open a new outgoing email message rather than linking to a resource...
HTML table advanced features and accessibility - Learn web development
ml code in your browser developer tools — you will see that the browser has added this tag for you. you might wonder why you ought to bother including it at all — you should, because it gives you more control over your table structure and styling. active learning: adding table structure let's put these new elements into action. first of all, make a local copy of spending-record.html and minimal-table.css in a new folder. try opening it in a browser — you'll see that it looks ok, but it could stand to be improved. the "sum" row that contains a summation of the spent amounts seems to be in the wrong place, and there are some details missing from the code. put the obvious headers row inside a <thead> element, the "sum" row inside a <tfoot> element, and the rest of the content insid...
...s="cost haircut">30</td> </tr> ... </tbody> note: this method creates very precise associations between headers and data cells but it uses a lot more markup and does not leave any room for errors. the scope approach is usually enough for most tables. active learning: playing with scope and headers for this final exercise, we'd like you to first make local copies of items-sold.html and minimal-table.css, in a new directory. now try adding in the appropriate scope attributes to make this table more appropriate. finally, try making another copy of the starter files, and this time make the table more accessible using id and headers attributes. note: you can check your work against our finished examples — see items-sold-scope.html (also see this live) and items-sold-headers.html...
Build your own function - Learn web development
the color, icon, or anything else. we'll build one that will prove to be more fun. note: this example should work in all modern browsers fine, but the styling might look a bit funny in slightly older browsers. we'd recommend you doing this exercise in a modern browser like firefox, opera, or chrome. the basic function to begin with, let's put together a basic function. note: for function naming conventions, you should follow the same rules as variable naming conventions. this is fine, as you can tell them apart — function names appear with parentheses after them, and variables don't. start by accessing the function-start.html file and making a local copy. you'll see that the html is simple — the body contains just a single button. we've also provided some basic css to style the...
... note: if you have trouble getting the example to work, feel free to check your code against the finished version on github (see it running live also), or ask us for help. test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see te...
Functions — reusable blocks of code - Learn web development
ul things without having to write all that code yourself. in fact, some of the code you are calling when you invoke (a fancy word for run, or execute) a built in browser function couldn't be written in javascript — many of these functions are calling parts of the background browser code, which is written largely in low-level system languages like c++, not web languages like javascript. bear in mind that some built-in browser functions are not part of the core javascript language — some are defined as part of browser apis, which build on top of the default language to provide even more functionality (refer to this early section of our course for more descriptions). we'll look at using browser apis in more detail in a later module. functions versus methods programmers call functions that...
..... }) and conditional blocks (e.g. if() { ... }) — they look very similar, but they are not the same thing! take care not to get these confused. note: the referenceerror: "x" is not defined error is one of the most common you'll encounter. if you get this error and you are sure that you have defined the variable in question, check what scope it is in. functions inside functions keep in mind that you can call a function from anywhere, even inside another function. this is often used as a way to keep code tidy — if you have a big complex function, it is easier to understand if you break it down into several sub-functions: function mybigfunction() { let myvalue; subfunction1(); subfunction2(); subfunction3(); } function subfunction1() { console.log(myvalue); } functio...
JavaScript object basics - Learn web development
ascript features that we've already seen earlier in the course, reiterating the fact that many of the features you've already dealt with are objects. prerequisites: basic computer literacy, a basic understanding of html and css, familiarity with javascript basics (see first steps and building blocks). objective: to understand the basic theory behind object-oriented programming, how this relates to javascript ("most things are objects"), and how to start working with javascript objects. object basics an object is a collection of related data and/or functionality (which usually consists of several variables and functions — which are called properties and methods when they are inside objects.) let's work through an example to understand what they look like. to...
...ep track of all the properties and methods in our person object as separate variables and functions, it would be inefficient and frustrating, and we'd run the risk of clashing with other variables and functions that have the same names. objects let us keep the information safely locked away in their own package, out of harm's way. in the next article we'll start to look at object-oriented programming (oop) theory, and how such techniques can be used in javascript. overview: objects next in this module object basics object-oriented javascript for beginners object prototypes inheritance in javascript working with json data object building practice adding features to our bouncing balls demo ...
Working with JSON - Learn web development
n to objects). objective: to understand how to work with data stored in json, and create your own json objects. no, really, what is json? json is a text-based data format following javascript object syntax, which was popularized by douglas crockford. even though it closely resembles javascript object literal syntax, it can be used independently from javascript, and many programming environments feature the ability to read (parse) and generate json. json exists as a string — useful when you want to transmit data across a network. it needs to be converted to a native javascript object when you want to access the data. this is not a big issue — javascript provides a global json object that has methods available for converting between the two. note: converting a string...
...here we first create an <h1> element with createelement(), set its textcontent to equal the squadname property of the object, then append it to the header using appendchild(). we then do a very similar operation with a paragraph: create it, set its text content and append it to the header. the only difference is that its text is set to ...
Object building practice - Learn web development
and canvas.height properties) to equal the width and height of the browser viewport (the area that the webpage appears on — this can be gotten from the window.innerwidth and window.innerheight properties). note that we are chaining multiple assignments together, to get the variables all set quicker — this is perfectly ok. the last bit of the initial script looks as follows: function random(min, max) { const num = math.floor(math.random() * (max - min + 1)) + min; return num; } this function takes two numbers as arguments, and returns a random number in the range between the two. modeling a ball in our program our program will feature lots of balls bouncing around the screen. since these balls will all behave in the same way, it makes sense to represent them with an object. let's...
...g: sets the canvas fill color to semi-transparent black, then draws a rectangle of the color across the whole width and height of the canvas, using fillrect() (the four parameters provide a start coordinate, and a width and height for the rectangle drawn). this serves to cover up the previous frame's drawing before the next one is drawn. if you don't do this, you'll just see long snakes worming their way around the canvas instead of balls moving! the color of the fill is set to semi-transparent, rgba(0,0,0,0.25), to allow the previous few frames to shine through slightly, producing the little trails behind the balls as they move. if you changed 0.25 to 1, you won't see them at all any more. try varying this number to see the effect it has. loops through all the balls in the balls ar...
JavaScript — Dynamic client-side scripting - Learn web development
every time a web page does more than just sit there and display static information for you to look at—displaying timely content updates, interactive maps, animated 2d/3d graphics, scrolling video jukeboxes, or more—you can bet that javascript is probably involved. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites javascript is arguably more difficult to learn than related technologies such as html and css. ...
...uably more difficult to learn than related technologies such as html and css. before attempting to learn javascript, you are strongly advised to get familiar with at least these two technologies first, and perhaps others as well. start by working through the following modules: getting started with the web introduction to html introduction to css having previous experience with other programming languages might also help. after getting familiar with the basics of javascript, you should be in a position to learn about more advanced topics, for example: javascript in depth, as taught in our javascript guide web apis modules this topic contains the following modules, in a suggested order for working through them. javascript first steps in our first javascript module, we first a...
What is web performance? - Learn web development
loading is called time to interactive. smoothness and interactivity: does the application feel reliable and pleasurable to use? is the scrolling smooth? are buttons clickable? are pop-ups quick to open up, and do they animate smoothly as they do so? 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. perceived performance: how fast a website seems to the user has a greater impact on user experience than how fast the website actually is. how a user perceives your performance is as important, or perhaps more important, than any objective statistic, but it's subjective, and not as readily measurable. perceived performance ...
... optimized. this involves a number of metrics (measurable indicators that can indicate success or failure) and tools to meaure those metrics, which we will discuss throughout this module. to summarize, many features impact performance including latency, application size, the number of dom nodes, the number of resource requests made, javascript performance, cpu load, and more. it is important to minimize the loading and response times, and add additional features to conceal latency by making the experience as available and interactive as possible, as soon as possible, while asynchronously loading in the longer tail parts of the experience. note: web performance includes both objective measurements like time to load, frames per second, and time to interactive, and subjective experiences of ...
JavaScript performance - Learn web development
rformance optimization, and how a javascript file size is not the only impact on web performance. similar to images and video, the best way to improve performance is to omit what is not, in fact, necessary. but not all bytes downloaded have the same impact. javascript bytes have to be downloaded, parsed, and exectuted. javascript impacts download performance. we'll cover tips and tricks to minimize that impact on download. but javascript can also consume the main thread, the cpu, and the battery. it can make the ui feel unresponsive or janky. we'll introduce concepts for handling that as well. download impact web applications include a lot of javascript. many applications are built with a javascrpit framework, or multiple, with several additional dependencies. often times third party...
...equired? is there a lighter weight or home spun solutions? some features may not be necessary, and though they may add some bling, is the cost of the feature in terms of performance worth it? remove unused code split the javascript into smaller files code-split javascript into critical and non-critical parts. module bundlers like webpack support code-splitting. optimize these smaller files minification reduces the number of characters in your file, thereby reducing the number of bytes or weight of your javascript. gzipping compresses the file further, and should be used even if you don't minify. brotli is similar to gzip, generally outperforming gzip's compression. render impact web applications include a lot of javascript. many applications are built with a javascrpit framew...
Web performance - Learn web development
bsite is in milliseconds, is how fast your users perceive your site to be. these perceptions are impacted by actual page load time, idling, responsiveness to user interaction, and the smoothness of scrolling and other animations. in this article, we discuss the various loading metrics, animation, and responsiveness metrics, along with best practices to improve user perception, if not the actual timings. measuring performance now that you understand a few performance metrics, we take a deeper dive into performance tools, metrics, and apis and how we can make performance part of the web development workflow. multimedia: images the lowest hanging fruit of web performance is often media optimization. serving different media files based on each user agent's capability, size, and pixel densi...
...web experiences — or it can significantly harm download time, render time, in-app performance, battery life, and user experience. this article outlines some javascript best practices that should be considered to ensure even complex content is as performant as possible. html performance features some attributes and the source order of your mark-up can impact the performance or your website. by minimizing the number of dom nodes, making sure the best order and attributes are used for including content such as styles, scripts, media, and third-party scripts, you can drastically improve the user experience. this article looks in detail at how html can be used to ensure maximum performance. css performance features css may be a less important optimization focus for improved performance, but ...
Accessibility in React - Learn web development
previous overview: client-side javascript frameworks next in our final tutorial article, we'll focus on (pun intended) accessibility, including focus management in react, which can improve usability and reduce confusion for both keyboard-only and screenreader users. prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. objective: to learn about implementing keyboard accessibility in react. including keyboard users at this point, we've accomplished all of the features we set out to implement. a user can add a new task, check and uncheck tasks, delete tasks, or edit task names. and they can filter their task list by all, active, or completed tasks. or, at least: they can do all o...
...s first in the code. main render (3) todo.js:100 side effect (3) todo.js:98 that's it for our experimentation for now. delete console.log("main render") now, and lets move on to implementing our focus management. focusing on our editing field now that we know our useeffect() hook works, we can manage focus with it. as a reminder, we want to focus on the editing field when we switch to the editing template. update your existing useeffect() hook so that it reads like this: useeffect(() => { if (isediting) { editfieldref.current.focus(); } }, [isediting]); these changes make it so that, if isediting is true, react reads the current value of the editfieldref and moves browser focus to it. we also pass an array ...
Focus management with Vue refs - Learn web development
rove our app's keyboard accessibility. we'll look at using vue refs to handle this — an advanced feature that allows you to have direct access to the underlying dom nodes below the virtual dom, or direct access from one component to the internal dom structure of a child component. prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. vue components are written as a combination of javascript objects that manage the app's data and an html-based template syntax that maps to the underlying dom structure. for installation, and to use some of the more advanced features of vue (like single file components or render functions), you'll need a terminal with node + npm installed. objective: to learn ...
...er assistive technology. now that we have a ref and have let browsers know that we can programmatically focus the <h2>, we need to set focus on it. at the end of deletetodo(), use the listsummary ref to set focus on the <h2>. since the <h2> is always rendered in the app, you do not need to worry about using $nexttick of lifecycle methods to handle focusing it. deletetodo(todoid) { const itemindex = this.todoitems.findindex(item => item.id === todoid); this.todoitems.splice(itemindex, 1); this.$refs.listsummary.focus(); } now, when you delete an item from your list, focus should be moved up to the list heading. this should provide a reasonable focus experience for all of our users. summary so that's it for focus management, and for our app! congratulations for working your w...
Vue resources - Learn web development
previous overview: client-side javascript frameworks next now we'll round off our study of vue by giving you a list of resources that you can use to go further in your learning, plus some other useful tips. prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. vue components are written as a combination of javascript objects that manage the app's data and an html-based template syntax that maps to the underlying dom structure. for installation, and to use some of the more advanced features of vue (like single file components or render functions), you'll need a terminal with node + npm installed. objective: to learn where to go to find further information on vue, to continue your le...
... vue mastery — a paid education platform that specializes in vue, including some free lessons. vue school — another paid education platform specializing in vue. building and publishing your vue app the vue cli also provides us with tools for preparing our app for publishing to the web. you can do this like so: if your local server is still running, end it by pressing ctrl + c in the terminal. next, run the npm run build (or yarn build) in the console. this will create a new dist directory containing all of your production ready files. to publish your site to the web, copy the contents of this folder to your hosting environment. note: the vue cli docs also include a specific guide on how to publish your app to many of the common hosting platforms. vue 3 vue 3 is a major rele...
Understanding client-side JavaScript frameworks - Learn web development
quire framework experience. 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. in this set of articles, we are aiming to give you a comfortable starting point to help you begin learning frameworks. we are not aiming to exhaustively teach you everything you need to know about react/reactdom, or vue, or some other specific framework; the framework teams' own docs (and other resources) do that job already. instead, we want to back up and first answer more fundamental questions such as: why should i use a framew...
... ...
Tools and testing - Learn web development
once you've started to become comfortable programming with core web technologies (like html, css, and javascript), and you start to get more experience, read more resources, and learn more tips and tricks, you'll start to come across all kind of tools, from javascript frameworks, to testing and automation tools, and more besides. as your web projects become larger and more complex, you'll want to start taking advantage of some of these tools, working out a reliable toolchain to give your development process superpowers. ...
...l start to come across all kind of tools, from javascript frameworks, to testing and automation tools, and more besides. as your web projects become larger and more complex, you'll want to start taking advantage of some of these tools, working out a reliable toolchain to give your development process superpowers. 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,...
Chrome Worker Modules
loading modules loading a module is simple. start by importing the module loader. you only need to do it once for each worker, from within the chrome worker itself: importscripts("resource://gre/modules/workers/require.js"); note: although you only need to do this once for each worker, it doesn't hurt if you do it more than once. ...
...s a secret"; let publickey = "this is public"; exports.key = publickey; // secretkey is not exported // publickey is exported with name "key" alternatively, if you prefer that style, you may write // variable |module| is a special global introduced by require() module.exports = { key: publickey }; once this is done, we may load the module and use the values that have been exported // assuming that mymodule.js is installed to resource://gre/modules/mymodule.js let module = require("resource://gre/modules/mymodule.js") foo(module.key); // module.key == "this is public"; // however, secretkey is not exported and cannot be used for the installation of resources, please see the documentation on moz.build (if your code is part of the platform) or on chrome manifests (if your code is part...
omni.ja (formerly omni.jar)
s reduces the amount of i/o needed to load the application. this article covers the contents of the archive and techniques for inspecting those contents. note: starting with firefox 10 and thunderbird 10, the file extension .ja is used because windows system restore does not back up files with the .jar extension, but it does back up .ja files. ...
...users of older versions of windows can use infozip's unzip tool to extract files - make a copy of omni.ja, and drag-and-drop it onto unzip.exe. linux users can simply use unzip command to inflate files of omni.ja. ...
Accessibility information for UI designers and developers
this page describes a number of design-related aspects to look out for, in no particular order. color enough contrast ensure there is enough contrast between foreground and background colors. your content can then be better consumed by users with low vision and people with color deficiencies. the ratio should be 4.5:1 for regular text and 3:1 for large text. calculating this ratio is easiest done with a tool, for example lea verou's contrast ratio. there are also plug-ins available for design software, like stark for sketch. ...
.... pages with a parallax effect can particularly cause troubles. to help these users, you could offer a setting to turn off animations, or wrap the css in the prefers-reduce-motion media query. see also: understanding success criterion 2.3.3: animation from interactions content on hover or focus if content is revealed on hover or focus, for example in tooltips, there are some things to keep in mind: if the extra content obscures existing content, there should be a way to close it without moving focus if the extra content is opened on hover, hovering the additional content itself should not cause it to disappear consistent navigation navigation should be consistent across different pages on your site. it does not need to be exactly the same, it is fine to have a different current me...
CSUN Firefox Materials
is simply more pleasant. as a result, nearly everyone who tries firefox finds themselves hooked.. assistive technology support on windows "i am a full firefox convert with the release of 1.5. at my next opportunity, i intend to convert my family over to it too. " -- darren paskell, from window-eyes beta testing list firefox works with popular screen readers, with the best support currently coming from gw micro's window-eyes 5.5. jaws support is quickly catching up as well. in recent articles from both afb's access world and nfb's voice of the nation's blind, reviewers found no significant roadblocks in moving to firefox from internet explorer for screen reader users. in fact, the same keyboard commands are still available, so users can become comfortable and productive right away. screen...
...e search field on the desired website. integrated web search via ctrl+k is much faster to use than first going to the search tool's web site. custom searches can be added to this quick search bar and the user can switch between them by choosing from a drop down available via the standard alt+down arrow key combination. the built-in text zoom feature can be accessed with the ctrl+plus and ctrl+minus hotkeys. the accessibility extension may be installed on top of firefox, allowing keyboard access to document structure. caret browsing allows you to move through web content one letter a time. you can even select web content and copy it to the clipboard. -- all with the keyboard moving back and forward by web page (alt+left and alt+right) occurs near-instantaneously the download manage...
Accessible Toolkit Checklist
uidelines for each platform. the approaches there are two basic kinds of toolkits, which each provide different challenges when implementing accessibility: native widget toolkits , like eclipse and wxwidgets, already have some accessibility built-in. these toolkits wrap the widgets implemented by the os with a consistent api for each platform. since the individual widgets predominately come from the operating system, they already implement standard keyboard commands and follow the operating system's visual theme. also, assistive technologies already understand native widgets so it is only necessary to implement microsoft active accessibility (msaa) api support for custom controls. however, be aware that the wrapping layer will introduce accessibility bugs, and thus you wil...
...mation about linux and os x. it is maintained by the mozilla accessibility community. contributions are welcome. general dialogs/windows/general escape key cancels dialogs and refocuses the previously focused on the parent window. alt+f4 closes windows, similar to escape but even works on dialogs without cancel button alt+space opens window menu with restore, move, size, minimize, maximize, close the move and size options must be usable with the arrow keys on the keyboard in windows, initial focus goes to first focusable widget that is not a clickable tabbed property sheet label making tab order definable. default tab order should be in document order. tab order must wrap, not have invisible items in tab order dynamically added items mus...
Accessibility and Mozilla
rence helps us see the difference between today's accessibility api's. all accessibility apis to date define a list of possible object roles, or general types, such as button, menu item, text, etc. they also define a list of possible object states, such as focused, read-only, checked, etc.accessibility features in firefoxfirefox works with popular screen readers, with the best support currently coming from gw micro's window-eyes 5.5. we are optimistic that jaws support will catch up this year. in recent articles from both afb's access world and nfb's voice of the nation's blind, reviewers found no significant roadblocks in moving to firefox from internet explorer for screen reader users. in fact, the same keyboard commands are still available, so users can become comfortable and productive r...
...ght away.accessibility information for core gecko developersboth end users and developers are invited for discussion on the live irc channel at irc.mozilla.org/#accessibility. since this is a worldwide effort, there is always a good chance to find someone to chat with there, day or night.accessibility information for ui designers and developerswhen you design user interfaces with accessibility in mind, they will work for more people. this page describes a number of design-related aspects to look out for, in no particular order.accessibility/liveregiondevguidethis page is currently under construction. this developer's guide lays out general guidelines that assistive technology (at) developers can use in developing live region support. this guide was written from an atk/at-spi point of view as...
Lightweight themes
p® express, a free online photo editor. submitting your theme image to get started submitting your images, go to the theme submission page: name your theme — pick a unique name for your theme. duplicate names are not allowed, so you may need to try a few times to find a unique name. pick a category and tags — select a category and enter some tags that best describe your theme. keep in mind that a reviewer may reject your theme if it is obvious that your category and/or tags are unrelated to your theme. describe your theme — write a short description of your theme. keep in mind that a reviewer may reject your theme if your description is not an accurate representation of your theme. select a license for your theme — decide on a copyright license for your work. read more about...
...file page. tip: to ensure that your theme is approved for the gallery, be sure it complies with the content guidelines and terms of service! submit your theme now frequently asked questions for more information about lightweight themes, including content guidelines, please see these frequently asked questions. more tutorials mozilla themes focal point on sizing - a tutorial on theming with a focus on sizing, by vanillaorchids. ...
Theme concepts
ckground_text": "#000" } } } where: "frame": is the heading area background color for your theme. "tab_background_text": the color of the text in the heading area. package your theme and submit it to amo, following these instructions. themes can be submitted to amo for hosting or for self-distribution. static theme approaches there are two approaches you can take to theming the header area of firefox: using a single image or using multiple images. you could combine the two, but it’s easier to treat them separately. single image themes this is the basic or minimal theming option, where you define: a single image, which is anchored to the top right of the header area. a color for the text in the header. the area your header image needs to fill is a maximum ...
...practically, this means you would need to allow for a width of up to 5120 pixels wide (for the next generation of 5k monitors). ...
Adding a new CSS property
d the syntax line in the property's specification (whose syntax is in turn defined in the css values and units specification) and any prose in the specification that adds additional restrictions to that syntax. every property in nscssproplist.h must have in its flags field exactly one of the four css_property_parse_* flags defined in nscssprops.h. given the syntax for the property, you can determine which one to use. if the property's values can be expressed as a single value, or as a space-separated or comma-separated list of values that can be described by the variant_* flags (also in nscssprops.h), you should use css_property_parse_value or css_property_parse_value_list, and set the appropriate variant_* flags in the entry in nscssproplist.h (and maybe also css_property_value_list_uses_...
...ion. you must take the latter approach for properties that are part of shorthands if you want the shorthand parser to be able to reuse the longhand parser. (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. the name of this keyword table needs to go in the nscssproplist entry; otherwise that keyword table should be null. if you need a keyword table, you should ...
Browser chrome tests
est() { ok(gbrowser, "gbrowser exists"); is(gbrowser.tabs.length, 1, "browser has 1 tab"); } the test() function is invoked by the test harness when the test is run. the test file can contain other functions, they will be ignored unless invoked by test(). gbrowser is set in browser.js and is a tabbrowser element (the tabbrowser with id="content" in browser.xul). note: be careful when naming your functions and variables. since the test files are executed in the same scope as the browser window, conflicting variable names could cause trouble while running the tests. you should attempt to reduce the side effects of the testing code and "clean up" after yourself, to avoid influencing other tests. the comparison functions are identical to those supported by mochitests, see how the comp...
...ting a result until after test() has returned. call finish() once the test is complete. be aware that the test harness will mark tests that take too long to complete as failed (the current timeout is 30 seconds). function test() { waitforexplicitfinish(); settimeout(completetest, 1000); } function completetest() { ok(true, "timeout ran"); finish(); } if your test is randomly timing out and you think that's just due to it taking too long, you can extend the timeout. be aware that this is not a solution; you should investigate why your test is taking so long, since it's most likely due to a bad test design or a performance problem. if you can rewrite the test to make is shorter, split it into smaller tests, or find why it's taking so long, you should really do that instead! ...
Testopia
testopia 3.0 (not yet released) if you upgraded to bugzilla 5.0, you probably noticed that testopia 2.5 is not compatible with this version. ...
...ng moved into extensions/testopia/lib/. this is not an trivial task, it takes time (it started in august 2014), and we decided that it was not a good idea to release half-baked code which still needs testing to make sure we didn't regress anything. the good news is that the current code in the git repository already works with bugzilla 5.0, and so if you upgraded to 5.0 already, and if you don't mind having a work-in-progress extension on your machine, you can decide to pull the code from the git repository. this would also let us get some early feedback in case you find regressions. if you find bugs in the code available from the git repository, please report it to us so that we can fix most critical ones on time for testopia 3.0. do not ask when we plan to release 3.0, because we really d...
Debugging on Mac OS X
for specific information on a way to debug hangs, see debugging a hang on os x. 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. compiled in). see building firefox for macos if you need help creating your own build. ...
...le.quarantine /path/to/nightly.app local builds local builds of mozilla-central do not enable hardened runtime and hence do not have debugging restrictions. as a result, some functionality will be permitted on local builds, but blocked on production builds which have hardened runtime enabled. bug 1522409 was filed to automate codesigning local builds to enable hardened runtime by default and eliminate this discrepancy. 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. this requires creating a codesigning identity. disabling system integrity protection (sip) if debugging a production build is required, follow apple's documented steps for d...
Old Thunderbird build
anifest as problems setting up the virtualenv for running tests (failure to install pip or virtualenv because of os access denied errors, where access is denied not because of permission problems, but because the paths being accessed have been truncated, and so do not exist). having the source deep in a filesystem hierarchy can also cause problems with pymake builds on windows. if you run into seemingly arbitrary problems in building and the source is deeply nested, try moving it close to the root of your machine and re-building. get the latest source code from mozilla's comm-central mercurial code repository: hg clone https://hg.mozilla.org/comm-central then, get all the repositories it depends on. the comm-central repository includes a script to do just that. this may take a while, it's...
...n https://treeherder.mozilla.org/#/jobs?repo=comm-central to start the build, cd into the comm-central subdirectory, and run: ./mozilla/mach build mach is our command-line tool to streamline common developer tasks. see the mach article for more. building can take a significant amount of time, depending on your system, os, and chosen build options. linux builds on a fast box may take under 15 minutes, but windows builds on a slow box may take several hours. tips for making builds faster. the executable will be at the location listed under running below. building thunderbird and lightning if you've set up your build environment as above, then all you need to do is: echo 'ac_add_options --enable-calendar' >> mozconfig in the comm-central directory, or just add the ac_add_options --ena...
Simple Instantbird build
anifest as problems setting up the virtualenv for running tests (failure to install pip or virtualenv because of os access denied errors, where access is denied not because of permission problems, but because the paths being accessed have been truncated, and so do not exist). having the source deep in a filesystem hierarchy can also cause problems with pymake builds on windows. if you run into seemingly arbitrary problems in building and the source is deeply nested, try moving it close to the root of your machine and re-building. get the latest source code from mozilla's comm-central mercurial code repository: hg clone http://hg.mozilla.org/comm-central then, get all the repositories it depends on. the comm-central repository includes a script to do just that. this may take a while, it's ...
...ozconfig to start the build, cd into the comm-central subdirectory (created automatically by the hg clone command), and run: ./mozilla/mach build mach is our command-line tool to streamline common developer tasks. see the mach article for more. building can take a significant amount of time, depending on your system, os, and chosen build options. linux builds on a fast box may take under 15 minutes, but windows builds on a slow box may take several hours. building purplexpcom and libpurple first download the purplexpcom code: hg clone http://hg.mozilla.org/users/florian_queze.net/purple mozilla/extensions/purple if you've set up your build environment as above, then all you need to do is: echo 'ac_add_options --enable-extensions=purple' >> .mozconfig in the comm-central directory...
Updating NSPR or NSS in mozilla-central
that need to be applied to nspr, and directory mozilla/security/patches/ for patches that need to be applied to nss. apply the patches. if merging is required, update the patch file. if a patch is no longer needed, remove the patch from the directory and update the readme file. check for new or removed files $ hg addremove -n review the output to make sure it looks correct update the minimum required system nss version in old-configure.in. this is for builds with --with-system-nss. for example, in the following, "3.16.1" would be replaced with the new nss version. moz_arg_with_bool(system-nss, [ --with-system-nss use system installed nss], _use_system_nss=1 ) if test -n "$_use_system_nss"; then am_path_nss(3.16.1, [moz_native_nss=1], [ac_msg_error([you don't ha...
...in the following, "3.16.1" would be replaced with the new nss version. moz_arg_with_bool(system-nss, [ --with-system-nss use system installed nss], _use_system_nss=1 ) if test -n "$_use_system_nss"; then am_path_nss(3.16.1, [moz_native_nss=1], [ac_msg_error([you don't have nss installed or your version is too old])]) fi commit the update: $ hg commit -a in order to eliminate any problems related to how nss and nspr are built differently in firefox than they are standalone, you should push your commit to try first. if your update fails linking because of missing nss or nspr symbols, add the missing symbols to config/external/nss/nspr-dummy.def or config/external/nss/nss.def, whichever is relevant. in your commit message, include the required keywords, upgrade_ns...
Callgraph
the callgraph project uses gcc and treehydra to generate information about function and method calls at compile time, and aggregates it into a sqlite database. ...
...the callgraph project uses gcc and treehydra to generate information about function and method calls at compile time, and aggregates it into a sqlite database. ...
Commenting IDL for better documentation
atic documentation generation tools can not see what is obvious to human brains. plus, what is obvious to you is likely not obvious to everyone. use doxygen style comments only for information that is directly useful to someone using or implementing the interface. this helps keep the documentation tidy. be concise and to the point. writers will expand upon your documentation if necessary. keep in mind that people for whom english is not their native language will be reading your comments (as well as the generated documentation), so try to avoid slang and abbreviations when possible. if possible, avoid putting comments in the middle of the definitions of apis. if an interface is used as a parameter or as the type of the value returned by a method, please use the full name of the interface in t...
...ookie. */ const integer cookie_flavor_sugar = 1; /** * chocolate chip cookie. */ const integer cookie_flavor_chocolate_chip = 2; /** * peanut butter cookie. */ const integer cookie_flavor_peanut_butter = 3; /** * chocolate cookie with chocolate chips. */ const integer cookie_flavor_double_chocolate = 4; /** * an unknown type of cookie. */ const integer cookie_flavor_other = 0; // yumminess constants /** * the cookie is disgusting. */ const integer cookie_not_yummy = 1; /** * the cookie is good but not awesome. */ const integer cookie_sort_of_yummy = 2; /** * the cookie is really, really yummy. */ const integer cookie_extremely_yummy = 3; /** * omg this is the best cookie evar!1!!1. */ const integer cookie_omg_yummy = 4; /** * the cookie monster's name. */ readonly...
Runtime Directories
default application installation and user profile directories firefox os application directory user profile directory temporary directory windows vista/7 c:\program files\mozilla firefox\ c:\users\<username>\appdata\roaming\mozilla\firefox\ (or %appdata%\mozilla\firefox\) c:\users\<username>\appdata\local\mozilla\firefox\ (or %localappdata%\mozilla\firefox) and c:\users\<username>\appdata\local\virtualstore\program files\mozilla firefox\ windows 2000/xp c:\program files\mozilla firefox\ c:\documents and settings\<username>\application data\mozilla\firefox\ (or %appdata%\mozilla\firefox\) c:\documents and settings\<username>\local settings\application data\mozilla\firefox\ os x /applications/firefox.app ...
...pp ~/library/application support/firefox/profiles/xxxxxxxx.default/ ~/library/caches/firefox/profiles/xxxxxxxx.default/ linux ???? ...
Cross Process Object Wrappers
g api. to learn more about this, see the documentation on using the message manager. chrome to content messaging must be asynchronous. this is because the chrome process runs the firefox ui, so if it were blocked by the content process, then a slow content process could cause firefox to become unresponsive to users. converting synchronous code to be asynchronous can be difficult and time-consuming. as a migration aid, the messaging framework enables frame scripts to make content objects available to chrome through a wrapper called a cross process object wrapper, also known as a cpow. however, although cpows are convenient, they have serious limitations and can cause responsiveness problems, so should only be used when necessary and only as a migration aid. passing cpows from frame script...
... following behavior: whenever chrome code tries to access content directly (for example, through window.content or browser.contentdocument), it is given back a cpow that wraps the content object. this means that examples like this will actually work, even in multiprocess firefox: gbrowser.selectedbrowser.contentdocument.body.innerhtml = "replaced by chrome code"; it's still important to keep in mind, though, that this is access through a cpow and not direct access to content. bidirectional cpows a common pattern is for chrome code to access content objects and add event listeners to them. to deal with this, cpows are bidirectional. this means that if content passes a cpow to the chrome process, the chrome process can synchronously pass objects (such as event listener functions) into funct...
Using the Browser API
Mozilla › Gecko › Chrome › API › Browser API › Using
listens for the mozbrowserlocationchange event. when this fires, we set the value inside the url bar input to be equal to the event object detail property — this is so that the url displayed continues to match the website being shown when the user navigates back and forth through the history. ...
...onchange', function (e) { urlbar.value = e.detail; }); zooming in and out the browser content can be programmatically zoomed in and out using the htmliframeelement.zoom() method. this takes a single method — a zoom factor — which dictates the percentage to zoom in or out by. for example, 1.1 would mean "zoom in by 10%", and 0.9 would mean "zoom out by 10%". var zoomfactor = 1; ... zoomin.addeventlistener('touchend',function() { zoomfactor += 0.1; browser.zoom(zoomfactor); }); zoomout.addeventlistener('touchend',function() { zoomfactor -= 0.1; browser.zoom(zoomfactor); }); controlling the stop/reload button next, let's talk about the stop/reload button. as in a traditional browser, this is a single button that acts as a reload button when the page has finished loading, ...
HTMLIFrameElement.zoom()
Mozilla › Gecko › Chrome › API › Browser API › zoom
warning: removed in firefox 65. the zoom() method of the htmliframeelement interface changes the zoom factor of the browser <iframe>'s content. this is particularly useful for zooming in/out on non-touch-enabled devices. syntax var instanceofdomrequest = instanceofhtmliframeelement.zoom(zoomfactor); returns void. parameters zoomfactor a unitless number value representing the amount to zoom in or out. it acts like a percentage, so for example 1.1 would zoom in by 10%, whereas 0.9 would zoom out by 10%. ...
...ch-enabled devices. syntax var instanceofdomrequest = instanceofhtmliframeelement.zoom(zoomfactor); returns void. parameters zoomfactor a unitless number value representing the amount to zoom in or out. it acts like a percentage, so for example 1.1 would zoom in by 10%, whereas 0.9 would zoom out by 10%. examples var browser = document.queryselector('iframe'); var zoomfactor = 1; zoomin.addeventlistener('touchend',function() { zoomfactor += 0.1; browser.zoom(zoomfactor); }); zoomout.addeventlistener('touchend',function() { zoomfactor -= 0.1; browser.zoom(zoomfactor); }); specification not part of any specification. ...
Embedding Tips
fied by a combination of state_stop | state_is_network state flags. you may also use the progress listener to query the request supplied in onstatechange for more information. for example, if you wanted to check the server response headers, you might check onstatechange for state_start | state_is_request flags, and from the nsirequest argument qi fornsihttpchanne and call methods on that to determine response codes and other information from the server. it is left as an exercise to make this sample synchronous, i.e. wait for persistence to complete before returning. hint, add a native message processing loop after the call to saveuri that terminates when onstatechange indicates persistence has finished.. how do i print a page? query the web browser object for nsiwebbrowserprint. call the ...
...(getter_addrefs(doc)); } what is the docshell? a description of the docshell may be found here. how do i implement context menus? make your chrome object implement the nsicontextmenulistener or nsicontextmenulistener2. the nsicontextmenulistener::onshowcontextmenu() method will be called with the dom node that the context applies, the dom event plus some flag combinations that assist in determining what menu to display (document, link, image, selected text etc.) how do i implement tool tips? make your chrome object implement the nsitooltiplistener interface. methods to hide or show the tool tips will automatically be called upon it when the user hovers over an item with title text. the contract id is defined here. for an example, see browserimpl.cpp in mfcembed and its simple cbrowser...
Getting from Content to Layout
d in the restyletracker are dispensed with from various method on the presshell that involve reflow and flushing notifications. frame construction regardless of whether content nodes are inserted/appended/deleted, frames can be created and destroyed, based on whatever is optimal for the changes in the content tree. "frame construction items" are queued for each change. these items are then examined in relation to the location in the content tree that is being modified and either the relevant frames are created/destroyed or the logic moves up to the parent frame. to give a trivial example of when this might be necessary, consider: "<span>foo <div></div> bar</span>". separate frames are created for the pre and post-div parts of the <span>. if the <div> is removed, the frame construction ...
...in the content tree that is being modified and either the relevant frames are created/destroyed or the logic moves up to the parent frame. to give a trivial example of when this might be necessary, consider: "<span>foo <div></div> bar</span>". separate frames are created for the pre and post-div parts of the <span>. if the <div> is removed, the frame construction code merges those frames by examining the parent frame, destroying the two frames created for the <span>, and creating one unified frame for the text content. examples of this type of code are in wipecontainingblock. this code tries hard to avoid unnecessary frame tree modifications and is rather complicated as a result. ...
How to get a stacktrace for a bug report
server currently only has debug information for mozilla builds and thus the crash reporter cannot work if you use a build from a linux distribution or if you compile from source code. in these cases you will need to use one of the alternative methods listed below. note: when filing a crash report, it is important to know whether the crash occurs with firefox safe mode. this helps engineers determine whether a particular extension or plugin is the cause of the crash. how to get a crash id with the mozilla crash reporter 1. crash and submit a report to the system. the mozilla crash reporter window should automatically come up after firefox crashes. if you have any additional information about the crash, such as additional detail on what you were doing at the time that may...
...ts 'crash reports' directory. if breakpad successfully sends the crash report to the reporting server then, by default, the files added to the 'pending' subdirectory for the crash are removed, and a .txt file is placed in the 'submitted' directory containing the crash id created by the reporting server. if you want breakpad to leave the .dump and .extra files on your computer so that you can examine them locally, then set the moz_crashreporter_no_delete_dump environment variable to 1. ubuntu: instructions from the ubuntu team opensuse: general instructions from opensuse fedora: capturing stack traces gentoo: debugging using gdb ...
How to Report a Hung Firefox
efox eventually recovers from a hang, you should try the instructions at reporting a performance problem instead.) is the rest of your system busy (high cpu or memory usage, or high disk activity)? if firefox is truly hung, please note the approximate amount of time you waited before forcing a crash (below) in the bug report. if you suspect a hang (as opposed to slow performance), wait one minute on an idle system before getting the stack trace. the crash report link for a hang, obtained by following the steps below. submit a crash report for a hung firefox the easiest way to help the firefox stability team to debug these kinds of hangs is to make the hung firefox crash and submit a crash report. then file a bug report with the crash report id. the steps to induce a crash are sligh...
...ar and click on the top listing. the crash report should look something like this report, which is an example of bug 1132241. create a new bug report at bugzilla.mozilla.org using this link. linux and mac on linux and mac (firefox >=27), sending sigabrt to a process will trigger the crash reporter. you can use any process monitoring tool to find the firefox process id (pid). 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. please check the box to send the crash report to mozilla start firefox. type "about:crashes" in the url bar and click on the top listing. create a new bug report at bugzilla.mozilla.org using this ...
Infallible memory allocation
s that your memory allocation request is guaranteed to succeed: your code can never see a failed request, and so doesn't need to check for failure. inside the allocation routine, the situation is different. under extreme memory conditions, it's possible that the allocation will fail; however, the allocation routine will not, in this scenario, return to your code. instead, the application will terminate. this should be rare, because the memory management system will do everything it can to find the memory you've asked for. 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 a...
...se 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. you should do this for large memory allocations because in extremely low memory conditions, as described in how can memory allocation be infallible?, the application may terminate if an infallible allocator can't find the memory you requested. if you don't know whether or not the memory will be large, use the standard malloc() routine. be sure to check the result for null. be warned that any allocation that's controlled by the user or web content may grow bigger than you expect; people and pages do surprising things all the time! when instantiating objects, the new op...
Addon
only integer a bitfield holding all of the current operations that are waiting to be performed for this add-on. operations are generally deferred when a restart is necessary to accomplish them. permissions read only integer a bitfield holding all the the operations that can be performed on this add-on. operations my be restricted based on system policies (e.g., the system administrator may not allow certain add-ons to be uninstalled), add-on type (e.g., themes may not be disabled), or add-on state (e.g., an incompatible add-on cannot be enabled). providesupdatessecurely read only boolean true if the add-on has a secure means of updating or cannot be updated at all. scope read only integer indicates what scope the add-on is installed in, p...
...version a platform version to test against findupdates() starts an update check for this add-on. this will perform asynchronously and deliver results to the given listener. void findupdates( in updatelistener listener, in integer reason, in string appversion, in string platformversion ) parameters listener an updatelistener for the update process reason a reason code for performing the update appversion an application version to check for updates for platformversion a platform version to check for updates for optional methods uninstall() uninstalls this add-on. if possible the uninstall will happen immediately, otherwise it will wait until the next application restart. this method must be defined if an add-on has the permission perm_can_uninstall. void uninstall(...
AddonManager
as possibly altered. startup_change_uninstalled a list of add-ons that were detected as having been uninstalled during startup. this doesn't include add-ons for which uninstall was pending the last time the application was running. startup_change_disabled a list of add-ons that were detected as having become disabled during startup. this normally means the application determined that the add-on is incompatible. this doesn't include add-ons that were pending becoming disabled the last time the application was running. startup_change_enabled a list of add-ons that were detected as having become enabled during startup. this normally means the application determined that an application change has made the add-on compatible. this doesn't include add-ons that wer...
... methods addstartupchange() adds an add-on change from the add-on changes list. this is used to build the lists of changed add-ons reported by the getstartupchanges() method. ...
CustomizableUI.jsm
sed widgets. onwidgetinstanceremoved(awidgetid, adocument) fired when a window is unloaded and a widget's instance is destroyed because of this. awidgetid is the widget whose instance is being destroyed, adocument the document in which this is happening. only fired for api-based widgets. onwidgetdrag(awidgetid, aarea) fired both when and after customize mode drag handling system tries to determine the width and height of widget awidgetid when dragged to a different area. aarea will be the area the item is dragged to, or undefined after the measurements have been done and the node has been moved back to its 'regular' area. oncustomizestart(awindow) fired when opening customize mode in awindow. oncustomizeend(awindow) fired when exiting customize mode in awindow. onwidgetoverflow(anode...
... split according to purpose: dynamic getters attribute type description areas array always returns an up to date array of all the area ids that are currently registered with customizableui. indefaultstate bool whether we're in a default state. note that non-removable non-default widgets and non-existing widgets are not taken into account in determining whether we're in the default state. nb: this is a property with a getter. the getter is not cheap, because it does smart things with non-removable non-default items, non-existent items, and so forth. please don't call unless necessary. canundoreset bool whether the "restore defaults" operation can be reverted. this is only true after "restore defaults" has been performe...
Log.jsm
cformatter())); // a dump appender logs to stdout. log.addappender(new log.dumpappender(new log.basicformatter())); // log some messages log.error("oh noes!! something bad happened!"); log.debug("details about bad thing only useful during debugging", {someinfo: "nothing"}); log.warn("here is an error", new error("ouch")); logger levels fatal severe errors that cause premature termination. expect these to be immediately visible on a status console. error other runtime errors or unexpected conditions. expect these to be immediately visible on a status console. warn use of deprecated apis, poor use of api, 'almost' errors, other runtime situations that are undesirable or unexpected, but not necessarily "wrong". expect these to be immediately visible on a...
...ble on a status console. warn use of deprecated apis, poor use of api, 'almost' errors, other runtime situations that are undesirable or unexpected, but not necessarily "wrong". expect these to be immediately visible on a status console. info interesting runtime events (startup/shutdown). expect these to be immediately visible on a console, so be conservative and keep to a minimum. config information regarding important configuration options the system is using that affect how it runs. debug detailed information on the flow through the system. expect these to be written to logs only. trace most detailed information. expect these to be written to logs only. class overview appender(); length: 1 keys of prototype...
NetUtil.jsm
to use these utilities, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/netutil.jsm"); once you've imported the module, you can then use its methods. ...
... representing the specified target. exceptions thrown this method throws an exception with the message "must have a non-null string spec or nsifile object" and result code ns_error_invalid_arg if aspec is null. readinputstreamtostring() reads a given number of bytes from an input stream, returning a string containing those bytes. this works even if some of those bytes are zeros, instead of terminating the string at the first zero byte. string readinputstreamtostring( ainputstream, acount, aoptions ); parameters ainputstream the input stream from which to read the data. acount the number of bytes to read from the stream. you can call nsiinputstream.available() to get the number of bytes currently available. aoptions specifies additional options to control the reading proce...
Examples
ueaftertimeout("value", 1000); let newpromise = promise.then(function onfulfill(avalue) { console.log("fulfilled with this value: " + avalue); }, function onreject(areason) { console.log("rejected with this reason: " + areason); }); // unexpected errors should always be reported at the end of a promise chain. newpromise.then(null, components.utils.reporterror); note: more examples for consuming promises are available in the promise object documentation. make user defined promise return after multiple images finish loading (promise.all and promise.defer) this example shows how to use promise.all to wait to create multiple promises with promise.defer() and return at the end of it. components.utils.import("resource://gre/modules/promise.jsm"); var mypromise = myuserdefinedpromise(); m...
...png']; change it to: var imagepaths = ['http://www.mozilla.org/media/img/firefox/favicon.png', 'https://developer.cdn.mozilla.net/media/redesign/img/favicon32.png', 'blah blah']; i added 'blah blah' to that array, it will cuase the whole promise to reject. the case of unhandled rejections one of the difficult problems with promises is locating uncaught rejections. warning: when consuming promises, you should always handle or report errors (rejection reasons). see handling errors and common pitfalls. rejection handlers provide information about the exact error time and location, but the handlers may sometimes be forgotten. consider the following cases: function f() { return promise.reject(new error("boom!")); // if nobody catches the error, how will it be reported? } funct...
PromiseWorker.jsm
a javascript file used by the worker thread, which is created by promiseworker.jsm in main thread, to communicate with the main thread. promiseworker.js provides abstractworker. here's the simplified diagram of how promiseworker works (svg version of the promiseworker diagram) setup and usage this section explains how to set up and use a promiseworker. as well known with workers, there is a minimum of two files required. the worker file, and the main thread file. the following sections tell you which content to use in your worker and main thread files, in order to use promiseworker objects. worker file there is some standard templating that must be dropped into the worker file by the developer. the require.js file must be imported with workerglobalscope/importscripts(). next, the prom...
...example can be rewritten like this: myworker.post('func', [new basepromiseworker.meta(buffer, {transfers: [buffer]})]); this is convenient if the function's arguments are generated by some other functions or passed from somewhere else. post callsite doesn't have to know which object should be transferred. for example: myworker.post('func', [foo(), bar(), baz()]) foo now has the power to determine if the argument should be transferred by returning a meta instance. so it can transfer an object without modifying the caller. here is a simple demo showing how to transfer the second argument to a worker: github:: promiseworker transfer data line 23. the command outline below this shows how to do the same with meta syntax. sending a message from worker with all other workers, to send a messa...
WebChannel.jsm
ing the scheme is https). components.utils.import("resource://gre/modules/webchannel.jsm"); constructor webchannel(string webchannelid, nsiuri originorpermission); 2nd argument is a valid origin that should be part of requests for this channel. webchannel(string webchannelid, string originorpermission); 2nd argument is a permission for which the permission manager will be checked to determine if the request is allowed. note that in addition to the permission manager check, the request must be made over https. method overview listen(function callback); stoplistening(); send(object message, eventtarget target); attributes id string webchannel id methods listen() registers the callback for messages on this channel. registers ...
...ening(); send(object message, eventtarget target); attributes id string webchannel id methods listen() registers the callback for messages on this channel. registers the channel itself with the webchannelbroker. parameters callback callback function containing function(id, message, sendercontext) parameters. id - webchannel id of the incoming messages message - incoming message object sendercontext - incoming message context - this should be treated as an opaque object and passed to the .send() method stoplistening() resets the callback for messages on this channel. removes the channel from the webchannelbroker. parameters none send() sends messages over the webchannel id using the "webchannelmessagetoc...
source-editor.jsm
you can listen for any of the events listed in event name constants. to stop listening for the event, call removeeventlistener(). void addeventlistener( string aeventtype, function acallback ); parameters aeventtype the name of the event type to listen for; see event name constants for possible values. acallback the function to call when the specified event occurs. canredo() determines whether or not there are changes that can be redone. boolean canredo(); parameters none. return value true if there are changes that can be redone, otherwise false. canundo() determines whether or not there are changes that can be undone. boolean canundo(); parameters none. return value true if there are changes that can be undone, otherwise false. destroy() destroys the editor,...
...ethods. void init( element aelement, object aconfig function acallback ); parameters aelement the dom element in which to place the editor. aconfig an object containing a set of properties used to configure the editor. see the editor configuration object for details. acallback a function that will be called when the editor has been fully loaded and initialized. hasfocus() determines whether or not the editor is currently focused. boolean hasfocus(); parameters none. return value true if the editor is currently focused, otherwise false. redo() redoes the most recently undone change in the editor. boolean redo(); parameters none. return value true if a change was redone, otherwise false. removebreakpoint removes the breakpoint from the specified line of code.
JavaScript code modules
ong with download links and documentation, that extension developers can use in their code. standard code modules addonmanager.jsm an interface to install, manage, and uninstall add-ons. addonrepository.jsm provides a search of add-ons in the repository. assert.jsm implements the commonjs unit testing specification version 1.1, which provides a basic standardized interface for performing in-code logical assertions with optional, customizable error reporting. bookmarkhtmlutils.jsm provides utility functions for importing and exporting bookmarks from the old-school "bookmarks.html" style bookmark files. ctypes.jsm provides an interface that allows javascript code to call native libraries without requiring the development of an xpcom component. customizableui.jsm allows you t...
...ask.jsm run a task after a delay. dict.jsm provides an api for key/value pair dictionaries. downloadlastdir.jsm supplies the path to the directory into which the last download occurred. downloads.jsm provides a single entry point to interact with the downloading capabilities of the platform. fileutils.jsm provides helpers for dealing with files. geometry.jsm provides routines for performing basic geometric operations on points and rectangles. http.jsm a wrapper for xmlhttprequest that provides convenient and simplified api for dealing with http requests. jni.jsm abstracts the js-ctypes to provide an interface that allows javascript code to call code running in native jvms. iso8601dateutils.jsm provides routines to convert between javascript date objects and iso 8601 date stri...
Index
guide guide, translation this guide is filled with all of the basic, technical information you need to get involved in the mozilla l10n program. 13 initial setup localization as a pre-requisite to contributing to the l10n program, you need to have access to code, tools, and a properly configured local environment (i.e., your personal computer). you also need to determine if a localization effort already exists for your locale. here we'll go over the accounts you need as well as the tools and their configurations you need to set up before contributing. 14 qa phase localization after all of your hard work localizing we're sure that you not only want to see your work but you want to make sure it's accurate! if you don't have a lot of experience...
...the tools and their configurations you need to set up before contributing. 14 qa phase localization after all of your hard work localizing we're sure that you not only want to see your work but you want to make sure it's accurate! if you don't have a lot of experience with code, you might even be concerned that you've broken something (oops!). now we'll walk you through performing some quality assurance testing on your work to make sure you're on the right track. 15 release phase localization you've made it! you've setup up your local and remote environments, you've selected your l10n tools and projects, done some localization and even some testing! now you're ready for the final phase: becoming an official l10n release. here, we'll continue to stay t...
Mozilla Content Localized in Your Language
s: 1)fully spelled out, 2). 2 or 3 letters and 3). single letter. and what is the order of year, month and day? reference material can be find here calendar calendar view: which date is considered the first day of the week, sunday or monday? is lunar calendar observed? other regional calendar observed? time format how is time expressed in your language? including 0-24 hr expression, hour, minute and second. percentages how are percentages expressed in your language? digit groups how are digit groups expressed in your language? example: 1.23 (decimal separator) or 1,000 (thousand separator) using comma or period. acronyms do you translate widely accepted acronyms such as cd, dvd, mb? if translated, is there an equavilent acronym and widely accepted in the language? gender ar...
...ostal code][state/province][city][district][street number and name][building and suite numbers][addressee] countries of european languages start from small to big: [addressee][street number and name][building and suite numbers][district][city][state/province][postal code][country] name convention what are the order of family name and given name in your language. here is the guideline on the naming convention from w3c.org: new terminology what is your localization team's process for identifying and creating new terminology? currency currency and symbol. what are other widely used currency and symbols used in your country/language for paid apps. user interface elements titles should be brief and precise. localizers can assume that source content reaches 2/3 of...
Localization content best practices
ging to different categories and are treated differently by the grammar), case and inflections (changes are made to a word to indicate differences in meaning or use) and so on. in modern english, such features are rare and are mainly restricted to plural -s and verb forms (e.g. go > went is a form of inflection). examples from other languages: gender in german: nouns can be either masculine, feminine or neuter. the most obvious impact is that the definite article which in english is always the can either be der, die or das. to complicate matters, if the grammatical context changes, the article will change: der text 'the text' changes to wollen sie den text speichern? 'do you want to save the text?' suffixes in basque: where english tends to use expressions such as 'to the' or 'from the', ...
...-transform: uppercase to app size but in gaelic this would change meud na h-aplacaid to meud na h-aplacaid which violates the locales orthographic rules, as it ought to be meud na haplacaid. in general, localizers should make the decision about capitalization. if you want to display warning, add a string with that capitalization, and explain it in the localization note. design for +50% bear in mind that english strings will likely be a lot shorter than their international equivalents, so you need to leave some space in your ui to allow for this. some examples: ok in english becomes ceart ma-thà in gaelic. save document? in english becomes a bheil thu airson an sgrìobhainn a shàbhaladh in gaelic. another good example is yes/no. there are two types of languages, those that have yes/...
Localizing XLIFF files for iOS
iting the raw xliff file is also rather easy, especially if you're already familiar with xml. this tutorial will walk you through the steps you need to take to translation strings within an xliff file. string repository for firefox on ios the firefox-ios.xliff file is located in svn. decide where on your local computer you will store your copy of the github repo and navigate there in your terminal. enter the command git clone https://github.com/mozilla-l10n/firefoxios-l10n/your-locale-code/ you should now see the firefox-ios project in your selected directoy with the firefox-ios.xliff file in it. translating the xliff file open the firefox-ios.xliff file in your favorite text editor. in the <file> tag, add the target-language attribute with your locale code as the value (e.g., ta...
...below each <source> tag set to help you to identify strings that need to be translated. do not delete the <source> tag sets. <trans-unit id="add to bookmarks"> <source>add to bookmarks</source> <target>your_translation_here</target> </trans-unit> provide translations of the strings in the <source> tag sets by placing their translations in the <target> tag sets beneath them. keep in mind the following sets of characters that need to remain untranslated: $(some_text_here) is a variable format, %1$@ is another variable format. <note> tags contain localizer notes from developers and should not be translated. <trans-unit id="add to bookmarks"> <source>add to bookmarks</source> <target>agregar a marcadores</target> <note>no comment provided by engineer.<...
Localizing with Koala
uldn't be deleted. to see the results of the comparison for locale's all files (including searchbar.dtd), switch to "locale files" view in the "koala file view" sidebar. you're now looking at your locale's file structure and can see that searchbar.dtd is "unmodified" with 2 translated entities (0 missing, 0 obsolete), whereas search.properties is "modified" with 1 translated entity (6 total minus 5 missing, 0 obsolete). click on any of the files to see more detail, including the exact list of missing (green "+" icon), obsolete and translated (white circle icon) entities. now that you've translated these 3 strings, let's commit your work to the local hg repository that you created in the "creating a new project" section. committing your work hopefully by now, you have translated 3 str...
...'s best to commit often (e.g. after you finish translating every file, or even more frequently). koala supports mercurial and allows you to add and commit files automatically from komodo. for the purposes of this tutorial, we will switch to the command line every now and then to see what koala does behind the scenes. normally though, you don't have to use the command line to commit your work. assuming that your locale files are in c:\mozilla\l10n\locale\x-testing\3.6 which is where the local mercurial repository was created (see creating a new project section), you should be able to successfully issue "hg cmd" commands in that directory (where "cmd" might be "status", "log", "commit" etc.). for example, try issuing "hg status" inside c:\mozilla\l10n\locale\x-testing\3.6: c:\mozilla\l10n\local...
Localizing with Mercurial
ing commands. choose the appropriate command for your distribution and make sure to run as root. # debian/ubuntu $ apt-get install mercurial # fedora $ yum install mercurial # gentoo $ emerge mercurial # arch linux $ pacman -s mercurial # opensolaris $ pkg install sunwmercurial if you prefer a graphical interface, you can download and install mercurialeclipse here. did it work? open a terminal window and enter hg --version. if you see a message about the version of mercurial (e.g. mercurial distributed scm (version 1.3.1)), you have installed mercurial successfully! more details for more details on installing hg on linux systems, refer to the instructions on mercurial's download page. mercurial on windows with windows, you have a couple of install options: for a command line i...
...e new shell window. if you see a message about the version of mercurial (e.g. mercurial distributed scm (version 1.3.1)), you have installed mercurial successfully! more details for more details on installing hg on windows, refer to the instructions on mercurial's download page. mercurial on mac osx installing hg on mac osx is super easy. you can install mercurial via macports through the terminal, like so: $ sudo port install mercurial you can also install it by downloading the dmg package from the hg download page. it has an install dialog that will walk you through the process. if you prefer a graphical interface, you can download and install mercurialeclipse here. did it work? open a terminal window and type hg --version. if you see a message about the version of mercurial (e.g.
Initial setup
as a pre-requisite to contributing to the l10n program, you need to have access to code, tools, and a properly configured local environment (i.e., your personal computer). you also need to determine if a localization effort already exists for your locale. here we'll go over the accounts you need as well as the tools and their configurations you need to set up before contributing. new or existing before anything else, you need to know if you will be creating a new localization or joining an existing one. this will determine what information is most applicable to you throughout the rest of this guide. here's what you do: look through the existing localization community directory to see if one already exists for your locale. if a community already exists, reach out to them and ask...
... creating mozilla application builds and language packs. we use version 2.13 and higher for these builds. you can find the source files and install instructions here. wget wget is a command-line utility that allows you to retrieve files using internet protocols. we use it for retrieving files from repositories. you can find the source files and install instructions here. perl perl is a programming language that will help you create mozilla application builds and language packs. you can find the source files and install instructions here. python python is a programming language in which many of our l10n testing scripts are written. you can find the source files and install instructions here. locale switcher or quick locale switcher both locale switcher and quick locale switcher are add...
Release phase
here, we'll continue to stay true to the original intent of this guide and only present you with the technical information you need to become an official release. we'll primarily focus on getting your release repository setup and the mercurial commands you'll need to know to use that repository. ...
...ating to branch default 239 files updated, 0 files merged, 0 files removed, 0 files unresolved the default push url is the same as the default pull url (i.e., ssh://hg.mozilla.org/releases/l10n-central/x-testing). you should now be able to push to the remote repository! commit, outgoing, and push you should try to commit your work regularly as you progress through the localization files. keep in mind that the hg commit command will save your changes locally (in the local clone). with the hg push command you can send the changesets to the remote server. here's how that's done: run this command to see recent commits in your local clone: $ hg log -l 3 you should a list of the most recent commits, similar to this one: changeset: 0:7c543e8f3a6a tag: tip user: your name <email...
Translation phase
he l10n tools are meant to help you maintain your localized content from release to release and leverage already localized materials when localizing new content. here we'll identify those groups of projects and the l10n tools associated with them. along the way we'll point you to basic, technical tutorials on localizing for that particular project group. it's up to you and your community to determine which l10n tool will best suit your needs. as you gain more experience, you may want to localize independent of mozilla-developed l10n tools, which we'll also discuss here. projects the mozilla projects and their l10n workflows are divided into these groups: mozilla applications, mozilla websites, and add-ons. below you'll find the list of all mozilla projects, their associated l10n tools, and...
...ou need to secure and maintain your tool independence. productization productization is an essential part of localizing mozilla products. this is where you research and select the search plugins, content and protocol handlers, bookmarks, and links to recommended sites on the in-product pages that your locale's users will find in their mozilla products. this tutorial will walk you through performing these productization tasks, creating productization patches, and submitting them for review. « previousnext » ...
Localization technical reviews
this review process to perform quality assurance (qa) testing on your l10n efforts. this ensures that every user who downloads your localized mozilla application receives all of your hard work in a functional product. each qa review helps us in these ways: ensures that your l10n work is visible and functional within the mozilla application. allows us to understand how each l10n team is performing their localization work. allows us to discover potential bugs within l10n tools. overview you've completed most, if not all, of your localization work. the merge date for migrating from one product release channel to the next (e.g., aurora to beta, or beta to release) is rapidly approaching. you need to make sure that your work can effectively be compiled into a build for the next release ch...
...ecurity/manager/chrome/pipnss/pipnss.properties file that you should be aware of. it is best to look into each of these files to see if the localizer's strings might be too long. this is something to look for, but can be difficult to diagnose immediately. for more info, see bug 435874. check for bad migration of access keys in the past, it was common to find broken access keys for safari and camino in browser/chrome/browser/migration/migration.dtd. for this review, we look at this file to make sure that the access keys look normal. if they don't, we report any strange access keys or translations that localizers might have changed during their initial translation process. for more info about access keys in the technical review process, see bug 421893. no utf-7 in the intl.properties file ...
Uplifting a localization from Central to Aurora
localizers who are working on l10n-central are responsible for getting their work onto the aurora repository. here some tips and tricks for syncing up both l10n-central and releases/l10n/mozilla-aurora at the same time en-us goes from central to aurora. you want to have a repo from which you can uplift to aurora shortly after the migration. the releases page on wikimo has the upcoming dates. you should be good doing it the day after. you don't need to work on making the synchronization happen in either of your copies of the aurora or central repositories, but you can create a third one for this work. we even suggest that you do. that makes it easier to throw away attempts that didn't work. so, here are the mercurial steps to reproduce. prerequisites: merge tool.
... ...
gettext
consider the following code snippet: <?php $num = 1; printf(ngettext("%d user likes this.", "%d users like this.", $num), $num); ?> depending on the value of the $num variable, this code will either use the singular ("user likes) or the plural ("users like") form of the string. notice that you need to pass the $num variable twice. first in the ngettext() call, where it will be used to determine which form of the string will be returned. in the above example, $num equals 1, so the string returned (for english) will be %d user likes this. the second time the $num variable is passed in the printf() call, which at this point of interpretation looks something like printf("%d user likes this.", $num);. the %d in the first argument (which is the string returned by gettext) will be replaced wi...
...hp:3 #, php-format msgid "%d user likes this." msgid_plural "%d users like this." msgstr[0] "" msgstr[1] "" depending on the localizer's target language and its rules for creating plural forms, there might be another field for translation, e.g. msgstr[2]. gettext will return one of the msgstrs, depending on the number passed to the gettext function in the code ($num in the above example). to determine which form to return, gettext uses a plural rule, which should be declared in the po file header. for example, for english, the plural rule is of the following form: plural-forms: nplurals=2; plural=n != 1; the first part defines the number of different plural forms (2). the second part is evaluated and the result of the evaluation is used to choose the right msgstr. in the rule above, if n equ...
Mozilla Framework Based on Templates (MFBT)
like "mozilla/standardinteger.h". it is fairly new, so its functionality is currently sparse. feel free to file bugs to add new functionality to it, or to move existing functionality into it, as needed. mfbt code goes to some length to document all its interfaces in comments, including examples when possible. it also attempts to define its functionality in well-named files, such that simply skimming the contents of mfbt/ will quickly suggest the relevant header to examine. therefore this document primarily attempts to direct readers to the correct file to read those comments. feel free to file a documentation bug if you think this approach could be improved, and feel free to make improvements to this document if you see them. functionality types and type manipulation standardinteger.h im...
...s header also provides a useful "hook" for embeddings that must customize the types underlying the fixed-size integer types.) types.h includes standardinteger.h and further provides size_t. checkedint.h implements checked integers. they behave like integers, but safely check for integer overflow and divide-by-zero. useful for input validation. floatingpoint.h provides various operations for examining and working upon double-precision floating point values, and for producing various special floating point values. core types.h further provides macros to define imported and exported c symbols. attributes.h implements various function and class attribute macros. the function macros control inlining, note whether a function returns, and enforce various c++-related restrictions on inheritance...
Mozilla Port Blocking
. for details on which ports are blocked and how to override the blocking see below. modifying mozilla's port blocking at run time users can modify the default port blocking through the addition of preferences containing comma delimited lists of port numbers to the user.js file (for single users with the user_pref(…) command) in the user's profile directory. see the example below. additionaly administrators can edit the all.js file (for multi-user systems with pref(…) ) in the defaults/pref/ sub-directory in the installation directory. enabling ports user_pref("network.security.ports.banned.override, "port1,port2"); disabling ports user_pref("network.security.ports.banned", "port3,port4"); blocked ports ports blocked by default in mozilla: port service 1 tcpmux ...
...s own protocol to function. ports enabled by protocol handlers in mozilla: protocol handler allowed ports ftp 21, 22 ldap 389, 636 nntp any port pop3 any port imap any port smtp any port finger 79 datetime 13 how to change mozilla port blocking permanently since each protocol can determine which ports are blocked, you should contact the protocol handler owner to request that a specific port be blocked or unblocked. if that fails, contact dougt@netscape.com and/or darin@netscape.com. you must have a good reason for the change, a deep understanding of the security risk involved and be able to justify it. things to do allow user preference to override default port blocking. current...
Mozilla Web Services Security Model
apply to web services. however, web services can be designed to be accessed from other domains, or even from any domain. mozilla allows sites hosting such web services to tell mozilla that other sites can access the service. they do this by creating a file called web-scripts-access.xml in the root of the server that grants permission for other domains to access web services. for example, to determine what web sites can access a web service at http://www.example.com/dir1/dir2/service, mozilla would load the file http://www.example.com/web-scripts-access.xml, which may choose to delegate the decision to http://www.example.com/dir1/dir2/web...pts-access.xml. web-scripts-access.xml file format the web-scripts-access.xml file is an xml document. any errors in xml syntax, as well as many failure...
...ns that the browser should delegate the access control to a web-scripts-access.xml file in the directory that the service is in. for example, when accessing a web service at http://www.example.com/dir1/dir2/service, if the access file at http://www.example.com/web-scripts-access.xml contains a delegate element, mozilla will instead use http://www.example.com/dir1/dir2/web...ipt-access.xml to determine whether access is permitted. if no such file exists, then access will be denied. the allow element if no delegate elements are present or if the web service is in the same directory as the web-script-access.xml file, then the allow elements will be processed. if the file exists but contains no allow elements, then all access will be allowed. if allow elements exist, then the access will be all...
Mozilla Quirks Mode Behavior
mode, the font element changes the color of text decorations specified on ancestor elements. proposed to apply in all modes: bug 747517. in quirks mode, text-decoration is propagated into floating and absolutely positioned elements. (firefox 4 / thunderbird 3.3 / seamonkey 2.1) in quirks mode, text-decoration is not propagated into tables (bug 572713). maybe (firefox 3) when computing the minimum intrinsic width of an inline flow directly in a table cell (no blocks in between), it is assumed that it is not possible to break before and after an image (when otherwise it would be). obsolete since gecko 8.0 prior to gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) text-decoration in quirks mode had line thickness and position adjusted on descendant text to match the descendant. ...
...(firefox 16) for standards mode but remains in quirks mode for compatibility with quirks mode behavior of other browsers. (firefox 16 / thunderbird 16 / seamonkey 2.13) since this version bug 338554 is fixed and (-moz-)box-sizing applies to table cells in standards mode, but quirks mode keeps the old behavior. obsolete since gecko 1.9 (firefox 3) in quirks mode table cells with a border have a minimum width of one pixel. obsolete since gecko 1.9 (firefox 3) the basic table layout strategy ignores padding (on what) in quirks mode. obsolete since gecko 1.9 (firefox 3) the basic table layout strategy handles widths differently in some way. obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) in quirks mode absmiddle (handled incorrectly?) and middle (perhaps incorrectly a...
Mozilla Style System Documentation
stylesheet and nsistylerule correspond to the css concepts of style sheets and style rules, except they are more general, and are used by other code that needs to add style information to the document. for the css stylesheets, this process corresponds to css selector matching. the output of css selector matching as defined by the css specification is an ordered list of rules, where the order determines which declarations override other declarations. (in css,declarations are the property-value pairs within style rules. in mozilla, nscssdeclaration objects correspond to css declaration-blocks.) due to the high similarity of these lists between elements in the content tree, mozilla stores the output of the selector matching process in a lexicographic tree, the rule tree. this double tree (style ...
...and allows the data computation to take less time. for example, suppose we had the css stylesheet: /* rule 1 */ doc { display: block; text-indent: 1em; } /* rule 2 */ title { display: block; font-size: 3em; } /* rule 3 */ para { display: block; } /* rule 4 */ [class="emph"] { font-style: italic; } and the following document: <doc> <title>a few quotes</title> <para class="emph">benjamin franklin said that <quote>"a penny saved is a penny earned."</quote></para> <para>franklin d. roosevelt said that <quote>"we have nothing to fear but <span class="emph">fear itself</span>."</para> </doc> this will lead to a rule tree that looks like this, where each node is in the format [name of node: rule it points to]: [a: null] ,------' / \ `---...
DMD
abled at start-up. if you wish to trigger dmd dumps from within c++ or javascript code, you can use nsimemoryinfodumper.dumpmemorytotempdir. for example, from javascript code you can do the following. const cc = components.classes; let mydumper = cc["@mozilla.org/memory-info-dumper;1"] .getservice(ci.nsimemoryinfodumper); mydumper.dumpmemoryinfototempdir(identifier, anonymize, minimize); this will dump memory reports and dmd output to the temporary directory. identifier is a string that will be used for part of the filename (or a timestamp will be used if it is an empty string); anonymize is a boolean that indicates if the memory reports should be anonymized; and minimize is a boolean that indicates if memory usage should be minimized first. (linux only) you can send s...
... to push this to the device and make it executable. since you cannot mark files in /sdcard/ as executable, we will use /data/local/tmp for this purpose: adb push dmd_fennec /data/local/tmp adb shell cd /data/local/tmp chmod 755 dmd_fennec the final step is to make android use the above wrapper script while launching fennec, so that the environment variable is present when fennec starts up. assuming you have done a local build, the app identifier will be org.mozilla.fennec_$username ($username is your username on the host machine) and so we do this as shown below. if you are using a dmd-enabled try build, or build from other source, adjust the app identifier as necessary. adb shell su # you need root access for the setprop command to take effect setprop wrap.org.mozilla.fennec_$username...
Power profiling overview
ing point for anybody doing power profiling for the first time. basic physics concepts in physics, power is the rate of doing work. it is equivalent to an amount of energy consumed per unit time. in si units, energy is measured in joules, and power is measured in watts, which is equivalent to joules per second. although power is an instantaneous concept, in practice measurements of it are determined in a non-instantaneous fashion, i.e. by dividing an energy amount by a non-infinitesimal time period. strictly speaking, such a computation gives the average power but this is often referred to as just the power when context makes it clear. in the context of computing, a fully-charged mobile device battery (as found in a laptop or smartphone) holds a certain amount of energy, and the speed at ...
... or off. try putting the relevant tab in the foreground vs. in the background. if the problem manifests on a particular website, try saving a local copy of the site and then manually removing html elements to see if a particular page feature is causing the problem many power problems are caused by either high cpu usage or high wakeup frequency. use one of the low-context tools to determine if this is the case (e.g. on mac use powermetrics.) if so, follow that up by using a tool that gives high-context measurements, which hopefully will identify the cause of the problem. for high cpu usage, many profilers can be used: firefox's dev tools profiler, the gecko profiler, or generic performance profilers. for high wakeup counts, use dtrace or perf or timerfirings logging. ...
Profiling with Xperf
ed. the stock windows crt allocator is horrible about fragmentation, and causes memory usage to rise drastically even if only a small fraction of that memory is in use. however, even despite this, it's a useful way to track allocations/deallocations. capturing heap data the "-heap" option is used to set up heap tracing. firefox generates lots of events, so you may want to play with the buffersize/minbuffers/maxbuffers options as well to ensure that you don't get dropped events. also, when recording the stack, i've found that a heap trace is often missing module information (i believe this is a bug in xperf). it's possible to get around that by doing a simultaneous capture of non-heap data. to start a trace session, launching a new firefox instance: xperf -on base xperf -start heapsession -he...
...e stack, i've found that a heap trace is often missing module information (i believe this is a bug in xperf). it's possible to get around that by doing a simultaneous capture of non-heap data. to start a trace session, launching a new firefox instance: xperf -on base xperf -start heapsession -heap -pidnewprocess "./firefox.exe -p test -no-remote" -stackwalk heapalloc+heaprealloc -buffersize 512 -minbuffers 128 -maxbuffers 512 to stop a session and merge the resulting files: xperf -stop heapsession -d heap.etl xperf -d main.etl xperf -merge main.etl heap.etl result.etl "result.etl" will contain your merged data; you can delete main.etl and heap.etl. note that it's possible to capture even more data for the non-heap profile; for example, you might want to be able to correlate heap events wit...
about:memory
-categories, sub-sub-categories, etc., to arbitrary depth, as needed. all the measurements within a single tree are non-overlapping. tree paths can be written using '/' as a separator. for example, preference/referent/weak/dead represents the path to the final leaf node in the example tree above. sub-trees can be collapsed or expanded by clicking on them. if you find any particular tree overwhelming, it can be helpful to collapse all the sub-trees immediately below the root, and then gradually expand the sub-trees of interest. sections memory reports are displayed on a per-process basis, with one process per section. within each process's measurements, there are the following subsections. explicit allocations this section contains a single tree, called "explicit", that measures all the ...
...s will be inserted. the "js-non-window" sub-tree represents javascript memory usage that doesn't come from windows, but from the browser core. the "heap-unclassified" value represents heap-allocated memory that is not measured by any memory reporter. this is typically 10--20% of "explicit". if it gets higher, it indicates that additional memory reporters should be added. dmd can be used to determine where these memory reporters should be added. there are measurements for other content such as images and workers, and for browser subsystems such as the startup cache and xpconnect. some add-on memory usage is identified, as the following example shows. ├───40,214,384 b (04.17%) -- add-ons │ ├──21,184,320 b (02.20%) ++ {d10d0bf8-f5b5-c8b4-a8b2-2b9879e08c5d}/js-non-window/z...
Performance
sheriffing information on automated performance testing and sheriffing at mozilla. best practices for front-end engineers tips for reducing impacts on browser performance in front-end code. memory profiling and leak detection tools the developer tools "memory" panel the memory panel in the devtools supports taking heap snapshots, diffing them, computing dominator trees to surface "heavy retainers", and recording allocation stacks. about:memory about:memory is the easiest-to-use tool for measuring memory usage in mozilla code, and is the best place to start. it also lets you do other memory-related operations like trigger gc and cc, dump gc & cc logs, and dump dmd reports. about:memory is built on top of firefox's memory reporting ...
...tacks. about:memory about:memory is the easiest-to-use tool for measuring memory usage in mozilla code, and is the best place to start. it also lets you do other memory-related operations like trigger gc and cc, dump gc & cc logs, and dump dmd reports. about:memory is built on top of firefox's memory reporting infrastructure. dmd dmd is a tool that identifies shortcomings in about:memory's measurements, and can also do multiple kinds of general heap profiling. are we slim yet areweslimyet.com (a.k.a. awsy) is a memory usage and regression tracker. bloatview bloatview prints per-class statistics on allocations and refcounts, and provides gross numbers on the amount of memory being leaked broken down by class. it is used as part of mozilla's co...
Research and prep
it is one of the most customizable and localizable parts of the product l10n process, as it goes beyond string translation. we believe that localization teams are in the best position to provide recommendations on what local providers we can use for web services because you're in the market, work in the language, and know your users. this is, therefore, meant to be a guideline for how you should be formulating your recommendations. ...
...ilos@mozilla.com or milos on irc. rss readers and content handlers productization for rss readers and content handlers applies only to firefox desktop. your selections for default rss readers and content handlers should follow these guidelines: be translated in your language (because it makes the application unusable if it's not in your language provide for the intended user experience (e.g., minimal to no advertisements within the user experience) no more than three (if possible) choices. choosing based on popularity is fine. examples from various localizations some examples from en-us web service provider rationale global search google best user experience and broadest results. e-commerce search amazon broad set of products, simple sear...
AsyncTestUtils extended framework
-chain that long. for example, if you pass 3, then 1 <- 2 <- 3 is what the reply chain looks like. if you need more complicated threads you will need to use the messagescenariofactory. age: (strictly incrementing from arbitrary origin) the default starts at jan 1, 2000 and adds an hour for every message. if you pass an object, it should be an object with one or more of the following attributes: minutes, hours, days, weeks. these attributes specify how old the message should be. for example, {weeks: 2, days: 3} would be a message sent exactly 17 days ago. if you pass age, you should also pass age_incr. age_incr: (no increment) takes an object of the same style taken by age. this specifies the time interval we should add to the date for each message. due to a bug, you should pass negative v...
... from john doe to random recipients. synthetic message sets the code that creates synthetic message sets returns instances of the syntheticmessageset class. this class not only holds references to the syntheticmessage instances, but it also tracks what folders they were injected into as well as what folders you move them to. this allows you to get at the nsimsgdbhdr instances directly. keep in mind that the class is not magic and will lose track of the message headers if you manipulate them without referencing the message set. accessing synthetic messages and headers synmessages [attribute] the js list of syntheticmessages held in the set. while you should not modify this list, you can get its length and read from it. getmsghdr(aindex) [function] retrieve the nsimsgdbhdr at the give...
Midas
an editable document. examples this example shows the basic structure described in the notes section : <html> <head> <title>simple edit box</title> </head> <body> <iframe id="midasform" src="about:blank" onload="this.contentdocument.designmode='on';" ></iframe> </body> </html> methods document.execcommand executes the given command. ...
... <title>simple edit box</title> </head> <body> <iframe id="midasform" src="about:blank" onload="this.contentdocument.designmode='on';" ></iframe> </body> </html> methods document.execcommand executes the given command. document.querycommandenabled determines whether the given command can be executed on the document in its current state. document.querycommandindeterm determines whether the current selection is in an indetermined state. document.querycommandstate determines whether the given command has been executed on the current selection. document.querycommandvalue determines the current value of the document, range, or current selection for the given command. supported commands command value description backcolor a color code. ...
Creating a Cookie Log
linux start a command shell (these instructions are for bash, if you use something else, you probably know how to modify these instructions already). change to the installation directory for firefox. type "export nspr_log_file=~/cookie-log.txt" and press enter. type "export nspr_log_modules=cookie:4" and press enter. run firefox by typing "./firefox" and pressing enter mac os x open terminal.app, which is located in the /applications/utilities folder (these instructions are for bash, the default shell in mac os x 10.3 and higher; if you use something else, you probably know how to modify these instructions already). change to the installation directory for firefox, e.g. type "cd /applications/firefox.app/contents/macos" and press return. type "export nspr_log_file=~/desktop/coo...
...and press return. run firefox by typing "./firefox-bin" and pressing return (note that firefox will launch behind windows for other applications). 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. once you have reproduced the bug, shut down firefox. close out of the command prompt/shell/terminal, and then launch firefox normally. finally, attach the cookie-log.txt file to the bug where it was requested (by clicking on create new attachment). it should be in c:\temp on windows, your home directory on linux, or the desktop on mac os x. thanks for helping us make firefox better! original document information author(s): mike connor last updated date: december 4, 2004 copyright info...
I/O Functions
that act on file descriptors directory i/o functions socket manipulation functions converting between host and network addresses memory-mapped i/o functions anonymous pipe function polling functions pollable events manipulating layers functions that operate on pathnames a file or directory in a file system is specified by its pathname. nspr uses unix-style pathnames, which are null-terminated character strings. only the ascii character set is supported. the forward slash (/) separates the directories in a pathname. nspr converts the slashes in a pathname to the directory separator of the native os--for example, backslash (\) on windows and colon (:) on mac os--before passing it to the native system calls. some file systems also differentiate drives or volumes. pr_open pr_dele...
...differences include the following: the blocking socket functions in nspr take a timeout parameter. two new functions, pr_transmitfile and pr_acceptread, can exploit the new system calls of some operating systems for higher performance. list of functions: pr_openudpsocket pr_newudpsocket pr_opentcpso...
Named Shared Memory
finished. pr_detachsharedmemory should be called to unmap the shared memory segment from the application's address space. pr_closesharedmemory should be called when no further use of the prsharedmemory object is required within a process. following a call to pr_closesharedmemory, the prsharedmemory object is invalid and cannot be reused. pr_deletesharedmemory should be called before process termination. after you call pr_deletesharedmemory, any further use of the shared memory associated with the name may cause unpredictable results. filenames the name passed to pr_opensharedmemory should be a valid filename for a unix platform. pr_opensharedmemory creates file using the name passed in. some platforms may mangle the name before creating the file and the shared memory. the unix implementa...
...y use sysv ipc shared memory, posix shared memory, or memory mapped files; the filename may be used to define the namespace. on windows, the name is significant, but there is no file associated with the name. no assumptions about the persistence of data in the named file should be made. depending on platform, the shared memory may be mapped onto system paging space and be discarded at process termination. all names provided to pr_opensharedmemory should be valid filename syntax or name syntax for shared memory for the target platform. referenced directories should have permissions appropriate for writing. limits on shared memory resources different platforms have limits on both the number and size of shared memory resources. the default system limits on some platforms may be smaller than ...
PRHostEnt
lude <prnetdb.h> typedef struct prhostent { char *h_name; char **h_aliases; #if defined(_win32) print16 h_addrtype; print16 h_length; #else print32 h_addrtype; print32 h_length; #endif char **h_addr_list; } prhostent; fields the structure has the following fields: h_name pointer to the official name of host. h_aliases pointer to a pointer to list of aliases. the list is terminated with a null entry. h_addrtype host address type. for valid nspr usage, this field must have a value indicating either an ipv4 or an ipv6 address. h_length length of internal representation of the address in bytes. all of the addresses in the list are of the same type and therefore of the same length. h_addr_list pointer to a pointer to a list of addresses from name server (in network by...
..._addrtype host address type. for valid nspr usage, this field must have a value indicating either an ipv4 or an ipv6 address. h_length length of internal representation of the address in bytes. all of the addresses in the list are of the same type and therefore of the same length. h_addr_list pointer to a pointer to a list of addresses from name server (in network byte order). the list is terminated with a null entry. description this structure is used by many of the network address functions. all addresses are passed in host order and returned in network order (suitable for use in system calls). use the network address functions to manipulate the prhostent structure. to make the transition to ip version 6 easier, it's best to treat prhostent as an opaque structure. note winsock.h ...
PRIntervalTime
a platform-dependent type that represents a monotonically increasing integer--the nspr runtime clock. syntax #include <prinrval.h> typedef pruint32 printervaltime; #define pr_interval_min 1000ul #define pr_interval_max 100000ul #define pr_interval_no_wait 0ul #define pr_interval_no_timeout 0xfffffffful description the units of printervaltime are platform-dependent. they are chosen to be appropriate for the host os, yet provide sufficient resolution and period to be useful to clients. the increasing interval value represented by printervaltime wraps. ...
...ey are chosen to be appropriate for the host os, yet provide sufficient resolution and period to be useful to clients. the increasing interval value represented by printervaltime wraps. it should therefore never be used for intervals greater than approximately 6 hours. interval times are accurate regardless of host processing requirements and are very cheap to acquire. the constants pr_interval_min and pr_interval_max define a range in ticks per second. these constants bound both the period and the resolution of a printervaltime object. the reserved constants pr_interval_no_wait and pr_interval_no_timeout have special meaning for nspr. they indicate that the process should wait no time (return immediately) or wait forever (never time out), respectively. important note the counters used f...
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. this macro compiles to nothing if compile-time options are not specified to enable logging. ...
...the macro converts the expression to a string and passes it to pr_assert, using file and line parameters from the compile-time environment. this macro compiles to nothing if compile-time options are not specified to enable logging. ...
PR_CreateThread
rity, prthreadscope scope, prthreadstate state, pruint32 stacksize); parameters pr_createthread has the following parameters: type specifies that the thread is either a user thread (pr_user_thread) or a system thread (pr_system_thread). start a pointer to the thread's root function, which is called as the root of the new thread. returning from this function is the only way to terminate a thread. arg a pointer to the root function's only parameter. nspr does not assess the type or the validity of the value passed in this parameter. priority the initial priority of the newly created thread. scope specifies your preference for making the thread local (pr_local_thread), global (pr_global_thread) or global bound (pr_global_bound_thread). however, nspr may override this pref...
... ...
PR_Initialize
he sequence of operations, pr_initialize implicitly calls pr_cleanup on exiting the primordial function. syntax #include <prinit.h> printn pr_initialize( prprimordialfn prmain, printn argc, char **argv, pruintn maxptds); parameters pr_initialize has the following parameters: prmain the function that becomes the primordial thread's root function. returning from prmain leads to termination of the process. argc the length of the argument vector, whether passed in from the host's program-launching facility or fabricated by the actual main program. this approach conforms to standard c programming practice. argv the base address of an array of strings that compromise the program's argument vector. this approach conforms to standard c programming practice. maxptds this parame...
...oot function, prmain. description pr_initialize initializes the nspr runtime and places nspr between the caller and the runtime library. this allows main to be treated like any other function, signaling its completion by returning and allowing the runtime to coordinate the completion of the other threads of the runtime. pr_initialize does not return to its caller until all user threads have terminated. the priority of the main (or primordial) thread is pr_priority_normal. the thread may adjust its own priority by using pr_setthreadpriority. ...
PR_NOT_REACHED
this macro compiles to nothing if compile-time options are not specified to enable logging. ...
...th a message to the log. syntax #include <prlog.h> void pr_not_reached(const char *_reasonstr); parameters the macro has this parameter: reasonstr a string that describes why you should not have reached this statement. returns nothing description this macro writes the specified reason string to the log and terminates the application. this macro compiles to nothing if compile-time options are not specified to enable logging. ...
PR_TicksPerSecond
the relationship between a printervaltime tick and standard clock units is platform-dependent. pr_pr_tickspersecond() allows you to discover exactly what that relationship is. ...
...ne the value of printervaltime. syntax #include <prinrval.h> pruint32 pr_tickspersecond(void); returns an integer between 1000 and 100000 indicating the number of ticks per second counted by printervaltime on the current platform. this value is platform-dependent and does not change after nspr is initialized. description the value returned by pr_tickspersecond() lies between pr_interval_min and pr_interval_max. the relationship between a printervaltime tick and standard clock units is platform-dependent. pr_pr_tickspersecond() allows you to discover exactly what that relationship is. seconds per tick (the inverse of pr_pr_tickspersecond()) is always between 10 microseconds and 1 millisecond. ...
PR_WaitCondVar
ck, possibly causing a rescheduling within the runtime, then immediately attempt to reacquire the lock and resume. returns the function returns one of the following values: if successful, pr_success. if unsuccessful (for example, if the caller has not locked the lock associated with the condition variable or the thread was interrupted with pr_interrupt), pr_failure. the details can be determined with pr_geterror. description before the call to pr_waitcondvar, the lock associated with the condition variable must be held by the calling thread. after a call to pr_waitcondvar, the lock is released and the thread is blocked in a "waiting on condition" state until another thread notifies the condition or a caller-specified amount of time expires. when the condition variable is notified, ...
...om the "waiting on condition" state to the "ready" state. when scheduled, the thread attempts to reacquire the lock that it held when pr_waitcondvar was called. any value other than pr_interval_no_timeout or pr_interval_no_wait for the timeout parameter will cause the thread to be rescheduled due to either explicit notification or the expiration of the specified interval. the latter must be determined by treating time as one part of the monitored data being protected by the lock and tested explicitly for an expired interval. to detect the expiration of the specified interval, call pr_intervalnow before and after the call to pr_waitcondvar and compare the elapsed time with the specified interval. ...
Threads
a thread has a limited number of resources that it truly owns. these resources include a stack and the cpu registers (including pc). to an nspr client, a thread is represented by a pointer to an opaque structure of type prthread. a thread is created by an explicit client request and remains a valid, independent execution entity until it returns from its root function or the process abnormally terminates. threads are critical resources and therefore require some management. to synchronize the termination of a thread, you can join it with another thread (see pr_jointhread). joining a thread provides definitive proof that the target thread has terminated and has finished with both the resources to which the thread has access and the resources of the thread itself. for an overview of the nspr t...
...read is valid. the effects of these functions on invalid threads are undefined. creating, joining, and identifying threads controlling thread priorities interrupting and yielding setting global thread concurrency getting a thread's scope creating, joining, and identifying threads pr_createthread creates a new thread. pr_jointhread blocks the calling thread until a specified thread terminates. pr_getcurrentthread returns the current thread object for the currently running code. pr_attachthread associates a prthread object with an existing native thread. pr_detachthread disassociates a prthread object from a native thread. controlling thread priorities for an overview of the way nspr controls thread priorities, see setting thread priorities. you set a thread's nspr prior...
NSPR API Reference
introduction to nspr nspr naming conventions nspr threads thread scheduling setting thread priorities preempting threads interrupting threads nspr thread synchronization locks and monitors condition variables nspr sample code nspr types calling convention types algebraic types 8-, 16-, and 32-bit integer types signed integers unsigned integers 64-bit integer types floating-point integer type native os integer types miscellaneous types size type pointer difference types boolean types status type for return values threads threading types and constants threading functions creating, joining, and identifying threads controlling thread priorities cont...
...escriptors directory i/o functions socket manipulation functions converting between host and network addresses memory-mapped i/o functions anonymous pipe function polling functions pollable events manipulating layers network addresses network address types and constants network address functions atomic operations pr_atomicincrement pr_atomicdecrement pr_atomicset interval timing interval time type and constants interval functions date and time types and constants time parameter callback functions functions memory management operations memory allocation functions memory allocation macros string operations pl_strlen pl_strcpy pl_strdup pl_strfree floating point number to string conversion pr_strtod pr_dtoa pr_cnvtf long long (64-bit) inte...
NSPR release process
kage.sh, prinit.h, and vercheck.c. look at their cvs histories for examples. make a dummy change (add or remove a blank line) to mozilla/nsprpub/config/prdepend.h. make sure the nss tinderboxes (which also build and test nspr) are all green. the build+test cycles of the nss tinderboxes are very long, so you usually need to wait half a day for them to cycle through. create a beta cvs tag. ...
... upload a source tar file to https://ftp.mozilla.org/pub/mozilla....nspr/releases/ write the release notes. announce the release in the mozilla nspr newsgroup. ...
NSS 3.20 release notes
introduction the nss team has released network security services (nss) 3.20, which is a minor release. distribution information the hg tag is nss_3_20_rtm. nss 3.20 requires nspr 4.10.8 or newer. nss 3.20 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_20_rtm/src/ new in nss 3.20 new functionality the tls library has been extended to support dhe ciphersuites in server applications. new functions in ssl.h ssl_dhegroupprefset - configure the set of allowed/enabled dhe group parameters that can be used by nss for a server socket. ...
...m/src/ new in nss 3.20 new functionality the tls library has been extended to support dhe ciphersuites in server applications. new functions in ssl.h ssl_dhegroupprefset - configure the set of allowed/enabled dhe group parameters that can be used by nss for a server socket. ssl_enableweakdheprimegroup - enable the use of weak dhe group parameters that are smaller than default minimum size of the library. new types in sslt.h ssldhegrouptype - enumerates the set of dhe parameters embedded in nss that can be used with function ssl_dhegroupprefset new macros in ssl.h ssl_enable_server_dhe - a socket option user to enable or disable dhe ciphersuites for a server socket notable changes in nss 3.20 the tls library has been extended to ...
NSS 3.23 release notes
distribution information the hg tag is nss_3_23_rtm. nss 3.23 requires nspr 4.12 or newer. nss 3.23 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_23_rtm/src/ new in nss 3.23 new functionality chacha20/poly1305 cipher and tls cipher suites now supported (bug 917571, bug 1227905) experimental-only support tls 1.3 1-rtt mode (draft-11). this code is not ready for production use. ...
...zlib (bug 1243872). the build time environment variable nss_disable_chachapoly was added, which can be used to prevent compilation of the chacha20/poly1305 code. ...
NSS 3.24 release notes
distribution information the hg tag is nss_3_24_rtm. nss 3.24 requires netscape portable runtime (nspr) 4.12 or newer. nss 3.24 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_24_rtm/src/ new in nss 3.24 nss 3.24 includes two nss softoken updates, a new function to configure ssl/tls server sockets, and two functions to improve the use of temporary arenas. ...
...m level 1 to level 2 (by setting an appropriate password), but not the reverse. a ssl_configservercert function has been added for configuring ssl/tls server sockets with a certificate and private key. use this new function in place of ssl_configsecureserver, ssl_configsecureserverwithcertchain, ssl_setstapledocspresponses, and ssl_setsignedcerttimestamps. ssl_configservercert automatically determines the certificate type from the certificate and private key. the caller is no longer required to use sslkeatype explicitly to select a "slot" into which the certificate is configured (which incorrectly identifies a key agreement type rather than a certificate). separate functions for configuring online certificate status protocol (ocsp) responses or signed certificate timestamps are not needed, s...
NSS 3.32 release notes
the code signing trust bit was turned off for all, included root certificates. the websites (tls/ssl) trust bit was turned off for the following root certificates. ...
... the code signing trust bit was turned off for all, included root certificates. the websites (tls/ssl) trust bit was turned off for the following root certificates. ...
NSS 3.33 release notes
distribution information the hg tag is nss_3_33_rtm. nss 3.33 requires netscape portable runtime (nspr) 4.17, or newer. nss 3.33 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_33_rtm/src/ notable changes in nss 3.33 tls compression is no longer supported. api calls that attempt to enable compression are accepted without failure. however, tls compression will remain disabled. ...
...re. however, tls compression will remain disabled. this version of nss uses a formally verified implementation of curve25519 on 64-bit systems. the compile time flag disable_ecc has been removed. when nss is compiled without nss_force_fips=1 startup checks are no longer performed. fixes cve-2017-7805, a potential use-after-free in tls 1.2 server, when verifying client authentication. various minor improvements and correctness fixes. 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...
NSS 3.46 release notes
the nss team would like to recognize first-time contributors: giulio benetti louis dassy mike kaganski xhimanshuz distribution information the hg tag is nss_3_46_rtm. nss 3.46 requires nspr 4.22 or newer. nss 3.46 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_46_rtm/src/ other releases are available in nss releases. ...
... see bug 1573118 for details. tls extended master secret will be enabled by default, where possible. see bug 1575411 for details. bugs fixed in nss 3.46 bug 1572164 - don't unn...
NSS 3.51 release notes
the nss team would like to recognize first-time contributors: dmitry baryshkov victor tapia distribution information the hg tag is nss_3_51_rtm. nss 3.51 requires nspr 4.25 or newer. nss 3.51 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_51_rtm/src/ other releases are available in nss releases. notable changes in nss 3.51 updated dtls 1.3 implementation to draft-34. see bug 1608892 for details. ...
...- complete integration of wycheproof ecdh test cases bug 1614183 - check if ppc __has_include(<sys/auxv.h>) bug 1614786 - fix a compilation error for ‘getfipsenv’ "defined but not used" bug 1615208 - send dtls version numbers in dtls 1.3 supported_versions extension to avoid an incompatibility. ...
NSS 3.55 release notes
the nss team would like to recognize first-time contributors: danh distribution information the hg tag is nss_3_55_rtm. nss 3.55 requires nspr 4.27 or newer. nss 3.55 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_55_rtm/src/ other releases are available in nss releases. notable changes in nss 3.55 p384 and p521 elliptic curve implementations are replaced with verifiable implementations from fiat-crypto and ecckiila. ...
...ndcertinslot to search a given slot for a der-encoded certificate. bug 1651520 - fix slotlock race in nsc_gettokeninfo. bug 1647752 - update dtls 1.3 implementation to draft-38. bug 1649190 - run cipher, sdr, and ocsp tests under standard test cycle in ci. bug 1649226 - add wycheproof ecdsa tests. bug 1637222 - consistently enforce iv requirements for des and 3des. bug 1067214 - enforce minimum pkcs#1 v1.5 padding length in rsa_checksignrecover. bug 1643528 - fix compilation error with -werror=strict-prototypes. bug 1646324 - advertise pkcs#1 schemes for certificates in the signature_algorithms extension. bug 1652331 - update nss 3.55 nspr version to 4.27. this bugzilla query returns all the bugs fixed in nss 3.55: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixe...
NSS Config Options
licy explicitly: config="allow=curve1:curve2:hash1:hash2:rsa-1024..." only the specified hashes and curves will be allowed: config="disallow=all allow=sha1:sha256:secp256r1:secp384r1" only the specified hashes and curves will be allowed, and rsa keys of 2048 or more will be accepted, and dh key exchange with 1024-bit primes or more: config="disallow=all allow=sha1:sha256:secp256r1:secp384r1:min-rsa=2048:min-dh=1024" a policy that enables the aes ciphersuites and the secp256/384 curves: config="allow=aes128-cbc:aes128-gcm::hmac-sha1:sha1:sha256:sha384:rsa:ecdhe-rsa:secp256r1:secp384r1" turn off md5 config="disallow=md5" turn off md5 and sha1 only for ssl config="disallow=md5(ssl):sha1(ssl)" disallow values are parsed first, and then allow values, independent of the order in which ...
...a384 hmac-sha512 hmac-md5 ciphers aes128-cbc aes192-cbc aes256-cbc aes128-gcm aes192-gcm aes256-gcm camellia128-cbc camellia192-cbc camellia256-cbc seed-cbc des-ede3-cbc des-40-cbc des-cbc null-cipher rc2 rc4 idea ssl key exchanges rsa rsa-export dhe-rsa dhe-dss dh-rsa dh-dss ecdhe-ecdsa ecdhe-rsa ecdh-ecdsa ecdh-rsa restrictions for asymmetric keys (integers) rsa-min dh-min dsa-min constraints on ssl protocols versions (integers) tls-version-min tls-version-max constraints on dtls protocols versions (integers) dtls-version-min dtls-version-max policy flags for algorithms ssl ssl-key-exchange key-exchange cert-signature signature all none ...
NSS Sample Code Sample_2_Initialization of NSS
ot, prbool retry, void *arg) { file *input; file *output; char *p0 = null; char *p1 = null; secupwdata *pwdata = (secupwdata *) arg; if (pwdata->source == pw_fromfile) { return filepasswd(slot, retry, pwdata->data); } if (pwdata->source == pw_plaintext) { return pl_strdup(pwdata->data); } /* open terminal */ input = fopen("/dev/tty", "r"); if (input == null) { pr_fprintf(pr_stderr, "error opening input terminal for read\n"); return null; } /* we have no password, so initialize database with one */ pr_fprintf(pr_stderr, "enter a password which will be used to encrypt your keys.\n" "the password should be at least 8 characters long,\n" "and should...
...e have no password, so initialize database with one */ pr_fprintf(pr_stderr, "enter a password which will be used to encrypt your keys.\n" "the password should be at least 8 characters long,\n" "and should contain at least one non-alphabetic character.\n\n"); output = fopen("/dev/tty", "w"); if (output == null) { pr_fprintf(pr_stderr, "error opening output terminal for write\n"); return null; } for (;;) { if (p0) port_free(p0); p0 = getpassword(input, output, "enter new password: ", checkpassword); if (p1) port_free(p1); p1 = getpassword(input, output, "re-enter password: ", checkpassword); ...
Initialize NSS database - sample 2
ot, prbool retry, void *arg) { file *input; file *output; char *p0 = null; char *p1 = null; secupwdata *pwdata = (secupwdata *) arg; if (pwdata->source == pw_fromfile) { return filepasswd(slot, retry, pwdata->data); } if (pwdata->source == pw_plaintext) { return pl_strdup(pwdata->data); } /* open terminal */ input = fopen("/dev/tty", "r"); if (input == null) { pr_fprintf(pr_stderr, "error opening input terminal for read\n"); return null; } /* we have no password, so initialize database with one */ pr_fprintf(pr_stderr, "enter a password which will be used to encrypt your keys.\n" "the password should be at least 8 characters long,\n" "and should...
...e have no password, so initialize database with one */ pr_fprintf(pr_stderr, "enter a password which will be used to encrypt your keys.\n" "the password should be at least 8 characters long,\n" "and should contain at least one non-alphabetic character.\n\n"); output = fopen("/dev/tty", "w"); if (output == null) { pr_fprintf(pr_stderr, "error opening output terminal for write\n"); return null; } for (;;) { if (p0) port_free(p0); p0 = getpassword(input, output, "enter new password: ", checkpassword); if (p1) port_free(p1); p1 = getpassword(input, output, "re-enter password: ", checkpassword); ...
nss tech note3
... used by an ocsp responder certusageverifyca ............ a ca of any kind. each cert has a "type" and a "key usage", each of which may contain one or more valid values. each of the above seccertusages translates into a required set of cert type and key usage for the certificate itself, and into another set of required cert type and key usage for all the ca certs in the cert chain. to determine if a cert is valid for a given cert usage, it must have the the cert type and key usage required for that cert usage, and all the ca certs in the cert chain must have the cert type and key usage required for ca certs for that cert usage. there are 8 key usages: cert_sign crl_sign data_encipherment digital_signature govt_approved key_agreement key_encipherment non_repudiation there are...
...respond directly to the cert types named above. the oid for this extension is { 2 16 840 1 113730 1 1 } encoded in hex as 0x60, 0x86, 0x48, 0x01, 0x86, 0xf8, 0x42, 0x01, 0x01 in addition to netscape's own cert type extension, nss recognizes various x.509 extensions. the x.509 key usage extension has oid { 2 5 29 0f } encoded in hex as 0x55, 0x1d, 0x0f. if present, this extension directly determines the values of the 8 key usages defined above. if absent, the cert is assumed to be valid for all key usages. the x.509v3 extended key usage extension as oid { 2 5 29 37 } encoded in hex as 0x55, 0x1d, 0x25. that extension contains a sequence of oids, each of which signifies one or more cert types, depending on the presence or absence of of the true basic constraints extension; that is, the i...
FC_GetTokenInfo
nfo has two parameters: slotid the id of the token's slot pinfo points to a ck_token_info structure description fc_gettokeninfo returns information about the token in the specified slot. on return, the ck_token_info structure that pinfo points to has the following information: label: the label of the token, assigned during token initialization, padded with spaces to 32 bytes and not null-terminated. manufacturerid: id of the device manufacturer, "mozilla foundation", padded with spaces to 32 characters and not null-terminated. model: model of the device, "nss 3", padded with spaces to 16 characters and not null-terminated. serialnumber: the device's serial number as a string, "0000000000000000", 16 characters and not null-terminated. flags: bit flags indicating capabilities and stat...
.... if login is required (which is true for the fips mode of operation), this flag means the user's password has been initialized. ulsessioncount: number of sessions that this application currently has open with the token ulrwsessioncount: number of read/write sessions that this application currently has open with the token hardwareversion: hardware version number, for example, 8.3 (major=0x08, minor=0x03), which are the version numbers of the certificate and key databases, respectively. firmwareversion: firmware version number, 0.0 (major=0x00, minor=0x00). a user may call fc_gettokeninfo without logging into the token (to assume the nss user role). return value ckr_ok token information was successfully copied. ckr_cryptoki_not_initialized the pkcs #11 module library is not initi...
NSS functions
pk11_getinternalkeyslot mxr 3.2 and later pk11_getinternalslot mxr 3.2 and later pk11_getkeygen mxr 3.4 and later pk11_getkeylength mxr 3.2 and later pk11_getkeystrength mxr 3.2 and later pk11_getmechanism mxr 3.2 and later pk11_getminimumpwdlength mxr 3.4 and later pk11_getmodinfo mxr 3.6 and later pk11_getmodule mxr 3.3 and later pk11_getmoduleid mxr 3.2 and later pk11_getnextgenericobject mxr 3.9.2 and later pk11_getnextsafe mxr 3.4 and later pk11_getnextsymke...
... 3.2 and later sec_asn1encode mxr 3.2 and later sec_asn1encodeinteger mxr 3.2 and later sec_asn1encodeitem mxr 3.2 and later sec_asn1encoderabort mxr 3.9 and later sec_asn1encoderclearnotifyproc mxr 3.2 and later sec_asn1encoderclearstreaming mxr 3.2 and later sec_asn1encodercleartakefrombuf mxr 3.2 and later sec_asn1encoderfinish mxr 3.2 and later sec_asn1encodersetnotifyproc mxr 3.2 and later sec_asn1encodersetstreaming mxr 3.2 and later sec_asn1encodersettakefrombuf mxr 3.2 and lat...
pkfnc.html
ccessful, returns null. many tokens keep track of the number of attempts to enter a password and do not allow further attempts after a certain point. therefore, if the retry argument is pr_true, indicating that the password was tried and is wrong, the callback function should return null to indicate that it is unsuccessful, rather than attempting to return the same password again. failing to terminate when the retry argument is pr_true can result in an endless loop. several functions in the nss libraries use the password callback function to obtain the password before performing operations that involve the protected information. the third parameter to the password callback function is application-defined and can be used for any purpose. for example, communicator uses the parameter to pass ...
...tected information. the third parameter to the password callback function is application-defined and can be used for any purpose. for example, communicator uses the parameter to pass information about which window is associated with the modal dialog box requesting the password from the user. when nss libraries call the password callback function, the value they pass in the third parameter is determined by ssl_setpkcs11pinarg. see also for examples of password callback functions, see the samples in the samples directory. ...
sslcrt.html
t the time to check against the certificate's validity period. for more information, see the nspr header pr_time.h. returns the function returns an enumerator of type seccerttimevalidity: typedef enum { seccerttimevalid, seccerttimeexpired, seccerttimenotvalidyet } seccerttimevalidity; nss_cmpcertchainwcanames determines whether any of the signers in the certificate chain for a specified certificate are on a specified list of ca names. syntax #include <nss.h> secstatus nss_cmpcertchainwcanames( certcertificate *cert, certdistnames *canames); parameters this function has the following parameters: cert a pointer to the certificate structure for the cert...
...ames a pointer to the certcertnicknames structure to be freed. cert_getdefaultcertdb returns a handle to the default certificate database. syntax #include <cert.h> certcertdbhandle *cert_getdefaultcertdb(void); returns the function returns the certcertdbhandle for the default certificate database. description this function is useful for determining whether the default certificate database has been opened. nss_findcertkeatype returns key exchange type of the keys in an ssl server certificate. syntax #include <nss.h> sslkeatype nss_findcertkeatype(certcertificate * cert); parameter this function has the following parameter: a the certificate to check. returns ...
NSS Tools
g the nss source, see https://developer.mozilla.org/nss/building. if you have feedback or questions, please feel free to post to mozilla.dev.tech.crypto. this newsgroup is the preferred forum for all questions about nss and nss tools. overall objectives provide a tool for analyzing and repairing certificate databases (dbck). migrate tools from secutil.h interface to pkcs #11 interface. eliminate redundant functionality in tools. many tools implement private versions of pkcs11init(), opencertdb(), etc. eliminate use of getopt() and replace with nspr calls to get command options (to eliminate platform dependencies with getopt()). tools information tool description links certutil 2.0 manage certificate and key databases (cert7.db and key3.db). source, do...
...display the contents of the messages exchanged between the client and server. the ssltap tool does not decrypt data, but it shows things like the type of ssl message (clienthello, serverhello, etc) and connection data (protocol version, cipher suite, etc). this tool is very useful for debugging. source, documentation currently points to the netscape certificate management system administration guide on docs.sun.com. for additional information about this tool, see object signing. currently points to the signver documentation on developer.netscape.com. for additional information about this tool, see form signing ...
NSS Tools ssltap
the ssl debugging tool is an ssl-aware command-line proxy. it watches tcp connections and displays the data going by. if a connection is ssl, the data display includes interpreted ssl records and handshaking. availability this tool is known to build on solaris 2.5.1 (sunos 5.5.1) and windows nt 4.0. description the ssltap command opens a socket on a rendezvous port and waits for an incoming connection from the client side. once this connection arrives, the tool makes another connection to the specified host name and port on the server side. it passes any data sent by the client to the server and vice versa. the tool also displays the data to the shell window from which it was called. it can do this for plain http connections or any tcp protocol, as well as for ssl streams, as descr...
...lthough you can run the tool at its most basic by issuing the ssltap command with no options other than hostname:port, the information you get in this way is not very useful. for example, assume your development machine is called intercept. the simplest way to use the debugging tool is to execute the following command from a command shell: ssltap www.netscape.com:80 the program waits for an incoming connection on the default port 1924. in your browser window, enter the url http://intercept:1924. the browser retrieves the requested page from the server at www.netscape.com, but the page is intercepted and passed on to the browser by the debugging tool on intercept. on its way to the browser, the data is printed to the command shell from which you issued the command. data sent from the clien...
NSS tools : signtool
gning certificate is a special kind of certificate that allows you to associate your digital signature with one or more files. an individual file can potentially be signed with multiple digital signatures. for example, a commercial software developer might sign the files that constitute a software product to prove that the files are indeed from a particular company. a network administrator manager might sign the same files with an additional digital signature based on a company-generated certificate to indicate that the product is approved for use within the company. the significance of a digital signature is comparable to the significance of a handwritten signature. once you have signed a file, it is difficult to claim later that you didn't sign it. in s...
...n't sign it. in some situations, a digital signature may be considered as legally binding as a handwritten signature. therefore, you should take great care to ensure that you can stand behind any file you sign and distribute. for example, if you are a software developer, you should test your code to make sure it is virus-free before signing it. similarly, if you are a network administrator, you should make sure, before signing any code, that it comes from a reliable source and will run correctly with the software installed on the machines to which you are distributing it. before you can use netscape signing tool to sign files, you must have an object-signing certificate, which is a special certificate whose associated private key is used to create digital si...
Proxies in Necko
http protocol handler or the protocol handler for the requested uri for a new channel with the nsiproxyinfo - if the channel supports nsiproxiedprotocolhandler. otherwise, the proxy info is discarded. nsiprotocolproxyservice the most important function on nsiprotocolproxyservice is resolve. it checks whether the passed-in uri should use a proxy, and returns an nsiproxyinfo if so. ...
...note that the proxy method is only used when the protocol handler supports http proxies, as indicated by its protocol flags. finally, depending on the protocol, the proxy info will be created with the appropriate type, host and port. socks and nsisockettransportservice the aforementioned methods work very well for application-level proxies. ...
Rhino scopes and contexts
. with dynamic scope, functions look at the top-level scope of the currently executed script rather than their lexical scope. so we can store information that varies across scopes in the instance scope yet still share functions that manipulate that information reside in the shared scope. the dynamicscopes example illustrates all the points discussed above. ...
...ared scope. the dynamicscopes example illustrates all the points discussed above. more on scopes the key things to determine in setting up scopes for your application are what scope should global variables be created in when your script executes an assignment to an undefined variable, and what variables should your script have access to when it references a variable? the answer to 1 determines which scope should be the ultimate parent scope: rhino follows the parent chain up to the top and places the variable there. after you've constructed your parent scope chain, the answer to question 2 may indicate that there are additional scopes that need to be searched that are not in your parent scope chain. you can add these as prototypes of scopes in your parent scope chain. when rhino look...
GC Rooting Guide
-- and then arrange for it to be called during tracing. if a pointer to your structure is stored in the private field of a jsobject, the usual way would be to define a trace hook on the jsobject (see above) that casts the private pointer to your structure and invokes trace() on it: class myobject : public jsobject { { ... ...
...f a pointer to your structure is stored in the private field of a jsobject, the usual way would be to define a trace hook on the jsobject (see above) that casts the private pointer to your structure and invokes trace() on it: class myobject : public jsobject { { ... ...
How to embed the JavaScript engine
compile the helloworld application and link to the spidermonkey library. run the helloworld executable at the command line: ./helloworld how to call c functions from javascript say the c function is named doit and it would like at least two actual parameters when called (if the caller supplies fewer, the js engine should ensure that undefined is passed for the missing ones): #define doit_minargs 2 // [spidermonkey 24] use jsbool instead of bool. static bool doit(jscontext *cx, unsigned argc, jsval *vp) { js::callargs args = callargsfromvp(argc, vp); /* * look in argv for argc actual parameters, set *rval to return a * value to the caller. * * ex. add two arguments as integer. * args.rval().setint32(args[0].toint32() + args[1].toint32()); */ return true; } t...
... argc, jsval *vp) { js::callargs args = callargsfromvp(argc, vp); /* * look in argv for argc actual parameters, set *rval to return a * value to the caller. * * ex. add two arguments as integer. * args.rval().setint32(args[0].toint32() + args[1].toint32()); */ return true; } then to wire it up to js, you could write: ok = js_definefunction(cx, global, "doit", doit, doit_minargs, 0); or, if you had a bunch of native functions to define, you would probably put them in a table: static jsfunctionspec my_functions[] = { js_fn("doit", doit, doit_minargs, 0), /* etc... */ js_fs_end }; js_fs_end terminates the table. and say: ok = js_definefunctions(cx, global, my_functions); how to call javascript functions from c first, create arguments for the call, here i...
SpiderMonkey Internals
string expression for // the sum of the divisors of i, excluding i itself. var sumofdivisors = new exprarray(n + 1, 1); for (var divisor = 2; divisor <= n; divisor++) { for (var j = divisor + divisor; j <= n; j += divisor) { sumofdivisors[j] += " + " + divisor; } // at this point everything up to 'divisor' has its sumofdivisors // expression calculated, so we can determine whether it's perfect // already by evaluating. 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 =...
... macros that amortize malloc costs and allow for en-masse freeing. see the paper mentioned in jsarena.h's major comment. jsgc.cpp, jsgc.h the garbage collector and tracing routines. jsinterp.*, jscntxt.*, jsinvoke.cpp the bytecode interpreter, and related functions such as call and allocstack, live in jsinterp.cpp. the jscontext constructor and destructor are factored out into jscntxt.cpp for minimal linking when the compiler part of js is split from the interpreter part into a separate program. jsinvoke.cpp is a build hack used on some platforms to build js_interpret under different compiler options from the rest of jsinterp.cpp. jsemit.*, jsopcode.tbl, jsopcode.*, jsparse.*, jsscan.*, jsscript.* compiler and decompiler modules. the jsopcode.tbl file is a c preprocessor source that de...
JS_DecompileFunctionBody
generate the source code representing the body of a function, minus the function keyword, name, parameters, and braces. syntax jsstring * js_decompilefunctionbody(jscontext *cx, js::handle<jsfunction*> fun, unsigned indent); name type description cx jscontext * the context in which to decompile the function. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. fun js::handle&lt;jsfunction*&gt; the function to decompile. indent unsigned if it's not js_dont_pretty_print, js_decompilefunction returns pretty printed source code of the function. ...
...requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. fun js::handle&lt;jsfunction*&gt; the function to decompile. indent unsigned if it's not js_dont_pretty_print, js_decompilefunction returns pretty printed source code of the function. description js_decompilefunctionbody generates the source code of a function's body, minus the function keyword, name, parameters, and braces, from a function's compiled form, fun. if successful, js_decompilefunctionbody returns a string containing the source code of the function body. otherwise, it returns null. the source code generated by this function is accurate but unadorned and is not suitable for recompilation without providing the function's declaration. if you decompile a f...
JS_DefineProperty
threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject the object on which to create the new property. name or id const char * or const char16_t *or js::handleid the name of the new property. namelen size_t (only in js_defineucproperty) the length of name, in characters; or (size_t) -1 to indicate that name is null-terminated. value js::handlevalue or js::handleobject or js::handlestring or int32_t or uint32_t or double initial stored value for the new property. getter jsnative the property getter callback, which the javascript engine will call each time the property's value is accessed; or null. setter jsnative the property setter callback, which the javascript engine ...
... the property is read or written, whether from javascript code or via jsapi functions like js_getproperty and js_setproperty. (exception: if attrs contains the jsprop_readonly flag, the setter will never be called, as property assignment will fail before it gets that far. also note that certain jsapi functions, including js_lookupproperty, js_hasproperty, and property_attributes, can detect or examine a property without calling its getter.) if getter (or setter) is null, the new property will use the jsclass.getproperty (or jsclass.setproperty) callback from obj's class. if attrs contains the jsprop_getter (or jsprop_setter) flag, then getter (or setter) must point to a javascript function, not a c/c++ function. that is, it must be a jsobject * that points to a javascript function, cast to t...
JS_EncodeCharacters
, converting the 16-bit values to 8-bit values. if spidermonkey was built with js_c_strings_are_utf8 defined or js_setcstringsareutf8 was called, the string is converted to utf-8. otherwise each character is simply truncated to 8 bits. if utf-8 is turned on, the length of the encoded string may vary. to calculate the number of bytes needed, call js_encodecharacters twice, like this: /* determine how many bytes to allocate. */ size_t dstlen = 0; if (!js_encodecharacters(cx, src, srclen, null, &dstlen)) return js_false; /* allocate. */ char *dst = (char *) js_malloc(cx, dstlen); if (dst == null) return js_false; /* convert characters to bytes. */ js_encodecharacters(cx, src, srclen, dst, &dstlen); /* use the converted bytes for something.
...d returns js_true. otherwise it reports an error and returns js_false. this happens if the destination is too small for the resulting string or if the source buffer isn't proper utf-16 because it contains unpaired surrogate values. the user is responsible for allocating and freeing the memory of the destination string. js_encodecharacters never adds a trailing null character. to obtain a null-terminated string, allocate an extra byte for the null character and set it manually. to convert bytes to jschars, the opposite conversion, use js_decodebytes. to convert a jsstring to a c char string, use js_encodestring or js_getstringbytes. see also bug 805080 ...
JS_GetStringChars
spidermonkey 1.8.2, obsolete since jsapi 33 name type description cx jscontext * (in js_getstringcharsz only) a context. str jsstring * the string to obtain characters from. description js_getstringchars obsolete since javascript 1.8.5 returns a pointer to the first element of an array of jschars. warnings: the array is not necessarily null-terminated. to get the length of the string, use js_getstringlength. the program must not modify the array. if it does, the behavior is undefined. the content of a js string is not guaranteed to be valid utf-16. it may contain surrogate code units that aren't properly paired. it may also contain zeroes. the array returned by this function remains valid as long as str is valid. (eventually, str become...
...ng is not guaranteed to be valid utf-16. it may contain surrogate code units that aren't properly paired. it may also contain zeroes. the array returned by this function remains valid as long as str is valid. (eventually, str becomes unreachable, the garbage collector collects it, and the array is freed by the system.) js_getstringcharsz is the same except that it always returns either a null-terminated string or null, indicating out-of-memory. see also bug 609440 - removed js_getstringchars bug 1037869 - removed js_getstringcharsz ...
JS_HasArrayLength
obsolete since jsapi 8this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. determines if an object has an array length property. syntax jsbool js_hasarraylength(jscontext *cx, jsobject *obj, jsuint *lengthp); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. ...
... cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * array object to get the length of. lengthp jsuint * out parameter. on success, *lengthp receives the length of the array. description js_hasarraylength determines if an object, obj, has a length property. if the property exists, js_hasarraylength stores the current value of the property in *lengthp. on success, js_hasarraylength returns js_true, and *lengthp receives the current value of the length property. on failure, js_hasarraylength returns js_false, and the value left in *lengthp is undefined. this function differs from js_getarraylength in the tre...
JS_HasProperty
syntax bool js_hasproperty(jscontext *cx, js::handleobject obj, const char *name, bool *foundp); bool js_hasucproperty(jscontext *cx, js::handleobject obj, const char16_t *name, size_t namelen, bool *vp); bool js_haspropertybyid(jscontext *cx, js::handleobject obj, js::handleid id, bool *foundp); // added in spidermonkey 1.8.1 name type description cx jscontext * a context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject object to search on for the property. ...
...res request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject object to search on for the property. name or id const char * or const char16_t or js::handleid name of the property to look up. namelen size_t (only in js_hasucproperty) the length of name in characters, or -1 to indicate that name is null-terminated. foundp bool * non-null pointer to a variable of type bool. on success, js_hasproperty stores true in this variable if obj has a property with the given name, and false if not. description js_hasproperty searches an object, obj, and its prototype chain, for a property with the specified name. it behaves like the javascript expression name in obj. js_hasucproperty is the c...
JS_InitClass
t. if constructor is null, then static_ps and static_fs must also be null. unlike other jsnatives, this function must not call js_this or js_this_object. instead it must create a new object and return it. nargs unsigned number of arguments for the constructor. ps jspropertyspec * either null or a pointer to the first element of an array of jspropertyspecs, terminated by the null jspropertyspec, which can be written {0, 0, 0, 0, 0}. these properties, if any, are added to the class's new prototype object. all instances of the new class will inherit these properties via the prototype chain. fs jsfunctionspec * either null or a pointer to the first element of an array of jsfunctionspecs, terminated by js_fs_end. these functions, if any, are add...
...functionspecs, terminated by js_fs_end. these functions, if any, are added to the class's new prototype object. all instances of the new class will inherit these methods via the prototype chain. (this is the javascript equivalent of public, non-static methods in c++ or java.) static_ps jspropertyspec * either null or a pointer to the first element of an array of jspropertyspecs, terminated by the null jspropertyspec. these properties, if any, are added to the new class's constructor. (this is the nearest javascript equivalent of public static member variables in c++ or public static fields in java.) static_fs jsfunctionspec * either null or a pointer to the first element of an array of jsfunctionspecs, terminated by js_fs_end. these functions, if any, are added t...
JS_InstanceOf
syntax bool js_instanceof(jscontext *cx, js::handle<jsobject*> obj, const jsclass *clasp, js::callargs *args); // added in spidermonkey 38 bool js_instanceof(jscontext *cx, js::handle<jsobject*> obj, const jsclass *clasp, jsval *argv); // obsolete since jsapi 32 name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handle&lt;jsobject*&gt; object to test. clasp jsclass * class against which to test the object. args js::callargs * optional pointer to arguments. ...
...uired. to use it this way, pass the arguments provided by the engine for args with js::callargsfromvp(argc, vp). when args is non-null, js_instanceof behaves as follows. if obj is of the given class, it returns true. otherwise, it returns false; it also reports a typeerror containing the function's name. note that js_instanceof is not the equivalent of the javascript instanceof keyword, which examines constructor properties along the prototype chain. js_hasinstance is similar to instanceof. see also mxr id search for js_instanceof js_hasinstance js_getclass bug 959787 ...
JS_IsExceptionPending
example /* jsapi */ bool pending; js::rootedvalue exception(cx); /* if an exception is pending, save and clear it. ...
...nding(jscontext *cx); name type description cx jscontext * pointer to a js context to check for pending exceptions. description js_isexceptionpending returns true if an exception has been thrown in the context cx and the exception has not yet been caught or cleared. otherwise, it returns false this can be used from jsnative functions which call js code to determine if the called js code threw an exception or not. example /* jsapi */ bool pending; js::rootedvalue exception(cx); /* if an exception is pending, save and clear it. */ pending = js_isexceptionpending(cx); if (pending) { if (!js_getpendingexception(cx, &exception)) return false; js_clearpendingexception(cx); } /* ... code that might throw js exception ... */ if (js_isexceptionp...
JS_IsGlobalObject
description js_isglobalobject returns true if obj is a global object, false otherwise. ...
... description js_isglobalobject returns true if obj is a global object, false otherwise. ...
JS_LookupElement
syntax bool js_lookupelement(jscontext *cx, js::handleobject obj, uint32_t index, js::mutablehandlevalue vp); name type description cx jscontext * the context in which to look up the property. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. ...
...js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject the object to search. index uint32_t the numeric id of the property to look up. vp js::mutablehandlevalue out parameter. on success, *vp receives the stored value of obj[index], or undefined if the element does not exist. description js_lookupelement examines a specified javascript object, obj, for a numeric property numbered index. note: in the javascript language, numeric properties (also called "elements") are just ordinary properties whose names are numeric strings. for example, obj[6] is always exactly the same as obj["6"]. the ecmascript standard also specifies this behavior: see ecma 262-3 §11.2.1, step 6. so any call to js_lookupelement is...
JS_LookupProperty
obsolete since jsapi 37this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. determine if a specified property exists. syntax bool js_lookupproperty(jscontext *cx, js::handleobject obj, const char *name, js::mutablehandlevalue vp); bool js_lookupucproperty(jscontext *cx, js::handleobject obj, const char16_t *name, size_t namelen, js::mutablehandlevalue vp); bool js_lookuppropertybyid(jscontext *cx, js::handleobject obj, js::handleid id, js::mutablehandlevalue vp); // added in spidermonkey 1.8.1 bool js_lookupelement(jscontext *cx, js::handleobject obj, uint32_t index, js::mutablehandlevalu...
...request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject object to search on for the property. name or id const char * or const char16_t *or js::handleid name of the property to look up. namelen size_t (only in js_lookupucproperty) the length of name in characters; or -1 to indicate that name is null-terminated. flags unsigned (only in js_lookuppropertywithflags) a combination of bits requesting special search behavior. see flags below. objp js::mutablehandleobject out parameter. on success, *objp receives the object on which the property was found. this will be either obj or an element on obj's prototype chain. vp js::mutablehandleobject out parameter. o...
JS_LooselyEqual
this article covers features introduced in spidermonkey 1.8.1 determine whether two javascript values are equal in the sense of the == operator. syntax bool js_looselyequal(jscontext *cx, js::handle<js::value> v1, js::handle<js::value> v2, bool *equal); name type description cx jscontext * the context in which to perform the conversion. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. v1, v2 js::handle&lt;js::value&gt; the value to compare. equal bool * out parameter. receives the comparison result. ...
... name type description cx jscontext * the context in which to perform the conversion. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. v1, v2 js::handle&lt;js::value&gt; the value to compare. equal bool * out parameter. receives the comparison result. description js_looselyequal determines if v1 is loosely equal to v2 under the javascript == operator, as specified in ecma 262-3 §11.9.3. if the comparison attempt was successful, the method returns js_true and stores the result in *equal; otherwise it returns js_false. comparing jsvals directly in c++, as in v1 == v2, does not produce a meaningful result, since it is possible for two distinct jsstrings or jsdoubles to represent t...
JS_MaybeGC
if so, it performs some garbage collection. ...
... periodically when the application is busy, from a jsbranchcallback or jsoperationcallback added in spidermonkey 1.8, can keep memory usage down and improve performance. both are good practices. in both cases, frequent calls js_maybegc are safe and will not cause the application to spend a lot of time doing redundant garbage collection work. implementation note: spidermonkey 1.8 and earlier determine whether garbage collection is appropriate by analyzing statistics about the gc heap and memory usage since the last garbage collection cycle. the analysis is simplistic but produces acceptable performance for many applications. in some applications, js_maybegc collects more often than it should for ideal performance. such applications can benefit from implementing their own custom-tuned maybe-gc...
JS_NewExternalString
with the desired character data before js_newexternalstring is called, and the array must remain in memory, with its contents unchanged, for as long as the javascript engine needs to hold on to it. (ultimately, the string will be garbage collected, and the javascript engine will call the string finalizer callback, allowing the application to free the array.) the array does not need to be zero-terminated. length size_t the number of characters in the array chars. fin jsstringfinalizer a string finalizer the javascript engine should use (later) to free the string buffer chars. added in spidermonkey 17 type int (js_newexternalstringwithclosure only) indicates which string finalizer callback the javascript engine should use (later) to free the string ...
...ill need to free it; this happens in an external string finalizer indicated by the type parameter. js_newexternalstringwithclosure works similarly, except it accepts an additional parameter, closure, which is saved in the string's internal data structure. it can be retrieved later by calling js_getexternalstringclosure. this is application-defined data you can associate with the string. to determine if a string was created as an external string, you can call js_isexternalstring. see also mxr id search for js_newexternalstring js_getexternalstringclosure js_isexternalstring bug 724810 - replaced type with fin parameter, and remove js_newexternalstringwithclosure ...
JS_NewStringCopyZ
create a new javascript string based on a null-terminated c string. syntax jsstring * js_newstringcopyz(jscontext *cx, const char *s); jsstring * js_newucstringcopyz(jscontext *cx, const char16_t *s); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. s const char * or const char16_t * pointer to the character array containing the text for the js string to create; or null. description js_newstringcopyz allocates space for a new javascript string and its underlying storage, and then copies the contents of a null-terminated character array, s, into the new string. on success, js_newstringcopyz r...
... a new javascript string and its underlying storage, and then copies the contents of a null-terminated character array, s, into the new string. on success, js_newstringcopyz returns a pointer to the new javascript string. on error, it returns null. if s is null, an empty javascript string is returned. js_newstringcopy(cx, s) is equivalent to js_newstringcopyn(cx, s, strlen(s)) when s is a null-terminated string. see also mxr id search for js_newstringcopyz mxr id search for js_newucstringcopyz js_getemptystringvalue js_newstringcopyn js_newucstringcopyn js_valuetostring ...
JS_SameValue
samevalue slightly differs from strict equality (===) in that +0 and -0 are not the same and in that nan is the same as nan. ...
...name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. v1 js::handle&lt;js::value&gt; / jsval the first value. v2 js::handle&lt;js::value&gt; / jsval the second value. description js_samevalue determines whether two values are the same, returning true or false accordingly. this method is infallible. see also mxr id search for js_samevalue js_strictlyequal js_looselyequal bug 1132045 -- use handle ...
JS_SetGCCallback
is no longer needed. to restore the original callback, call js_setgccallback a second time, and pass the old callback in as the cb argument. during each complete garbage collection cycle, the current gc callback is called four times: jsgc_begin start of gc. the callback may prevent gc from starting by returning false. but even if the callback returns true, the garbage collector may determine that gc is not necessary, in which case the other three callbacks are skipped. jsgc_mark_end obsolete since jsapi 13 end of marking. the callback may use js_isabouttobefinalized to clean up weak references to js objects (that is, pointers that are not traced by the gc). jsgc_finalize_end obsolete since jsapi 13 end of finalization. jsgc_end end of gc. sometimes these fou...
...appens and the rest of garbage collection does not happen, so the other three callbacks are not called. sometimes several gc cycles happen in a row, so jsgc_begin is followed by alternating jsgc_mark_end and jsgc_finalize_end callbacks, followed at last by jsgc_end. the jsgc_begin callback can occur very early when something triggers garbage collection—before the javascript engine has even determined whether gc should actually be done at the moment. some quirky behavior follows from this: the javascript engine can call the gc callback reentrantly on a single thread. for example, if the jsgc_mark_end callback does something that triggers gc, a jsgc_begin callback might happen. but the javascript engine will then detect that gc is already happening and will not actually do a nested gc cycle...
JS_SetParent
ent. this must be an object that has not yet been exposed to script. see the description for details. parent js::handleobject pointer to the parent object to use. description js_setparent sets an object's parent. each object may have at most one parent, which is another object. applications that use spidermonkey's security features typically use the parent relation to determine both (a) what security principals are attached to the currently executing script; and (b) what security principals are attached to the object being accessed. (for some function objects, the parent chain is also used to implement lexical scoping, but this should be considered an implementation detail.) ordinarily an application sets a new object's parent by passing the parent object to js_newobj...
...nt chain is also used to implement lexical scoping, but this should be considered an implementation detail.) ordinarily an application sets a new object's parent by passing the parent object to js_newobject, and that is the preferred approach. but an application may instead use js_setparent after the object is created. 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. in fact, once an object is exposed to a script, the object's parent must not change. the javascript engine relies on this invariant. js_setparent has no way to check that this is the case, but nonetheless, applications must not call js_setparent on an object that has already been exposed to...
JS_StrictlyEqual
syntax // added in spidermonkey 45 bool js_strictlyequal(jscontext *cx, js::handle<js::value> v1, js::handle<js::value> v2, bool *equal); // obsolete since jsapi 39 bool js_strictlyequal(jscontext *cx, jsval v1, jsval v2, bool *equal); name type description cx jscontext * the context in which to perform the conversion. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. v1, v2 js::handle&lt;js::value&gt; / jsval the value to compare. ...
... name type description cx jscontext * the context in which to perform the conversion. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. v1, v2 js::handle&lt;js::value&gt; / jsval the value to compare. equal bool * out parameter. receives the comparison result. description js_strictlyequal determines if v1 is strictly equal to v2 under the javascript === operator, as specified in ecma 262-3 §11.9.6. if the comparison attempt was successful, the method returns true and stores the result in *equal; otherwise it returns false. comparing jsvals directly in c++, as in v1 == v2, does not produce a meaningful result, since it is possible for two distinct jsstrings or jsdoubles to represent the s...
JS_StringHasBeenInterned
description js_stringhasbeeninterned returns true if the string str is interned. ...
... description js_stringhasbeeninterned returns true if the string str is interned. ...
JS_StringIsFlat
description js_stringisflat returns true if the string is flattened. ...
... description js_stringisflat returns true if the string is flattened. ...
JS_SuspendRequest
although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. removed from spidermonkey at or prior to version 45. since then, a jsruntime is tied to the thread that created it; it may not be accessed by any other thread. suspends the calling thread's current request, if any, to allow the thread to block or perform time-consuming calculations. syntax jsrefcount js_suspendrequest(jscontext *cx); void js_resumerequest(jscontext *cx, jsrefcount savedepth); name type description cx jscontext * the context whose current request is to be suspended or resumed. savedepth jsrefcount (only in js_resumerequest) the valued returned by the matching js_suspendrequest call. descr...
... to be suspended or resumed. savedepth jsrefcount (only in js_resumerequest) the valued returned by the matching js_suspendrequest call. description in js_threadsafe builds, when a multi-threaded application is in a request but needs to block or perform lengthy computation that can race safely with the garbage collector, it should call js_suspendrequest before the time-consuming operation and js_resumerequest after. for more information about thread safety and requests, see js_threadsafe. js_suspendrequest suspends any currently active requests associated with the context cx. this allows the runtime to perform garbage collection if needed and allows other threads to access objects that the calling thread had locked. the return value is the number of nested requests tha...
JS_THREADSAFE
recently, sharing objects among threads would mostly work, although scripts could easily make it crash. we have now completely removed that feature. each thread that uses the javascript engine must essentially operate in a totally separate region of memory. requests in a js_threadsafe build, the application must separate code that uses the jsapi from code that performs blocking i/o or time-consuming calculations. a request is a region of code that uses the jsapi. requests must be bracketed with calls to js_beginrequest() and js_endrequest(). js_beginrequest(cx); /* ... do jsapi stuff ... */ js_endrequest(cx); a request is always associated with a specific jscontext and runs from start to finish on a single thread. most jsapi functions require the caller to be in a request. in this refe...
...or may call js_gc(). the above rules mean that at any given moment, there can be either (a) multiple threads in active requests, or (b) one thread doing gc and all requests suspended. when one thread calls js_gc or otherwise finds that garbage collection is necessary, it must wait for all other threads that are in requests to pause before garbage collection can occur. to keep this wait time to a minimum, applications must avoid long-running requests. the recommended technique in spidermonkey 1.8 and later is to periodically call js_yieldrequest from an operation callback. sharing data among threads "data can be marshaled across the process boundary through a process known as smuggling." --mr. bunny's guide to activex even in js_threadsafe builds, threads cannot safely share objects or str...
JS_malloc
jscontext * pointer to a js context. if allocation fails, an error is reported in this context. p void * (js_realloc and js_free only) pointer to a previously allocated region of memory to resize or deallocate. nbytes size_t (js_malloc and js_realloc only) amount of space, in bytes, to allocate. s const char * (js_strdup only) pointer to a null-terminated string. s must not be null. description js_malloc allocates a region of memory nbytes in size. on success, js_malloc returns a pointer to the beginning of the region. as with the standard c function malloc, memory allocated by js_malloc is uninitialized. js_realloc tries to change the allocation size of the region of memory at p to nbytes. failing that, js_realloc allocates a new region...
...e existing data in p as will fit to the new region. then it frees the region at p and returns a pointer to the new region. apart from whatever is copied, any newly allocated space is uninitialized. js_realloc(cx, null, nbytes) behaves exactly like js_malloc(cx, nbytes). when p is not null, js_realloc(cx, p, 0) behaves like js_free(cx, p) and returns null. js_strdup allocates a copy of the null-terminated string s. on success, it returns a pointer to the copy. if any of these three functions fails to allocate the required amount of memory, it reports an error as though by calling js_reportoutofmemory(cx) and returns null. js_free deallocates a region of memory allocated a previous call to js_malloc, js_realloc, or js_strdup. if p is null, js_free does nothing. once the region of memory is free...
Property attributes
rty's setter is a javascript function, not a c/c++ function. see js_defineproperty for details. mxr id search for jsprop_setter jsprop_shared the property is shared. this is usually the right thing for properties that have getters or setters. this has three effects: the javascript engine does not set aside any memory for the property's value. the value is determined entirely by the getter. (the property has no stored value.) assignment via the prototype chain is affected. assigning to obj.x, where obj inherits a non-shared property from its prototype, creates a new own data property on obj; the prototype's .x is not shared with its children. if the inherited property is shared, the setter is called instead. if the property is also jsprop_permanen...
... that will need to go away in bug 1105518. added in spidermonkey 38 mxr id search for jsprop_redefine_nonconfigurable jsprop_resolving resolve hooks and enumerate hooks must pass this flag when calling js_define* apis to reify lazily-defined properties. jsprop_resolving is used only with property-defining apis. it tells the engine to skip the resolve hook when performing the lookup at the beginning of property definition. this keeps the resolve hook from accidentally triggering itself: unchecked recursion. for enumerate hooks, triggering the resolve hook would be merely silly, not fatal, except in some cases involving non-configurable properties. added in spidermonkey 45 mxr id search for jsprop_resolving jsprop_ignore_enumerate ...
Parser API
ch are plain javascript objects (i.e., their prototype derives from the standard object prototype). all node types implement the following interface: interface node { type: string; loc: sourcelocation | null; } the type field is a string representing the ast variant type. each subtype of node is documented below with the specific string of its type field. you can use this field to determine which interface a node implements. the loc field represents the source location information of the node. if the parser produced no information about the node's source location, the field is null; otherwise it is an object consisting of a start position (the position of the first character of the parsed source region) and an end position (the position of the first character after the parsed sour...
... label: identifier | null; } a break statement. interface continuestatement <: statement { type: "continuestatement"; label: identifier | null; } a continue statement. interface withstatement <: statement { type: "withstatement"; object: expression; body: statement; } a with statement. interface switchstatement <: statement { type: "switchstatement"; discriminant: expression; cases: [ switchcase ]; lexical: boolean; } a switch statement. the lexical flag is metadata indicating whether the switch statement contains any unnested let declarations (and therefore introduces a new lexical scope). interface returnstatement <: statement { type: "returnstatement"; argument: expression | null; } a return statement. interface throwstatement ...
WebReplayRoadmap
d below. retroactive console logging console logging is one of the primary tools most developers use to debug a page. seeing messages in the console provides a simple and intuitive view into the order in which events have happened. without time travel, using the console requires repeatedly updating the source or the debugger's log points, reloading, and reproducing the bug. this is time consuming, especially when the bug only reproduces intermittently. retroactive console logging offers a large improvement to this workflow. the bug only needs to be reproduced in a recording tab once, and then console logs can be added which apply throughout the entire recording. this is based on the logpoints feature in the debugger, which can be enabled with the devtools.debugger.features.log-points ...
...tion, and as with static type integration above, points where unexpected types appear can be seeked to in the debugger for investigation. memory analysis (not yet implemented) analyzing memory usage and leaks in js can be difficult because there is no (or limited) information about where objects were allocated or how the object graph was constructed. recordings can be manually analyzed to determine this information, but it would be nice to automate this process and provide a summary of the allocation sites and places where objects are linked together that end up entraining the most amount of memory later on. platform improvements this section describes improvements to web replay's underlying platform which could make it more broadly useful for developers. support more web features (not ...
Exploitable crashes
what is an exploitable crash? a crash report from your debugger, your os, or mozilla crash-stats can tell you a lot about whether or not a crash is potentially exploitable. you want to look primarily for three things, in order: look at the top frame of the stack trace. if you see a hex address such as 0x292c2830 rather than a function name such as nslistboxbodyframe::getrowcount at the top of the stack, a bug has caused the program to transfer control to a "random" part of memory that isn't part of the program. these crashes are almost always exploitable to run arbitrary code. ...
...ploitable. additionally, mozilla developers make heavy use of two tools in particular to find exploitable situations before they show up as exploitable crash reports. the first tool is addresssanitizer (asan). there is an mdn article documenting its use with mozilla projects. the other tool is valgrind. there is an mdn article documenting its use with mozilla projects. next steps once you've determined that a crash is potentially exploitable, take the following steps. if you need help with any of the steps (e.g. perhaps you lack necessary bugzilla privileges) please email security@mozilla.org. make sure a bug is on file. mark the bug as security-sensitive by putting it into the "security-sensitive core bug" group. do this before making comments or taking actions that expose exploitability ...
Setting up an update server
ths with spaces. serving the update preparing the update files first, create the directory that updates will be served from and put the mar file in it. then, create a file within called update.xml with these contents, replacing <mar name>, <hash> and <size> with the mar's filename, its sha512 hash, and its file size in bytes. ...
... 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. installing the update you may want to start by deleting any pending updates to ensure that no previously found updates interfere with installing the desired update. you can use this command with firefox's browser console to determine the update directory: const {fileutils} = chromeutils.import("resource://gre/modules/fileutils.jsm"); fileutils.getdir("updrootd", [], false).path once you have determined the update directory, close firefox, browse to the directory and remove the subdirectory called updates. next, you need to change the update url to point to the local xml file. this can be done most reliably with an enterpr...
Gecko Roles
cally showing the user the percent complete of an operation in progress. role_dial represents a dial or knob whose purpose is to allow a user to set a value. role_hotkeyfield represents a hot-key field that allows the user to enter a combination or sequence of keystrokes. role_slider represents a slider, which allows the user to adjust a setting in given increments between minimum and maximum values. role_spinbutton represents a spin box, which is a control that allows the user to increment or decrement the value displayed in a separate "buddy" control associated with the spin box. role_diagram represents a graphical image used to diagram data. role_animation represents an animation control, which contains content that changes over time, such as...
...ed panel that presents two other panels at the same time. between the two panels is a divider the user can manipulate to make one panel larger and the other panel smaller. role_table_column_header the header for a column of a table. role_table_row_header the header for a row of a table. role_tear_off_menu_item a menu item used to tear off and reattach its menu. role_terminal represents an accessible terminal. role_text_container collection of objects that constitute a logical text entity. role_toggle_button a toggle button. a specialized push button that can be checked or unchecked, but does not provide a separate indicator for the current state. role_tree_table representas a control that is capable of expanding and collapsing rows as we...
AT APIs Support
ng engine (please contact us for a copy). k-meleon - light, ultra-fast and more advanced (fully configurable) gecko-based web browser available on the windows platform on linux/unix platform yelp help viewer - the help viewer in gnome evolution email - provides integrated mail, addressbook and calendaring functionality to users of the gnome desktop. on mac platform camino - web browser for os x xul applications xul applications make full use of the gecko architecture, not only for html content, but also for the entire user interface. widgets such as menus, tab panels, tree views and dialogs are provided via an xml language called xul (extensible user-interface language). none of the user interface contains standard os controls. this is done to ensure a co...
...ation applies to up-to-date product builds based on gecko 1.9.2 -- currently not available on official releases. however most of described features are supported starting from gecko 1.9.0 (firefox 3.0). however it's preferable to grab the current build of firefox or any other gecko-based product to be up to dated: firefox recent builds thunderbird recent builds seamonkey recent builds determining if accessibility is enabled in a firefox accessibility is enabled on windows and linux platforms by default. as well you might find helpful the about:accessibilityenabled firefox extension. supported at apis at apis terms microsoft active accessibility (msaa) an api devised by microsoft so that accessibility aids can track what's going on inside the user interface of any software packag...
Places Developer Guide
f the livemark siteuri, // the uri of the site. a nsiuri object. feeduri, // the uri of the actual feed. a nsiuri object. bookmarks.default_index); // the position of the livemark in its parent folder. ...
..., and iterate over its contents. resultcontainernode.containeropen = true; for (var i=0; i < resultcontainernode.childcount; ++i) { var childnode = resultcontainernode.getchild(i); // accessing properties of matching bookmarks var title = childnode.title; var uri = childnode.uri; } updating bookmark items for all items: setitemtitle(aitemid, atitle) - changes an item's title. setitemindex(aitemid, aindex) - changes an item's position. note: this does not re-index the whole folder - use moveitem for a managed solution. setitemdateadded(aitemid, adateadded) - set the date the item was first added, in microseconds. setitemlastmodified(aitemid, alastmodified) - set the date the item was last modified, in microseconds. setitemguid(aitemid, aguid) obsolete since gecko 14.0 - re...
Places Expiration
vailable disk space. this means on mobile and old systems expiration will be more aggressive than on high-end hardware, to try keep the database size at a reasonable (and performant) value. all of expiration uses the storage async api, that ensures i/o is in a separate thread, plus it won't block any read thanks to the use of the wal journaling system. common expiration runs on a timer, every 3 minutes and uses a simple adaptive algorithm: if the last step was unable to expire enough entries the next one will expire more entries, otherwise if the previous step completed the cleanup the next step will be delayed. this ensures expiration doesn't lag behind without hitting performances when there is no need for it. apart this periodic expiration, there are other steps on idle, on shutdown on ...
...intenance when places maintenance runs (about once a week, on daily idle), an orphans expiration step is executed, this ensures database cleanup. preferences usually there is no need to tweak or set any preference, since adaptive behavior should satisfy each need, though in case of unexpected issues it's possible to act on some hidden preferences: places.history.expiration.interval_seconds: minimum number of seconds between expiration steps. default is 180 seconds. places.history.expiration.max_pages: the maximum number of pages that may be retained in the database before starting to expire. default value is calculated on startup and put into the places.history.expiration.transient_current_max_pages preference. this transient version of the preference is just mirroring the current valu...
Using the Places favicon service
ce;1, so to gain access to the favicon service, you should do something like this: var faviconservice = components.classes["@mozilla.org/browser/favicon-service;1"] .getservice(components.interfaces.nsifaviconservice); caching the favicon service stores an expiration time for each favicon. this time is used by nsifaviconservice.setandloadfaviconforpage() to determine if the data is fresh or needs reloading from the server. if you are manually loading favicon data, you can specify the expiration time yourself. otherwise, nsifaviconservice.setandloadfaviconforpage() will use the default expiration time. currently, the default expiration time is set to one day in the future. this makes sure that we aren't obsessively reloading favicons into the database for eve...
...iconservice.setandloadfaviconforpage() will use the default expiration time. currently, the default expiration time is set to one day in the future. this makes sure that we aren't obsessively reloading favicons into the database for every page viewed, but also that changes in the favicon will be picked up quickly. most of the time, the favicon will be served from the browser's cache and will have minimal performance impact. this expiration time is not the time that the favicon will be deleted. expiration is handled by browser/components/places/src/nsnavhistoryexpire.cpp as described in places design. the expiration time is only used to determine whether data should be reloaded from the network (or cache) or whether the version in the database is fresh enough. getting favicon images you can...
FUEL
we want to start with areas that will provide the most benefit. fuel has a fueliapplication interface that implements all the functions of extiapplication. ...
...we want to start with areas that will provide the most benefit. fuel has a fueliapplication interface that implements all the functions of extiapplication. ...
SMILE
we want to start with areas that will provide the most benefit. smile has a smileiapplication interface that implements all the functions of extiapplication. the library has also been implemented in firefox ("fuel") and in thunderbird ("steel"). ...
...we want to start with areas that will provide the most benefit. smile has a smileiapplication interface that implements all the functions of extiapplication. the library has also been implemented in firefox ("fuel") and in thunderbird ("steel"). ...
Building the WebLock UI
as you can see, weblock is initialized as a global javascript variable, available in the scope of these functions and others: var weblock = components.classes["@dougt/weblock"] .getservice() .qu...
...tandard dialog, so it can use a single declaration to import the "global" skin from the browser and make it available to the widgets you define in weblock.xul. you can save this first, outermost part of the web lock dialog in a file called weblock.xul, which you'll be adding to an installer archive in appendix b in this book. note that this file defines the dialog that displays when the user/administrator clicks the web locking icon in the bottom right corner of the browser. that piece of ui - which needs to be dynamically inserted into the browser at runtime - is described in overlaying new user interface into mozilla. the finished dialog appears below. web lock manager dialog as you can see, it's a simple interface, providing just enough widgetry to lock and unlock the browser and ...
Using XPCOM Components
ing capabilities of xpcom. it is handled by the queryinterface method, which was introduced in the chapter an overview of xpcom. the xpcom api reference provides a full reference of the xpcom components available in mozilla. the weblock component now it's time to look at the weblock component as another example of xpcom components (since you'll be creating it shortly). in object-oriented programming, it's typical to design the interface first-to define the functionality that's going to be provided in the abstract, without worrying about how this functionality will be achieved. so we'll put aside the details of the implementation until the next chapter and look at the component from the outside-at the interface to the weblock component. the iweblock interface lock lock the brow...
...ite remove a given site from the whitelist. sites enumerator for the list of approved sites read in from the whitelist. the weblock component is software that implements all of these methods in the way described by the interface definition. it registers itself for use when the browser starts up, and provides a factory that creates an instance of it for use when the user or administrator clicks the weblock icon in the browser's user interface. component use in mozilla so how are components obtained and used in mozilla? you've seen some enticing snippets of javascript in earlier sections of this chapter, but we haven't explained how xpcom makes components available in general. this section discusses practical component use in mozilla. it's divided into three subsections...
XPCOM hashtable guide
time: o(1): lookup time is a simple constant o(1): lookup time is mostly-constant, but the constant time can be larger than an array lookup sorting: sorted: stored sorted; iterated over in a sorted fashion. unsorted: stored unsorted; cannot be iterated over in a sorted manner. inserting/removing: o(n): adding and removing items from a large array can be time-consuming o(1): adding and removing items from hashtables is a quick operation wasted space: none: arrays are packed structures, so there is no wasted space. some: hashtables are not packed structures; depending on the implementation, there may be significant wasted memory. in their implementation, hashtables take the key and apply a mathematical hash function to randomize the key...
... a few examples: a hashtable that maps utf-8 origin names to a dom window - nsinterfacehashtable<nscstringhashkey, nsidomwindow> a hashtable that maps 32 bit integers to floats - nsdatahashtable<nsuint32hashkey, float> a hashtable that maps nsisupports pointers to reference counted cacheentrys - nsrefptrhashtable<nsi...
Interfacing with the XPCOM cycle collector
time accumulating (and forgetting about) pointers to xpcom objects that might be involved in garbage cycles. this is the idle stage of the collector's operation, in which special variants of nsautorefcnt register and unregister themselves very rapidly with the collector, as they pass through a "suspicious" refcount event (from n+1 to n, for nonzero n). periodically the collector wakes up and examines any suspicious pointers that have been sitting in its buffer for a while. this is the scanning stage of the collector's operation. in this stage the collector repeatedly asks each candidate for a singleton cycle-collection helper class, and if that helper exists, the collector asks the helper to describe the candidate's (owned) children. this way the collector builds a picture of the ownership ...
...ce counts it finds in the owned objects, so may fail to collect cycles. 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. in general, assuming you are modifying class nsfoo with two nscomptr edges mbar and mbaz, the process can be distilled to a few simple modifications: include the header nscyclecollectionparticipant.h in both nsfoo.h and nsfoo.cpp. add a line declaring that your class nsfoo participates in the cycle collection in nsfoo.cpp: ns_impl_cycle_collection_class(nsfoo) change the line ns_decl_isupports to ns_decl_cy...
Introduction to XPCOM for the DOM
ch easier. in this chapter i will attempt to cover the most widespread use of xpcom in the dom, avoiding the details as much as possible. i will introduce nscomptr's, interfaces, reference counting, and the nsisupports interface. a tutorial about how to add a new interface is also provided, and eventually, a more detailed discussion of class inheritance in c++. interfaces object-oriented programming is based on the used of inheritance between classes. furthermore, a class can be de declared to be "abstract" if it declares some methods but does not implement them entirely. pushing this concept to its maximum, a class can be "purely virtual" if it declares methods without implementing any of them. such a class is called an interface. the goal of interfaces is to have a single ... interface to...
...l rebuild. i recommend building distclean. your methods will not be available from javascript, however, because nsidomfabian is not in the class info. please see the user's guide of class info to learn how to add it. interface inheritance (advanced topic) the inheritance model in mozilla is of course the same as the class inheritance model of c++. if you are familiar with object-oriented programming you will have no problem understanding this discussion. raw interface inheritance the first concept is easy to grasp, it's the "interface inheritance". if we look at any interface definition, in xpidl or as a header, we can see that it always inherits from another interface. for instance, we have the following "chain" for the nsidomhtmlanchorelement interface: nsisupports -> nsidomnode -> nsi...
Components.utils.getGlobalForObject
this method is used to determine the global object with which an object is associated. this is the global object in place at the time the object was created, which is to say the global object used when executing the script that created the object. ...
... whose corresponding global object is to be retrieved; non-optional, must be object-valued example var obj = {}; function foo() { } var global = this; var g1 = components.utils.getglobalforobject(foo); var g2 = components.utils.getglobalforobject(obj); // g1 === global, g2 === global, g1 === g2 // in a script in another window var global2 = this; function bar() { } var obj2 = {}; // then, assuming bar refers to the function defined in that other window: var o1 = components.utils.getglobalforobject(bar); var o2 = components.utils.getglobalforobject(obj2); // o1 === global2, o2 === global2 ...
nsACString
beginreading the beginreading function returns a const pointer to the first element of the string's internal buffer. endreading the endreading function returns a const char_type pointer to the element just beyond the last element of the string's internal buffer. length the length function returns the number of storage units in the string's internal buffer (not including the null-terminator if present). assign the assign family of functions sets the value of a string's internal buffer. replace the replace family of functions sets the value of a string's internal buffer. append the append family of functions appends a value to the end of a string's internal buffer. insert the insert family of functions inserts a value into a string's internal buffer. cut ...
... utf-8 characters, ascii characters, or any random binary data. the character encoding in use for a particular nsacstring instance depends on the context in which it is used. if used with xpidl, then the character encodings of the corresponding xpidl data types applies. nsacstring may even hold data with embedded null bytes. thus, the length of the data contained in the nsacstring should be determined by calling the nsacstring::length() method. the methods defined on nsacstring are implemented as inline wrappers around the xpcom string functions, prefixed with ns_cstring. see, for example, ns_cstringgetdata. see also nsacstring::length() ns_cstringgetdata nsembedcstring ...
nsAString
reading the beginreading function returns a const pointer to the first element of the string's internal buffer. endreading the endreading function returns a const char_type pointer to the element just beyond the last element of the string's internal buffer. length the length function returns the number of storage units in the string's internal buffer (not including the null-terminator if present). assign the assign family of functions sets the value of a string's internal buffer. replace the replace family of functions sets the value of a string's internal buffer. append the append family of functions appends a value to the end of a string's internal buffer. insert the insert family of functions inserts a value into a string's internal buffe...
...f-16 characters, ucs-2 characters, or any random double-byte data. the character encoding in use for a particular nsastring instance depends on the context in which it is used. if used with xpidl, then the character encodings of the corresponding xpidl data types applies. nsastring may even hold data with embedded null values. thus, the length of the data contained in the nsastring should be determined by calling the nsastring::length method. the methods defined on nsastring are implemented as inline wrappers around the xpcom string functions, prefixed with ns_string. see, for example, ns_stringgetdata. see also nsastring::length, endreading, ns_stringgetdata, nsembedstring ...
XPCOM glue classes
these routines allow easy acce...
...these routines allow easy access to xpcom's global nsimemory implementation without having to go through the service manager to get it.nspromiseflatcstringclass d...
IAccessibleTable2
urned. return value e_invalidarg if bad [in] passed, [out] value is null. s_false if there is nothing to return, [out] value is null. s_ok. iscolumnselected() returns a boolean value indicating whether the specified column is completely selected. [propget] hresult iscolumnselected( [in] long column, [out] boolean isselected ); parameters column 0 based index of the column for which to determine whether it is selected. isselected returns true if the specified column is selected completely and false otherwise. return value e_invalidarg if bad [in] passed, [out] value is false. s_ok. isrowselected() returns a boolean value indicating whether the specified row is completely selected. [propget] hresult isrowselected( [in] long row, [out] boolean isselected ); parameters row 0 based i...
...ed returns true if the specified column is selected completely and false otherwise. return value e_invalidarg if bad [in] passed, [out] value is false. s_ok. isrowselected() returns a boolean value indicating whether the specified row is completely selected. [propget] hresult isrowselected( [in] long row, [out] boolean isselected ); parameters row 0 based index of the row for which to determine whether it is selected. isselected returns true if the specified row is selected completely and false otherwise. return value e_invalidarg if bad [in] passed, [out] value is false. s_ok. modelchange() returns the type and extents describing how a table changed. provided for use by the ia2_event_table_model_changed event handler. this data is only guaranteed to be valid while the thread notifyin...
inIDOMUtils
sheet object. getusedfontfaces() returns a list of the fonts specified using @font-face in the specified portion of the document. nsidomfontfacelist getusedfontfaces( in nsidomrange arange ); parameters arange the dom range to retrieve the font faces of. return value an nsidomfontfacelist object listing all the font faces used by the text in the range. isignorablewhitespace() determines if the specified text node contains only ignorable whitespace characters. boolean isignorablewhitespace( in nsidomcharacterdata adatanode ); parameters adatanode a dom characterdata node; that is, a text node. return value true if the node only contains insignificant whitespace. in particular, this will be false if certain css white-space styles are in effect. isinheritedproperty()...
...he specified text node contains only ignorable whitespace characters. boolean isignorablewhitespace( in nsidomcharacterdata adatanode ); parameters adatanode a dom characterdata node; that is, a text node. return value true if the node only contains insignificant whitespace. in particular, this will be false if certain css white-space styles are in effect. isinheritedproperty() determines if the specified string names a css property that is inherited by default. boolean isinheritedproperty( in astring apropertyname ); parameters apropertyname the name of the css property. return value true if the property is inherited, otherwise false. parsestylesheet() parse css and update the style sheet in place. void parsestylesheet( in nsidomcssstylesheet asheet, in domst...
mozIVisitStatusCallback
void isvisited( in nsiuri auri, in boolean avisitedstatus ); parameters auri the uri that was checked to see if it's been visited. avisitedstatus true if the specified uri has been visited; otherwise false. see also moziasynchistory ...
... introduced gecko 11.0 inherits from: nsisupports last changed in gecko 11.0 (firefox 11.0 / thunderbird 11.0 / seamonkey 2.8) method overview void isvisited(in nsiuri auri, in boolean avisitedstatus); methods isvisited() called when the moziasynchistory.isurivisited() method's check to determine whether a given uri has been visited has completed. implement this method to determine the results of the request. void isvisited( in nsiuri auri, in boolean avisitedstatus ); parameters auri the uri that was checked to see if it's been visited. avisitedstatus true if the specified uri has been visited; otherwise false. see also moziasynchistory ...
nsIAccessibleHyperLink
o the nsiaccessiblehyperlink interface of the object that owns this hyperlink. read only. note: the link itself is represented by one embedded character within the parent text, so the endindex should be startindex + 1. exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. selected boolean determines whether the element currently has the focus, for example after returning from the destination page. read only. note: aria links can only be focused if they have the tabindex attribute set. also, state_focused should then be set on the accessible for this link. exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. ...
... startindex long the offset of the hyperlink accessible within the parent accessible. the returned value is related to the nsiaccessiblehyperlink interface of the object that owns this hyperlink. read only. exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. valid boolean determines whether the hyperlink is valid, for example points to a valid url. read only. note: currently only used with aria links, and the author has to specify that the link is invalid via the aria-invalid='true' attribute. in all other cases, true is returned. exceptions thrown ns_error_failure indicates that the accessible is unattached from the accessible tree. ...
nsIAccessibleValue
accessible/public/nsiaccessiblevalue.idlscriptable please add a summary to this article. inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview boolean setcurrentvalue(in double value); obsolete since gecko 1.9 attributes attribute type description currentvalue double maximumvalue double read only. minimumincrement double read only. minimumvalue double read only. ...
...ouble value); obsolete since gecko 1.9 attributes attribute type description currentvalue double maximumvalue double read only. minimumincrement double read only. minimumvalue double read only. methods setcurrentvalue() obsolete since gecko 1.9 (firefox 3) return a success condition of the value getting set. that is if the value is within the range of minimumvalue - maximumvalue. boolean setcurrentvalue( in double value ); parameters value new value for current value. return value true if the value is within the range of minimumvalue - maximumvalue, false if it is not. ...
nsIAlertsService
di override for the title. valid values are "auto", "ltr" or "rtl". only available on supported platforms. lang optional language of title and text of the alert. only available on supported platforms. data optional the value of the cookie parameter passed to showalertnotification. principal optional the principal of the page that created the alert. used for ipc security checks, and to determine whether the alert is actionable. inprivatebrowsing optional controls the image loading behavior. if true, the image url will be loaded in private browsing mode. exceptions thrown ns_error_not_available unable to display the notification; this may happen, for example, on mac os x if growl is not installed. example simple usage the following code was used to display the above notificat...
... service test", "click me", true, "cookie", listener, ""); } catch (e) { // this can fail on mac os x } example 2 this example shows how to use all the available observer topics: var as = cc['@mozilla.org/alerts-service;1'].getservice(ci.nsialertsservice); var notiflistener = { observe: function(asubject, atopic, adata) { console.error('incoming notification observer:', asubject, atopic, adata); if (atopic == 'alertclickcallback') { console.error('user clicked trying to throw click'); services.prompt.alert(services.wm.getmostrecentwindow('navigator:firefox'), 'focus firefox', 'will now focus fireox and then focus the tab'); } else if (atopic == 'alertshow') { console.log('just showe...
nsIBrowserHistory
bsolete since gecko 15.0 pruint32 indicates if there are entries in global history. for performance reasons this does not return the real number of entries. read only. lastpagevisited obsolete since gecko 10.0 autf8string the last page that was visited in a top-level window. read only. note: the count attribute was removed in gecko 15.0 because it was only used to determine if there were any entries at all anyway, so the nsinavhistoryservice.hashistoryentries attribute is better for this. methods addpagewithdetails() obsolete since gecko 15.0 (firefox 15.0 / thunderbird 15.0 / seamonkey 2.12) note: this method was removed in gecko 15.0. you should use moziasynchistory.updateplaces() instead. this method adds a page to the history wit...
...epoch. markpageasfollowedlink() obsolete since gecko 22.0 (firefox 22.0 / thunderbird 22.0 / seamonkey 2.19) note: this method was moved to another interface in gecko 22.0. you should use nsinavhistoryservice.markpageasfollowedlink() instead. this function was originally added in gecko 2.0 (firefox 4/thunderbird 3.3/seamonkey 2.1). designates the specified url as coming from a link explicitly followed by the user (for example by clicking on it). void markpageasfollowedlink( in nsiuri auri ); parameters auri the url that is to be marked as explicitly followed by the user. markpageastyped() obsolete since gecko 22.0 (firefox 22.0 / thunderbird 22.0 / seamonkey 2.19) note: this method was moved to another interface in gecko 2...
nsICacheEntryDescriptor
che descriptor. this is meant as a tool for clients that wish to instruct pending requests to skip the cache. void doomandfailpendingrequests( in nsresult status ); parameters status the access status. getmetadataelement() this method retrieves the meta data. meta data is a table of key/value string pairs. the strings do not have to conform to any particular charset, but they must be null terminated. string getmetadataelement( in string key ); parameters key the key for retrieving the meta data. return value returns the string value containing the meta data for the provided key. markvalid() this method means that a writer must validate this cache object before any readers are given a descriptor to the object. void markvalid(); parameters none. openinputstream() this method opens bl...
...h the cache entry should be considered invalid (in seconds since the epoch). void setexpirationtime( in pruint32 expirationtime ); parameters expirationtime the time for cache entry expiration (in seconds). setmetadataelement() this method sets the meta data. meta data is a table of key/value string pairs. the strings do not have to conform to any particular charset, but they must be null terminated. void setmetadataelement( in string key, in string value ); parameters key the key for setting the meta data. value the value for setting the meta data. visitmetadata() this method means that the visitor will be called with key/value pair for each meta data element. void visitmetadata( in nsicachemetadatavisitor visitor ); parameters visitor the visitor to be called. see also nsi...
nsIChannel
so on.), and the caller most likely wants to verify with the actual data. setting contenttype before the channel has been opened provides a hint to the channel as to what the mime type is. the channel may ignore this hint in deciding on the actual mime type that it will report. setting contenttype after onstartrequest has been fired or after open() is called will override the type determined by the channel. setting contenttype between the time that asyncopen() is called and the time when onstartrequest is fired has undefined behavior at this time. the value of the contenttype attribute is a lowercase string. a value assigned to this attribute will be parsed and normalized as follows: any parameters (delimited with a ';') will be stripped. if a charset para...
...er onstartrequest/onstoprequest pair, each pair for a different request). load_initial_document_uri 19 set (for example by the docshell) to indicate whether or not the channel corresponds to an initial document uri load (for example link click). load_targeted 20 set (for example by the uriloader) to indicate whether or not the end consumer for this load has been determined. load_call_content_sniffers 21 if this flag is set, the channel should call the content sniffers as described in netwerk/build/nsnetcid.h about ns_content_sniffer_category. see nsicontentsniffer [en-us] note: channels may ignore this flag; however, new channel implementations should only do so with good reason. load_classify_uri 22 this flag tells the...
nsIContentPrefService2
ctly, like "example.com", or as full urls, like "http://example.com/foo/bar". in the latter case the api extracts the full domain from the url, so if you specify "http://foo.bar.example.com/baz", the domain is taken to be "foo.bar.example.com", not "example.com". private-browsing context parameters many methods also accept a "context" parameter. this parameter relates to private browsing and determines the kind of storage that a method uses, either the usual permanent storage or temporary storage set() aside for private browsing sessions. pass null to unconditionally use permanent storage. pass an nsiloadcontext to use storage appropriate to the context's useprivatebrowsing attribute: if useprivatebrowsing is true, temporary private-browsing storage is used, and otherwise permanent storage is...
...eference with the given domain and name. in addition to caching preference values, the cache also keeps track of preferences that are known not to exist. if the preference is known not to exist, the value attribute of the returned object will be undefined (nsidatatype.vtype_void()). if the preference is neither cached nor known not to exist, then null is returned, and get() must be called to determine whether the preference exists. nsicontentpref getcachedbydomainandname( in astring domain, in astring name, in nsiloadcontext context ); parameters domain the preference's domain. name the preference's name. context the private-browsing context, if any. return value the preference, or null if no such preference is known to exist. getcachedbysubd...
nsICrashReporter
nctionality. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void annotatecrashreport(in acstring key, in acstring data); void appendappnotestocrashreport(in acstring data); void appendobjcexceptioninfotoappnotes(in voidptr aexception); native code only! void writeminidumpforexception(in voidptr aexceptioninfo); native code only! attributes attribute type description enabled boolean enable or disable the crashreporter at runtime. minidumppath nsilocalfile get or set the path on the local system to which minidumps will be written when a crash happens. exceptions thrown ns_error_not_initialized if crash reporting is not initialized. serverurl ns...
...valid_arg if data contains invalid characters. the only invalid character is '\0'. ns_error_not_initialized if crash reporting not initialized. native code only!appendobjcexceptioninfotoappnotes append note containing an obj-c exception's info. void appendobjcexceptioninfotoappnotes( in voidptr aexception ); parameters aexception nsexception object to append note for. native code only!writeminidumpforexception write a minidump immediately, with the user-supplied exception information. this is implemented on windows only, because seh (structured exception handling) exists on windows only. void writeminidumpforexception( in voidptr aexceptioninfo ); parameters aexceptioninfo exception_info* provided by window's seh. ...
nsIDOMClientRect
introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) attributes attribute type description bottom float y-coordinate, relative to the viewport origin, of the bottom of the rectangle box. read only. height float height of the rectangle box (this is identical to bottom minus top). read only. left float x-coordinate, relative to the viewport origin, of the left of the rectangle box. read only. right float x-coordinate, relative to the viewport origin, of the right of the rectangle box. read only. top float y-coordinate, relative to the viewport origin, of the top of the rectangle box. read only. width float ...
...te, relative to the viewport origin, of the left of the rectangle box. read only. right float x-coordinate, relative to the viewport origin, of the right of the rectangle box. read only. top float y-coordinate, relative to the viewport origin, of the top of the rectangle box. read only. width float width of the rectangle box (this is identical to right minus left). read only. x float x-coordinate, relative to the viewport origin, of the left of the rectangle box. read only. y float y-coordinate, relative to the viewport origin, of the top of the rectangle box. read only. see also cssom view module : the clientrect interfacewd this object was renamed a few times: initial name was textrectangle, then clientr...
nsIDOMHTMLSourceElement
e address of the media resource. the value must be a valid url. this attribute must be present. note that dynamically manipulating this value after the page has loaded has no effect on the containing element; instead, change the src attribute of that element (audio or video) instead. ...
...its value must be a valid media query. example <video controls> <source src="foo.webm" type="video/webm; codecs=&quot;vp9, opus&quot;"> your browser does not support the <code>video</code> element. ...
nsIDOMSimpleGestureEvent
finger down, second finger down, second finger up, first finger up) on the input device. client coordinates contain the center pivot point of the action. (xxx not implemented on mac) default behavior: some operating systems support default behaviors for gesture events when they are not handled by the application. consumers should use event.preventdefault() to prevent default behavior when consuming events. method overview void initsimplegestureevent(in domstring typearg, in boolean canbubblearg, in boolean cancelablearg, in nsidomabstractview viewarg, in long detailarg, in long screenxarg, in long screenyarg, in long clientxarg, in long clientyarg, in boolean ctrlkeyarg, in boolean altkeyarg, in boolean shiftkeyarg, in boolean metakeyarg, in unsigned short buttonarg, in nsidomev...
...e mozrotategesture and mozmagnifygesture events, this indicates the total movement that occurred while the event was being processed. the value is specified in degrees for rotation events (where positive values indicate clockwise rotation and negative values indicate counter-clockwise rotation). for magnify gestures, the units are implementation-specific; however, positive values indicate zooming in, and negative values indicate zooming out. read only. note: on mac os x, the units used for magnification gestures by the underlying operating system api are not documented at this time; typical values appear to be in the range 0.0 to 100.0, but currently you can only rely on the value being either positive or negative. on windows, the units indicate the difference between the previous a...
nsIExternalHelperAppService
boolean applydecodingforextension( in autf8string aextension, in acstring aencodingtype ); parameters aextension the filename extension to check. aencodingtype the encoding type to check. return value tru...
.... the caller should pump data into the returned stream listener. when the onstoprequest is issued, the stream listener implementation will launch the helper app with this data. nsistreamlistener docontent( in acstring amimecontenttype, in nsirequest arequest, in nsiinterfacerequestor awindowcontext, in boolean aforcesave ); parameters amimecontenttype the content type of the incoming data. arequest the request corresponding to the incoming data. awindowcontext use nsiservicemanager.getinterface() to retrieve properties like the dom window or parent window; the service might need this in order to bring up dialogs. aforcesave true to always save this content to disk, regardless of nsimimeinfo and other such influences. return value a nsistreamlistener ...
nsIFTPChannel
netwerk/protocol/ftp/nsiftpchannel.idlscriptable please add a summary to this article. ...
... netwerk/protocol/ftp/nsiftpchannel.idlscriptable please add a summary to this article. ...
nsIFile
eferenced by this nsifile. if this nsifile does not reference a symbolic link, then the value of this attribute is undefined. the value of this attribute is the number of bytes corresponding to the data represented by the symbolic link. any meta data, such as a resource fork on the mac, is not included in the measurement of the file size. read only. followlinks prbool determines whether or not the nsifile will automatically resolve symbolic links. by default, this value is false on all non-unix systems. as of mozilla 1.7, this attribute is ignored on unix systems. lastmodifiedtime print64 this attribute exposes the time when the file referenced by this nsifile was last modified. the value of this attribute is milliseconds since midnight (00...
...ring-valued methods and attributes have two forms. the preferred form operates on utf-16 (unicode) encoded character strings. the alternate form operates on character strings encoded in the "native" multibyte character set. the native character encoding is defined as the single-byte character encoding used with the standard fopen function on the host system. the native character encoding is determined using platform specific methods. as of gecko 1.7, it is utf-8 on mac os x. on linux and other unix platforms, it is the value returned from nl_langinfo (codeset), which usually corresponds to the value of the lc_all, lc_ctype and lang environment variables (with the precedence the same as the order they're enumerated). on win32 platforms, it is the currently selected ansi codepage (specified by...
nsILivemarkService
k container doesn't have a valid feed uri, null will be returned or the nsiuri object returned will be the empty string. exceptions thrown ns_error_invalid_arg if the folder id isn't known or identifies a folder that isn't a livemark container. ns_error_malformed_uri if the site uri annotation has somehow been corrupted (and can't be turned into an nsiuri) getlivemarkidforfeeduri() determines whether the feed uri is a currently registered livemark. long long getlivemarkidforfeeduri( in nsiuri afeeduri ); parameters afeeduri feed uri to look for. return value the id of the livemark. getsiteuri() this method retrieves the uri of the website associated with a livemark container. nsiuri getsiteuri( in long long container ); parameters container the folder id of a ...
...iuri representing the uri of the website; if the livemark container doesn't have a valid site uri, null will be returned. exceptions thrown ns_error_invalid_arg if the folder id isn't known or identifies a folder that isn't a livemark container. ns_error_malformed_uri if the site uri annotation has somehow been corrupted (and can't be turned into an nsiuri) islivemark() this method determines whether the folder with the given folder id identifies a livemark container. boolean islivemark( in long long folder ); parameters folder a folder id. return value true if the given folder is a livemark folder, otherwise it returns false. exceptions thrown ns_error_invalid_arg if the folder id isn't known. reloadalllivemarks() this method reloads all livemark subscriptions, ...
nsIModule
boolean canunload( in nsicomponentmanager acompmgr ); parameters acompmgr the global component manager. return value indicates to the caller whether or not the component module can be unloaded. returning true is not a guarantee that the module will be unloaded. it constitues only willingness of the module to be unloaded. ...
...ue is not a guarantee that the module will be unloaded. it constitues only willingness of the module to be unloaded. it is very important to ensure that no outstanding references to the module's code/data exist before returning true. returning false guaratees that the module will not be unloaded. if the component module is native (that is, as part of a dll), then this method may be called to determine whether or not the dll may be unloaded from memory. note: as of gecko 1.7, native component modules are never unloaded. getclassobject() obtains a class object from a nsimodule for a given cid and iid pair. this class object can either be query to a nsifactory or a may be query to a nsiclassinfo. void getclassobject( in nsicomponentmanager acompmgr, in nscidref aclass, in nsiidref aiid, ...
Building an Account Manager Extension
mple@mozilla.org/content/am-devmo-account.xul. and the property file needs to be in chrome://example@mozilla.org/locale/am-devmo-account.properties. the xul file needs a page element as root element, with a special on load command. furthermore you should include the accountmanager.js script and accountmanage.css styles. it is common practice to use for the javascript of the new panel, the same naming as used for the xul. this means in our example, the javascript file should be located in chrome://example@mozilla.org/content/am-devmo-account.js. <?xml version="1.0" encoding="utf-8"?> <?xml-stylesheet href="chrome://messenger/skin/accountmanage.css" type="text/css"?> <page xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" onload="parent.onpanelloaded('am-devmo-acco...
...messenger/content/accountmanager.js"/> <script type="application/javascript" src="chrome://example@mozilla.org/content/am-devmo-account.js"/> <dialogheader title="devmo example panel"/> <description> this panel is only shown in imap accounts... </description> <vbox flex = "1"/> </page> as with the xul page, the content of the property file relies on a very strict naming. as our account manager extension is named "devmo-account", we are required to include a property named prefpanel-devmo-account. prefpanel-devmo-account=devmo demo panel step4: the new panel and javascript the javascript for an account manager panel needs to implement at least the following functions. these functions are invoked by the account manager. function onpreinit(account, accountval...
nsIMsgHeaderParser
the form name <address>. exceptions thrown missing exception missing description native code only!parseheaderaddresses given a string which contains a list of header addresses, parses it into their component names and mailboxes. the returned value is the number of addresses, or a negative error code; the names and addresses are returned into the provided pointers as consecutive null-terminated strings. it is up to the caller to free them. note that some of the strings may be zero-length. the caller may pass nsnull for charset and it will be interpreted as "us-ascii". either of the provided pointers may be null if the caller is not interested in those components. void parseheaderaddresses( in string line, out string names, out string addresses, out pruint32 numaddres...
...set and it will be interpreted as "us-ascii". either of the provided pointers may be null if the caller is not interested in those components. void parseheaderaddresses( in string line, out string names, out string addresses, out pruint32 numaddresses ); parameters line the header line to parse. names a string of the names in the header line. the names are separated by null-terminators. this param may be null if the caller does not want this part of the result. addresses a string of the addresses in the header line. the addresses are separated by null-terminators. this param may be null if the caller does not want this part of the result. numaddresses the number of addresses in the header. if this is negative, there has been an error parsing the header. exceptions th...
nsIMsgMessageService
objects that implements nsimsgmessageservice give the user top level routines related to messages like copying, displaying, attachment's manipulation, printing, streaming the message content to eml format string, etc. inherits from: nsisupports method overview void copymessage(in string asrcuri, in nsistreamlistener acopylistener, in boolean amovemessage, in nsiurllistener aurllistener, in nsimsgwindow amsgwindow, out nsiuri aurl); [noscript] void copymessages(in nsmsgkeyarrayptr keys, in nsimsgfolder srcfolder, in nsistreamlistener acopylistener, in boolean amovemessage, in nsiurllistener aurllistener, in nsimsgwindow amsgwindow, out nsiuri aurl); void displaymessage(in string amessageuri, in nsisupports adisplayconsumer, in nsimsgwindow amsgwindow, in n...
...ly, a stream listener listening to the message headers. the consumer has to be a stream listener and in your listener's ondataavailable method, you can write out the stream data to a local file or concatenate it to a string. aurllistener an nsiurllistener that is notified when url starts and stops, if we run a url. alocalonly whether data should be retrieved only from local caches. if streaming over the network is required and this is true, then an exception is thrown. this defaults to false. note if we're offline, then even if alocalonly is false, we won't stream over the network return the url that gets run, if any ismsginmemcache() determines whether a message is in the memory cache. local folders don't implement this. boolean ismsginmemcache(in nsiuri aurl, ...
nsIMsgProtocolInfo
senger/protocol/info;1?type=acct, where acct is the account type that are you are interested in. method overview long getdefaultserverport(in boolean issecure); attributes attribute type description candelete boolean true if an account of this type may be deleted. read only. canduplicate boolean unused. read only. cangetincomingmessages boolean true if junk ui actions should be enabled for the account type. read only. cangetmessages boolean true if "get messages" ui actions should be enabled for the account type. read only. canloginatstartup boolean true if the account type can perform biff during startup. read only. defaultdobiff boolean true if the biff should be enab...
...verport() returns the default port for a connection to a server of this account type. long getdefaultserverport( in boolean issecure ); parameters issecure whether or not the connection will be secure. return value the default port number for connections of this account type. remarks this is one of the interfaces that is required to create a new account type. see also nsimsgincomingserver ...
nsIMsgSearchCustomTerm
d; name /// name to display in term list. this should be localized. */ readonly attribute astring name; needsbody /// does this term need the message body? readonly attribute boolean needsbody; methods getenabled /** * is this custom term enabled? * * @param scope search scope (nsmsgsearchscope) * @param op search operator (nsmsgsearchop). if null, determine * if term is available for any operator. * * @return true if enabled */ boolean getenabled(in nsmsgsearchscopevalue scope, in nsmsgsearchopvalue op); getavailable /** * is this custom term available? * * @param scope search scope (nsmsgsearchscope) * @param op search operator (nsmsgsearc...
... if term is available for any operator. * * @return true if enabled */ boolean getenabled(in nsmsgsearchscopevalue scope, in nsmsgsearchopvalue op); getavailable /** * is this custom term available? * * @param scope search scope (nsmsgsearchscope) * @param op search operator (nsmsgsearchop). if null, determine * if term is available for any operator. * * @return true if available */ boolean getavailable(in nsmsgsearchscopevalue scope, in nsmsgsearchopvalue op); getavailableoperators /** * list the valid operators for this term. * * @param scope search scope (nsmsgsearchscope) * @param length object...
nsINavHistoryResult
vhistoryresultobserver aobserver, in boolean aownsweak); void removeobserver(in nsinavhistoryresultobserver aobserver); attributes attribute type description root nsinavhistorycontainerresultnode the root of the results. this container gives you access to all the results in the tree. note: keep in mind that you need to open containers for their results to be valid. when a result goes out of scope it will continue to observe changes till it is cycle collected. while the result waits to be collected it will stay in memory, and continue to update itself, potentially causing unwanted additional work. when you close the root node the result will stop observing changes, so it is good practic...
...sult. this value must be one of nsinavhistoryqueryoptions.sort_by_*. 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. suppressnotifications boolean if true, notifications are suppressed. this is used to prevent rapid flickering of changes when performing batch or temporary operations on the result structure. viewer nsinavhistoryresultviewer the viewer for this result. the viewer is responsible for actually updating the view object itself, as well as for handling events on the view. obsolete since gecko 2.0 methods addobserver() adds an observer for changes that occur on the result. void addobserver( in nsi...
nsIParentalControlsService
as blocked or false if it was allowed. asource the uri source of the subject content. atarget optional the location to which the content was saved if it was not blocked. requesturioverride() requests that a blocked uri be allowed through parental control filters. this method may block while the operating system presents user interface to handle the override request (such as an "enter an administrator's password" dialog box). boolean requesturioverride( in nsiuri atarget, in nsiinterfacerequestor awindowcontext optional ); parameters atarget the uri to be overridden. awindowcontext optional the window generating the event. return value true if the block was successfully overridden, otherwise false. requesturioverrides() requests that a set of uris be allowed through t...
...get the uri to be overridden. awindowcontext optional the window generating the event. return value true if the block was successfully overridden, otherwise false. requesturioverrides() requests that a set of uris be allowed through the parental control filters. this method may block while the operating system presents user interface to handle the override request (such as an "enter an administrator's password" dialog box). boolean requesturioverrides( in nsiarray atargets, in nsiinterfacerequestor awindowcontext optional ); parameters atargets an array of nsiuri objects, each representing a uri for which an override is desired. awindowcontext optional the window generating the event. return value true if the block was successfully overridden, otherwise false. ...
nsIPrintingPrompt
historically, platform toolkits with native dialogs have implemented them in the gfx layer usually they were displayed when a new devicecontextspec specific to that platform was created. windows: the gfx layer no longer supports default toolkit behavior for displaying the native print dialog. if an embedder implemented service returns any error code (other than ns_error_abort) printing will terminate. returning ns_ok assumes that the printsettings object was correctly filled in and if it does not have valid fields for printer name, and so on. it may also terminate. defaults for platform service: showprintdialog - displays a native dialog showpagesetup() - displays a xul dialog showprogress() - displays a xul dialog summary for windows embedders: stated once again: there is no "...
...ack ns_error_not_implemented for any of the others. for the print dialog: you may stub out this service by having all the methods return ns_error_not_implemented. you can then fly you own dialog and then properly fill in the printsettings object before calling nsiwebbrowserprint's print method. if you stub out this service you must set "printsilent" to true, if you do not, printing will terminate and an error dialog will be displayed. mac: the gfx layer still supports default toolkit behavior for displaying the print dialog. if an embedder implemented service returns ns_error_not_implemented for "showprintdialog" the toolkit will display the native print dialog. defaults for platform service: mac os x: showprintdialog - displays a native dialog showpagesetup() - displays ...
nsIProtocolProxyService
methods resolve() deprecated since gecko 18 this method has been removed in firefox 18. use resolveasync instead previous doc this method returns a nsiproxyinfo instance that identifies a proxy to be used for loading the given uri. otherwise, this method returns null indicating that a direct connection should be used. if this proxy is unavailable, getfailoverforproxy() may be called to determine the correct secondary proxy to be used. if the protocol handler for the given uri supports nsiproxiedprotocolhandler, then the nsiproxyinfo instance returned from resolve may be passed to the nsiproxiedprotocolhandler.newproxiedchannel() method to create a nsichannel to the given uri that uses the specified proxy. however, if the nsiproxyinfo type is "http", then it means that the given uri ...
... used to tune the delay before this proxy is used again. the proxy that was unavailable. return value an nsiproxyinfo object or null for a direct connection. exceptions thrown ns_error_not_available if there is no alternate proxy available. registerfilter() this method may be used to register a proxy filter instance. each proxy filter is registered with an associated position that determines the order in which the filters are applied (starting from position 0). when resolve/asyncresolve is called, it generates a list of proxies for the given uri, and then it applies the proxy filters. the filters have the opportunity to modify the list of proxies. if two filters register for the same position, then the filters will be visited in the order in which they were registered. if the filt...
nsIRadioInterfaceLayer
al read only. obsolete since gecko 13.0 microphonemuted bool radiostate jsval read only. ...
... only. ...
nsISelection2
tically. a value of 0 means the frame's upper edge is aligned with the top edge of the visible area. a value of 100 means the frame's bottom edge is aligned with the bottom edge of the visible area. for values in between, the point "avpercent" down the frame is placed at the point "avpercent" down the visible area. a value of 50 centers the frame vertically. a value of -1 means move the frame the minimum amount necessary in order for the entire frame to be visible vertically (if possible). ahpercent how to align the frame horizontally. a value of 0 means the frame's left edge is aligned with the left edge of the visible area. a value of 100 means the frame's right edge is aligned with the right edge of the visible area. for values in between, the point "ahpercent" across the frame is placed...
...ly. a value of 0 means the frame's left edge is aligned with the left edge of the visible area. a value of 100 means the frame's right edge is aligned with the right edge of the visible area. for values in between, the point "ahpercent" across the frame is placed at the point "ahpercent" across the visible area. a value of 50 centers the frame horizontally . a value of -1 means move the frame the minimum amount necessary in order for the entire frame to be visible horizontally (if possible). see also nsiselectionprivate ...
nsISelectionPrivate
tically. a value of 0 means the frame's upper edge is aligned with the top edge of the visible area. a value of 100 means the frame's bottom edge is aligned with the bottom edge of the visible area. for values in between, the point "avpercent" down the frame is placed at the point "avpercent" down the visible area. a value of 50 centers the frame vertically. a value of -1 means move the frame the minimum amount necessary in order for the entire frame to be visible vertically (if possible). ahpercent how to align the frame horizontally. a value of 0 means the frame's left edge is aligned with the left edge of the visible area. a value of 100 means the frame's right edge is aligned with the right edge of the visible area. for values in between, the point "ahpercent" across the frame is placed...
...ly. a value of 0 means the frame's left edge is aligned with the left edge of the visible area. a value of 100 means the frame's right edge is aligned with the right edge of the visible area. for values in between, the point "ahpercent" across the frame is placed at the point "ahpercent" across the visible area. a value of 50 centers the frame horizontally . a value of -1 means move the frame the minimum amount necessary in order for the entire frame to be visible horizontally (if possible). native code only!setancestorlimiter void setancestorlimiter( in nsicontent acontent ); parameters acontent native code only!setpresshell internal utility method to set the pres shell on a newly created selection. void setpresshell( in nsipresshell apresshell ); parameters apressh...
nsIServerSocket
netwerk/base/public/nsiserversocket.idlscriptable please add a summary to this article. last changed in gecko 1.6 inherits from: nsisupports implemented by: @mozilla.org/network/server-socket;1. ...
... native code only!getaddress returns the address to which this server socket is bound. since a server socket may be bound to multiple network devices, this address may not necessarily be specific to a single network device. in the case of an ip socket, the ip address field would be zeroed out to indicate a server socket bound to all network devices. therefore, this method cannot be used to determine the ip address of the local system. see nsidnsservice.myhostname() if this is what you need. prnetaddr getaddress(); parameters none. return value the network address to which the socket is bound. init() initializes a server socket. void init( in long aport, in boolean aloopbackonly, in long abacklog ); parameters aport the port of the server socket. pass -1 to indicate no pr...
nsITaskbarProgress
(firefox 3.6 / thunderbird 3.1 / fennec 1.0) method overview void setprogressstate(in nstaskbarprogressstate state, in unsigned long long currentvalue optional, in unsigned long long maxvalue optional); constants constant value description state_no_progress 0 stop displaying progress on the taskbar button. this should be used when the operation is complete or canceled. state_indeterminate 1 display a cycling, indeterminate progress bar. state_normal 2 display a determinate, normal progress bar. state_error 3 display a determinate, error progress bar. state_paused 4 display a determinate progress bar indicating that the operation has paused. methods setprogressstate() sets the taskbar progress state and value for this window. the currentvalue and maxvalue parameters are...
... see also nsiwintaskbar windows 7 taskbar apis ...
nsITextInputProcessor
evel. nsidomwindowutils has provided the methods which dispatched keyboard events and composition events almost directly. therefore they sometimes caused impossible scenarios in automated tests (what's tested with such events?) and js-ime and/or js-keyboard on firefox os or add-ons may dispatch events with wrong rules. for solving that issue, methods of this interface have been designed for performing a key operation or representing a change of composition state. for example, the implementation of this interface manages modifier state and composition state, initializes dom events from minimum information, and doesn't dispatch some events if they are not necessary. this means that even when gecko changes the dom event behavior, it may not be necessary that the users of this interface need to ...
...nt = new keyboardevent("", { key: "convert", code: "convert" }); tip.flushpendingcomposition(convertkeyevent); // this means that the composition is committed by a keypress of "enter" key. var enterkeyevent = new keyboardevent("", { key: "enter", code: "enter" }); tip.commitcomposition(enterkeyevent); note that specifying keyboard event may not be dispatched during composition due to conforming to the specification of dom level 3 events. however, it's the best for every textinputprocessor user to specify keyboardevent every time because when gecko will change the behavior of keyboard events during composition, textinputprocessor must not need to change for the new behavior in most cases. method overview void appendclausetopendingcomposition(in unsigned long alength, in unsig...
nsITransferable
.0 / thunderbird 13.0 / seamonkey 2.10) implemented by: @mozilla.org/widget/transferable;1. to create an instance, use: var transferable = components.classes["@mozilla.org/widget/transferable;1"] .createinstance(components.interfaces.nsitransferable); it's important to note that a flavor, which specifies a type of data the transferable supports, is represented by a null-terminated string indicating the mime type of the format supported by the flavor. method overview void adddataflavor( in string adataflavor ); nsisupportsarray flavorstransferablecanexport( ); nsisupportsarray flavorstransferablecanimport( ); void getanytransferdata( out string aflavor, out nsisupports adata, out unsigned long adatalen ); void gettransferda...
...ext); in c++ callers, if you have the corresponding document, you can just call nsidocument.getloadcontext() to get to the load context object. islargedataset() returns true if the data is large. boolean islargedataset(); parameters none. return value true if the data is large; otherwise, the result is false. removedataflavor() removes the data flavor matching the given one (as determined by a string comparison), along with the corresponding data. void removedataflavor( in string adataflavor ); parameters adataflavor the data flavor to remove. settransferdata() sets the data in the transferable with the specified flavor. the transferable maintains its own copy of the data, so you can safely discard the original after making this call, if you wish. void settransferda...
nsIUpdate
t(in unsigned long index); nsidomelement serialize(in nsidomdocument updates); attributes attribute type description appversion astring the application version of this update. billboardurl astring the url to a page that is typically localized to display in the update prompt. buildid astring the build id of this update. this is used to identify a particular build, down to the hour, minute, and second of its creation. this lets the system differentiate between several nightly builds with the same version, for example. channel astring the channel used to retrieve this update from the update service. detailsurl astring the url to a page which offers details about the content of this update. ideally, this page is not the release notes but some other page that summarizes the di...
.... "applying" the update is in the process of being applied. "succeeded" the update has been installed successfully. "download-failed" the update failed to be downloaded. "failed" installing the update failed. read only. statustext astring an optional message associated with the update. type astring the type of patch represented by the object: "major" a major new version of the application. "minor" a minor update, such as a security update. version astring the application version of the update.obsolete since gecko 2.0 methods getpatchat() retrieves a patch. nsiupdatepatch getpatchat( in unsigned long index ); parameters index the index of the patch to retrieve. return value an nsiupdatepatch object describing the specified patch. serialize() serializes the update object into ...
nsIWebBrowserPersist
e 1 only use cached data (could result in failure if data is not cached). persist_flags_bypass_cache 2 bypass the cached data. persist_flags_ignore_redirected_data 4 ignore any redirected data (usually adverts). persist_flags_ignore_iframes 8 ignore iframe content (usually adverts). persist_flags_no_conversion 16 do not run the incoming data through a content converter for example to decompress it. persist_flags_replace_existing_files 32 replace existing files on the disk (use with due diligence!) persist_flags_no_base_tag_modifications 64 don't modify or add base tags. persist_flags_fixup_original_dom 128 make changes to original dom rather than cloning nodes. persist_flags...
...l_on_broken_links 4096 fail on broken in-line links. persist_flags_cleanup_on_failure 8192 automatically cleanup after a failed or cancelled operation, deleting all created files and directories. this flag does nothing for failed upload operations to remote servers. persist_flags_autodetect_apply_conversion 16384 let the webbrowserpersist decide whether the incoming data is encoded and whether it needs to go through a content converter, for example to decompress it. persist_flags_append_to_file 32768 append the downloaded data to the target file. this can only be used when persisting to a local file. persist_flags_force_allow_cookies 65536 force relevant cookies to be sent with this load even if normally they wouldn't be. ...
nsIWebNavigation
docshell/base/nsiwebnavigation.idlscriptable defines an interface for navigating the web. it provides methods and attributes to direct an object to navigate to a new location, stop or restart an in process load, or determine where the object has previously gone. inherits from: nsisupports last changed in gecko 1.9 (firefox 3) this interface is implemented by the following components: * @mozilla.org/browser/shistory-internal;1 * @mozilla.org/browser/shistory;1 * @mozilla.org/embedding/browser/nswebbrowser;1 * @mozilla.org/docshell;1 gecko 1.9.2 note in gecko 1.9.2 (firefox 3.6), the @mozilla.org/webshell;1 component no longer exists; you need to use @mozilla.org/docshell;1 instead. method overview void goback void goforward void gotoind...
.... this parameter may be null. headers if the uri corresponds to a http request, then any http headers contained in this stream are set on the http request. the http header stream is formatted as: ( header \r\n )* this parameter may be null. reload() tells the object to reload the current page. there may be cases where the user will be asked to confirm the reload (for example, when it is determined that the request is non-idempotent). void reload( unsigned long reloadflags ); parameters reloadflags flags modifying load behaviour. this parameter is a bitwise combination of the load flags defined above. (undefined bits are reserved for future use.) generally you will pass load_flags_none for this parameter. stop() stops a load of a uri. void stop( unsigned long stopflags ); ...
nsIWebNavigationInfo
d by istypesupported() to indicate that a type is supported via an npapi ("netscape 4 api") plug-in. this is not the value returned for "xpcom plug-ins". other 1 << 15 note: other return types may be added here in the future as they become relevant. returned by istypesupported() to indicate that a type is supported via some other means. methods istypesupported() determines whether or not the specified mime type is supported by the given nsiwebnavigation object. this lets you determine whether a mime type can be displayed as-is inside a browser, or if the browser will instead forward handling of the data to a plug-in or an external helper application. note: this method may cause plug-ins to be rescanned in order to ensure they are properly registered for the typ...
...ly registered for the types they support. unsigned long istypesupported( in acstring atype, in nsiwebnavigation awebnav ); parameters atype the mime type to check. awebnav the nsiwebnavigation object on which to check for compatibility. 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). return value returns one of the support type constants, indicating whether or not the specified mime type is supported, and in what form that support exists. example let webnavigationinfo_service = components.classes["@mozilla.org/webnavigation-info;1"] ...
NS_CStringCloneData
on failure it returns nsnull. the resulting buffer may be freed by calling nsmemory::free. history this function was frozen for mozilla 1.7. ...
...on failure it returns nsnull. the resulting buffer may be freed by calling nsmemory::free. history this function was frozen for mozilla 1.7. ...
NS_CStringGetMutableData
a nsacstring instance to modify. adatalength [in] the number of characters to resize the string's internal buffer to or pr_uint32_max to return the buffer as-is. adata [out] upon return, if the function was successful, then *adata references the string's internal buffer. return values this function returns the number of characters contained in the string's internal buffer (excluding any null-terminator). this value will be zero if the function failed to resize its internal buffer to the size requested. remarks this function provides mutable access to a string's internal buffer. it returns a pointer to the first element of an array of characters that may be modified in-place. the returned pointer remains valid until the string object is passed to some other string function. this function doe...
...zero if the function failed to resize its internal buffer to the size requested. remarks this function provides mutable access to a string's internal buffer. it returns a pointer to the first element of an array of characters that may be modified in-place. the returned pointer remains valid until the string object is passed to some other string function. this function does not necessarily null-terminate astring's internal buffer after resizing it. that behavior depends on the implementation of astring. if astring is a reference to a nscstringcontainer, then its data will be null-terminated by this function. the caller is not responsible for writing a null-terminator. example // convert any uppercase ascii letters to lowercase void tolowercase(nscstring &str) { char *iter; pruint32 len = n...
NS_StringCloneData
on failure it returns nsnull. the resulting buffer may be freed by calling nsmemory::free. history this function was frozen for mozilla 1.7. ...
...on failure it returns nsnull. the resulting buffer may be freed by calling nsmemory::free. history this function was frozen for mozilla 1.7. ...
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. ns_cstringappenddatathe ns_cstringappenddata function appends data to the existing value of a nsacstring instance. ...
...s internal buffer. this is a low-level api.ns_cstringtoutf16the ns_cstringtoutf16 function converts the value of a nsacstring instance to utf-16 and stores the result in a nsastring instance. ns_stringappenddatathe ns_stringappenddata function appends data to the existing value of a nsastring instance. this is a low-level api.ns_stringclonedatathe ns_stringclonedata function returns a null-terminated, heap allocated copy of the string's internal buffer.ns_stringcontainerfinishthe ns_stringcontainerfinish function releases any memory allocated by a nsstringcontainer instance. this is a low-level api.ns_stringcontainerinitthe ns_stringcontainerinit function initializes a nsstringcontainer instance for use as a nsastring. this is a low-level api.ns_stringcopythe ns_stringcopy function copies...
nsMsgViewCommandType
last changed in gecko 1.9 (firefox 3) constants name value description markmessagesread 0 marks the selected messages as read. ...
...lder() to select the destination folder. selectall 15 select all messages. downloadselectedforoffline 16 download the selected messages for offline. downloadflaggedforoffline 17 download all flagged messages for offline. selectthread 18 select the entire thread. selectflagged 19 select all flagged messages. cmdrequiringmsgbody 20 used with nsimsgdbview.getcommandstatus() to determine if commands requiring the message body (i.e. reload or print preview) are available. label0 21 attach a label to the selected messages. label1 22 attach a label to the selected messages. label2 23 attach a label to the selected messages. label3 24 attach a label to the selected messages. label4 25 attach a label to the selected messages. label5 26 attach a label to the selected...
Setting HTTP request headers
r that we added is named x-hello and the value of this http request header is world. note: if you are making up your own http header, you must put a x- in front of the name. (in our example, our made up http header is x-hello and not hello because we correctly added the x- in front of our name.) no longer the case: http://tools.ietf.org/html/rfc6648 notifications the question that may be coming to your mind right now is, how do you get the nsihttpchannel when an http request is made. in the case your code initiates the request, you probably already have one. trapping other requests is done with notifications, which are a lot like events or signals found in other languages and frameworks. in particular, to get the nsihttpchannel just before the http request is made we need to observe th...
...ions, which are a lot like events or signals found in other languages and frameworks. in particular, to get the nsihttpchannel just before the http request is made we need to observe the "http-on-modify-request" topic. (and yes, "http-on-modify-request" is a string.) note: there are many topics, besides just "http-on-modify-request", that you can get notifications about, for example "http-on-examine-response" and "xpcom-shutdown". you can also make up your own topics and send out your own notifications. for more information about notifications framework and a list of common notification topics, see observer notifications. observers to get notified about some topic (like "http-on-modify-request") we need to create an observer. an observer is a component implementing nsiobserver interface. ...
Frequently Asked Questions
r which code pattern you use to solve this problem, you should comment it, e.g., // warning: this getter doesn't addref() its result. if the getter returns the new pointer as its function result, no worries, general does nscomptr bloat the code? are nscomptrs fast? can i use them in tight loops? bibliography web resources nscomptr.h, and nscomptr.cpp are the source to nscomptr. you can examine the source to nscomptr online using (the wonderful) lxr. exploring this code is not an adventure for the faint of heart. some com ownership guidelines. interface pointers considered harmful by don box originally appeared in the september 1995 issue of "the c++ report". com smart pointers even more harmful by don box is a follow-up article that originally appeared in the february 1996 issue of...
... faint of heart. some com ownership guidelines. interface pointers considered harmful by don box originally appeared in the september 1995 issue of "the c++ report". com smart pointers even more harmful by don box is a follow-up article that originally appeared in the february 1996 issue of "the c++ report". books essential com by don box. effective com by don box, et al. the c++ programming language (3rd edition) by bjarne stroustrup. effective c++ (2nd edition): 50 specific ways to improve your programs and designs by scott meyers. more effective c++ : 35 new ways to improve your programs and designs by scott meyers. effective c++ cd: 85 specific ways to improve your programs and designs by scott meyers. people don box is a smart guy who has been writing about com programm...
Reference Manual
ect for its nsifoo interface. in debug builds, if you subvert this invariant with one of the assignment forms that doesn't call queryinterface, nscomptr will assert at runtime in the bad assignment. // given two un-related interfaces |nsifoo| and |nsibar|... nsibar* bar = ...; // ... nscomptr<nsifoo> foo = bar; // ns_assertion: "queryinterface needed" // ...even assuming you can get the line to compile // (either by casting, or because the types are related by c ) this invariant is relaxed for nscomptr<nsisupports>. like nsisupports* (or even void*), people generally use nscomptr<nsisupports> to mean "any xpcom interface." it would be annoying if nscomptr forced you to queryinterface to the xpcom-correct nsisupports within an object in place...
..., especially in the face of work done by queryinterface, and the work that may be done by release. in all other cases, nscomptr does only the work you would have done by hand. the bulk of the work for which an nscomptr is used is dereferencing with operator->, just as it is with a primitive pointer. on every platform, this operation generates the exact same code, and takes the same time, as performing this operation on a raw xpcom interface pointer. the destructor, which corresponds to client code calling release against a raw xpcom interface pointer, is factored, requiring the extra time required to invoke a subroutine call, though this is balanced against the cost already present in both cases of calling release which may, in turn, invoke delete and the referents destructor. all nscomptrs c...
XPCOM ABI
pcom component consists of an .xpt file which fits all platforms and a dll (.dll on windows, .so on unix) which is platform-specific and has a certain abi. only applications which use this abi could use this xpcom component. to put it simply, an xpcom component built for a specific abi would only be compatible with firefox, thunderbird or other xulrunner application built for the same abi. ...
...c subdirectory. at extension installation time, the application will choose the most fitting component build for its own abi. if no such build is found, the extension will be deemed incompatible and the application will refuse to install it. if the application doesn't have an xpcom abi string (due to the fact that either its cpu architecture or c++ compiler are unknown, as described in the abi naming section), you should use the operating system's name (without appending the xpcom abi) as the platform name in the install manifest etc. ...
Xptcall Porting Status
dl@nycap.rr.com> glen writes: i am attaching a patch which contains my linux alpha xptcall code. it passes testxptcinvoke and testxpc on my machine which runs kernel 2.2.7, glibc 2.1.1, and egcs 1.1.2. i have not tested it with older gnu compilers such as gcc 2.8.x. from looking at the linux x86 code, i gather that the vtable layout is a little different for those compilers and the code will need minor modifications in order to work properly. i am not sure how much of the code can be used for openvms alpha and/or digital unix. currently the code is dependent on the g++ name mangling convention and a few gnu extensions so i'm not sure how useful it will be for the other systems. hopefully the comments in the code are detailed enough to help people attempting a port. <font color="white">don...
...alpha and/or digital unix. currently the code is dependent on the g++ name mangling convention and a few gnu extensions so i'm not sure how useful it will be for the other systems. hopefully the comments in the code are detailed enough to help people attempting a port. <font color="white">done</font> sunos x86 arthur jones <aljones@lbl.gov> <font color="red">?</font> philip pokorny <ppokorny@mindspring.com> the word i hear is that this is working and done <font color="white">done</font> hp-ux thomas wang <wang@cup.hp.com> mike gleeson <mgleeson1@netscape.com> i hear that this code is checked in and working. though, there is some doubt - see bug #17997 <font color="white">done</font> aix ppc jim dunn <jdunn@netscape.com> philip k. warren writes: we have gone through several releas...
XPCOM
pers trying to support multiple gecko versions (firefox 2 and 3, for example).creating a python xpcom componentcreating applications with mozilla already provides a tutorial for making a simple javascript or c++ component (implementing the nsisimple interface). 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. add-ons can (and should) be identified with ids of the form extensionname@organization.tld since firefox 1.5.generic factorymost xpcom factories can be very simple. rick potts wrote a...
...must be a fairly self-contained library, so as not to encumber clients with any unnecessary external dependencies.xpcom thread synchronizationxpcom thread synchronization primitives have the same semantics as those in nspr, and each method of these synchronization objects (e.g. mutex::lock()) has a matching function in nspr (pr_lock()). this is no accident, as mozilla:: primitives are merely bare-minimum wrappers around nspr's.xptcall faqxptcall is a small low level xpcom method call library. it is implemented using platform specific c/c++ and assembly language code. it is used to facilitate cross language and cross thread method calls. porting this code is required in order to make mozilla run on any given platform.xptcall porting guideoriginal author: john bandhauer, 31 may 1999.xptcall por...
XPIDL
, on attribute declared 'attribute type foo;' is syntactic sugar for the declaration of two methods 'type getfoo();' and 'void setfoo(in type foo);'. if foo were declared readonly, the latter method would not be present. attributes support all of the properties of methods with the exception of optional_argc, as this does not make sense for attributes. there are some special rules for attribute naming. as a result of vtable munging by the msvc++ compiler, an attribute with the name `iid' is forbidden. in addition, any attribute whose name matches the regex /^[a-z]{2,3}i[a-z][a-z]/ is emitted with a warning, as its name looks like an nsiinterface or a moziinterface declaration. also like methods, if the first character of an attribute is lowercase in idl, it is made uppercase in native code on...
...r, the capitalization is not applied when using binaryname with attributes; i.e., [binaryname(foo)] readonly attribute quux bar; becomes getfoo(quux**) in native code. attributes named 'iid' and methods named 'getiid' are forbidden, although this is checked before binaryname conversion. the implicit_jscontext and optional_argc parameters are properties which help native code implementations determine how the call was made from script. if implicit_jscontext is present on a method, then an additional jscontext *cx parameter is added just after the regular list which receives the context of the caller. if optional_argc is present, then an additional uint8_t _argc method is added at the end which receives the number of optional arguments that were actually used (obviously, you need to have an op...
Xray vision
sed, the attacker can take over the user's computer. javascript loaded from normal web pages is called content code. because this code is being loaded from arbitrary web pages, it is regarded as untrusted and potentially hostile, both to other websites and to the user. as well as these two levels of privilege, chrome code can create sandboxes. the security principal defined for the sandbox determines its privilege level. if an expanded principal is used, the sandbox is granted certain privileges over content code and is protected from direct access by content code. the security machinery in gecko ensures that there's asymmetric access between code at different privilege levels: so for example, content code can't access objects created by chrome code, but chrome code can access objects cre...
... script has created a property on an object instance that shadows a property on the prototype, the shadowing property is not visible in the xray second, we want to prevent the chrome code from running content code, so functions and accessor properties of the object are not visible in the xray. these rules are demonstrated in the script below, which evaluates a script in a sandbox, then examines the object attached to the sandbox. to test out examples like this, you can use the scratchpad in browser context for the code snippet, and the browser console to see the expected output. because code running in scratchpad's browser context has chrome privileges, any time you use it to run code, you need to understand exactly what the code is doing. that includes the code samples in this art...
Address book sync client design
warning: the content of this article may be out of date. it was imported from mozilla.org and last updated in 2000. by richard h. pizzarro <rhp@netscape.com> contents overview client side sync logic public interfaces overview there is an component available in the mozilla tree for performing synchronization operations against a server based address book. the general architecture for the sync component is the following: mozilla ui ab sync logic mork ab database sync protocol encoding sync protocol decoding http "post" api ...
...the static information that is held on the client for address book sync operations is stored in a file called absync.dat which is located in the root directory of the users profile information. // // the client keeps a sync mapping table which holds the following: // // serverrecordid - unique id for a record provided ...
Autoconfiguration in Thunderbird
by setting up a web server at autoconfig.<domain>, which simply returns a static xml file with the configuration, as described below. for more complicated setups, for example when the login name does not appear in the email address, the xml file can also be generated by the isp. in such complicated cases, this is the only way to allow an automatic setup. configuration file on harddisk local administrators may place a configuration file in the thunderbird installation folder. this is mainly intended for companies who install thunderbird on their employees' computers and want to enable easy account setup without having to set up a configuration server. this method is not practical for other use cases, because it is difficult to update the configuration file. guessing if all other mechani...
...et utf-8 (esp. if there are any non-ascii-characters). if you like to use name-based virtual hosts you probably don't want to setup the autoconfig subdomain for every domain of your customers. you can add a rewriterule in the default virtual host (on debian /etc/apache2/sites-enabled/000-default) to match all autoconfig.* subdomains: <virtualhost *:80> #must be the first virtual host serveradmin webmaster@hoster.com servername www documentroot /var/www rewriteengine on rewritecond %{http_host} ^autoconfig\. [nc] rewriterule ^/(.*) http://autoconfig.hoster.com/$1 [l,r=301,ne] #... </virtualhost> <virtualhost *:80> documentroot /var/www/autoconfig/ servername autoconfig.hoster.com <directory /var/www/autoconfig> order allow,deny allow from all </directory> <...
Creating a gloda message query
js: tags: a list of the nsimsgtags applied to this message. starred: a boolean indicating whether this message is starred/flagged or not. read: a boolean indicating whether this message is read or not. want a glodamessage when you already have an nsimsgdbhdr? gloda.getmessagecollectionforheader(amsrhdr, alistener, adata) returns a collection (with your provided listener and data). ...
...stener and data). keep in mind that gloda is not infallible and it's conceivable that your collection may end up with no messages in it. have a glodamessage and want the rest of the messages in the conversation? glodamessage.conversation.getmessagescollection(alistener, adata) returns a collection that should contain all of the messages gloda knows about that belong to the conversation. keep in mind that duplicate messages can and will appear. (a duplicate message is a message with the same message-id header.) ...
Adding items to the Folder Pane
this tutorial examines how to add items to an existing folder pane view. the result is a javascript file that will add a "numbers" container to the end of thunderbird's "all folders" mode. that container will have 3 child-items, the numbers 1, 2, and 3. clicking on those items will display the number in the main viewing pane of thunderbird. first, some necessary background on how the folder pane constructs the data it displays. the folder pane tracks modifications to a user's folders and accounts. each time the folder pane determines that it is necessary to invalidate all its data (because of too many changes, or more commonly because the folder pane's "mode" (aka view) has changed), a "rebuild" occurs. when this happens, the folder pane consults the map-generator for the current mode, and ...
...of folder-tree-items. each item in this array satisfies the following interface: id (attribute) a unique string for this object. must persist over sessions text (attribute) the text to display in the tree level (attribute) the level in the tree to display the item at open (rw, attribute) whether or not this container is open children (attribute) an array of child items also conforming to this spec getproperties (function) a call from getrowproperties or getcellproperties for this item will be passed into this function command (function) this function will be called when the item is double-clicked for our example extension, two different types of folder-tree-items will be defined. first, our "numbers" container looks like this: let containerrow = { _numbers:...
Building a Thunderbird extension 6: Adding JavaScript
erbird window. depending on the installed theme the result will look something like this: modify xul elements with javascript save the following javascript code into the content/ folder next to your myhelloworld.xul file and name it overlay.js. window.addeventlistener("load", function(e) { startup(); }, false); window.setinterval( function() { startup(); }, 60000); //update date every minute function startup() { var mypanel = document.getelementbyid("my-panel"); var date = new date(); var day = date.getday(); var datestring = date.getfullyear() + "." + (date.getmonth()+1) + "." + date.getdate(); mypanel.label = "date: " + datestring; } the first part registers a new event listener that will be executed automatically when thunderbird loads. the event listener then calls our ...
...because the month is zero-based we also need to add one to the month. finally the label of our panel is set to "date: " and concatenated with the date string that contains the formatted date. we use the function window.setinterval to update the date in case thunderbird is left running for more than one day. this allows us to call the startup function repeatedly with an interval of 60000ms (every minute). further documentation more functions for the dom objects are listed on: dom/window (api reference for the window object) dom/document (api reference for the document object) gecko dom reference (overview of all dom objects in gecko) you may also find the javascript cheat sheet very useful. « previousnext » ...
Access Window
...
...dow object is a reference of the application window or of one of it is a tabs. register a timer window.setinterval( function() { alert('foobar'); }, 60000); //execute the function once very minute if you periodically need to perform a certain action then you can use the setinterval function, it will then call this function every x milliseconds, in this case every 60000ms or one minute. ...
Theme Packaging
le install.rdf file <?xml version="1.0"?> <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest"> <em:id>{18b64b56-d42f-428d-a88c-baa413bc413f}</em:id> <em:version>1.0</em:version> <em:type>4</em:type> <!-- target application this extension can install into, with minimum and maximum supported versions. --> <em:targetapplication> <description> <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> <em:minversion>0.8</em:minversion> <em:maxversion>0.9</em:maxversion> </description> </em:targetapplication> <!-- front end metadata --> <em:name>new theme 1</em:name> <em:description>a test theme for thunderbir...
... </description> </rdf> the following are some common target application guids that you can use in your targetapplication properties: thunderbird {3550f703-e582-4d05-9a08-453d09bdfdc6} seamonkey {92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a} pale moon {8de7fcbb-c55c-4fbe-bfc5-fc555c87dbc4} official references for toolkit api official references. do not add to this list without contacting benjamin smedberg. note that this page is included from the pages listed below. so: don't add breadcrumbs! structure of an installable bundle: describes the common structure of installable bundles, including extensions, themes, and xulrunner applications extension packaging: specific information about how to package extensions theme packaging: specific information about how to package themes multiple...
customDBHeaders Preference
is stored and edit the user.js file with my favorite text editor. in addition to the preference outlined in setting up extension development environment, you'll want to add the following preferences: // this allows you to add extra headers while composing messages user_pref("mail.compose.other.header", "x-superfluous,x-other,x-whatever"); // this enables the preservation of custom headers as incoming mail is processed user_pref( "mailnews.customdbheaders", "x-superfluous,x-other"); important: please pay careful attention to the case of the mailnews.customdbheaders preference. because comparisons are case-insensitive, all of the custom headers get set to lowercase when the data gets migrated to the message database. also, it has been brought to my attention that the delimiter has been chang...
...4/em-rdf#'> <description about='urn:mozilla:install-manifest'> <em:id>superfluous@yoursite.com</em:id> <em:version>0.1.1</em:version> <em:type>2</em:type> <!-- 2 is type 'extension' --> <em:targetapplication> <description> <!-- this next line identifies tbird as target --> <em:id>{3550f703-e582-4d05-9a08-453d09bdfdc6}</em:id> <em:minversion>2*</em:minversion> <em:maxversion>3.0.0.*</em:maxversion> </description> </em:targetapplication> <em:name>superfluous</em:name> <em:description>test superfluous extension</em:description> <em:creator>garrett comeaux</em:creator> </description> </rdf> build process: [gcomeaux@kyle tbird-ext]$ cd superfluous/ [gcomeaux@kyle superfluous]$ make zip supe...
Using MAPI with Thunderbird's Windows 7 developer builds
the thunderbird installer sets the installed build as the default mapi/mail client. if you want to set a debug build as the default mail client, you need configure it manually: in the objdir/mozilla/dist/bin directory, copy mozmapi32.dll to mozmapi32_inuse.dll and mapiproxy to mapiproxy_inuse.dll. (be sure to copy - not move - these files.) in the uninstall sub-directory of the bin directory, run these two commands: helper.exe /setasdefaultappglobal helper.exe /setasdefaultappuser create an elevated shell and register the mapi proxy.dll as a com server. ...
...inuse.dll. ...
Toolkit version format
...
... ...
Working with windows in chrome code
bute. this is different from the user-visible window title, which is specified using xul. the third, and optional, parameter is a list of special window features the window should have. the window.opendialog function works similarly, but lets you specify optional arguments that can be referenced from the javascript code. it also handles window features a little differently, including always assuming the dialog feature is specified. from xpcom components and modules if the window object is unavailable (for example, when opening a window from xpcom component code), you might want to use nsiwindowwatcher interface. its parameters are similar to window.open; in fact, window.open's implementation calls nsiwindowwatcher's methods. var ww = components.classes["@mozilla.org/embedcomp/window-wat...
...you can find the window's opener using its window.opener property or via a callback function passed to the window in a way d...
Add to iPhoto
tension uses a number of methods and data types, as well as constants, from three system frameworks. since a lot of this stuff is repetitive, we'll only look at selected parts of the code to get an idea how things work. you can download the extension and poke through the code inside it if you'd like to see all of it. for the sake of organization, i chose to implement each system framework (and, mind you, i only declare the apis i actually use, not all of them) as a javascript object containing all the types and methods that framework's api. note: in a few cases, this code takes the easy way out by using ctypes.voidptr_t instead of a typed pointer. that's not really the ideal way to do things but saved some time for this simple example. some of this may change as i refine the example in the...
...ason i include this here is because of the last parameter, which should be a pointer to an fsref, but that's not declared until we get around to declaring the carbon api, and i think that's worth noting. cfarray the cfarray type is used to create arrays of objects; the objects in the array can be of any type, thanks to a set of callbacks you can provide to handle managing their memory and performing operations such as comparisons. the most interesting thing we'll look at here is how to reference the system-provided default callback record, which is exported by core foundation under the name kcftypearraycallbacks. in c, the callback structure, and the predefined callback record, look like this: typedef const void * (*cfarrayretaincallback)(cfallocatorref allocator, const void *value); type...
Type conversion
tr(ctypes.uint64("0x11d6ff400"))' mystruct.v = null; console.log(mystruct.v.tostring()); // 'ctypes.int16_t.ptr(ctypes.uint64("0x0"))' mystruct.v = ctypes.int32_t.array(10)(); // throws error only in functiontype argument, the following rules are also applied: target type source converted value ctypes.char.ptr js string pointer to temporary allocated null-terminated utf8 string ctypes.signed_char.ptr ctypes.unsigned_char.ptr ctypes.char16.ptr js string pointer to temporary allocated null-terminated utf16 string any pointer types any arraybuffer object pointer to the arraybuffer ctypes.voidptr_t any typedarray/dataview object pointer to the typedarray/dataview ctypes.char.ptr ...
...c = myfunctype.ptr(function(v) { console.log(v.tostring()); }); myfunc("abcde"); // 'ctypes.char.ptr(ctypes.uint64("0x101d1d680"))' myfunc(int32array([1, 2, 3])); // 'ctypes.char.ptr(ctypes.uint64("0x103b7ffe0"))' array types target type source converted value ctypes.char.array(n) js string (only if utf8 representation fits to the array) null-terminated utf8 string ctypes.signed_char.array(n) ctypes.unsigned_char.array(n) ctypes.char16_t.array(n) js string (only if fits to the array) null-terminated utf16 string any array types js array (only if array length is same) convert each element implicitly any array types any arraybuffer object (only if array length is same in b...
Int64
nt64 object. see 64-bit integers for details. syntax creates and returns a new 64-bit signed integer. int64 int64( value ); parameters value the value to assign the new 64-bit integer object. this may be specified as an integer (if the value can be represented as a 32-bit value), another 64-bit integer object (either signed or unsigned), or as a string, which may consist of an optional minus sign, followed by either a decimal number or "0x" or "0x" followed by a hexadecimal number. the string is then converted into the corresponding 64-bit integer value. you can therefore use a string to represent a 64-bit value that is too large to represent as a 32-bit javascript number. return value a new object representing the specified value. exceptions thrown typeerror the specified ...
...ending on the debugging needs of the developers. tostring() returns a string representation of the object's numeric value. string tostring( [radix] ); parameters radix optional the radix (base) to use when constructing the string. if you don't specify a radix, base 10 is used. return value a string representation of the value in the specified radix. this string consists of a leading minus sign, if the value was negative, followed by one or more lower-case digits in the specified radix. see also ctypes uint64 ...
UInt64
see 64-bit integers for details. syntax creates and returns a new 64-bit unsigned integer. uint64 uint64( value ); parameters value the value to assign the new 64-bit unsigned integer object. this may be specified as an integer (if the value can be represented as a 32-bit value), another 64-bit integer object (either signed or unsigned), or as a string, which may consist of an optional minus sign, followed by either a decimal number or "0x" or "0x" followed by a hexadecimal number. the string is then converted into the corresponding 64-bit integer value. you can therefore use a string to represent a 64-bit value that is too large to represent as a 32-bit javascript number. return value a new object representing the specified value. exceptions thrown typeerror the specified ...
...ding on the debugging needs of the developers. tostring() returns a string representation of the object's numeric value. string tostring( [radix] ); parameters radix optional the radix (base) to use when constructing the string. if you don't specify a radix, base 10 is used. return value a string representation of the value in the specified radix. this string consists of a leading minus sign, if the value was negative, followed by one or more lower-case digits in the specified radix. arithmetic operations const uint64 = ctypes.uint64; const int64 = ctypes.int64; function ensureuint64(aarr) { // makes elements in aarr a uint64 if it can be made, else throws for (var i=0; i<aarr.length; i++) { var ccon = aarr[i].constructor.name; ...
PKCS #11 Netscape Trust Objects - Network Security Services
bject ultimately denotes a level of trust in a certificate. the trust is expressed for a specific purpose (or usage). a trust object contains multiple purposes and the level of trust for each one. examples of purposes are: email, code signing, authenticating a server. the levels of trust are: untrusted: the certificate is explicitly untrusted. unknown: the trust is not known and should be determined elsewhere. trusted: the certificate itself is explicitly trusted. trusted delegator: the certificate is trusted as a certificate authority trust root, and confers its trust to other certificates. certificate reference each trust object contains a reference to a certificate. there are two ways to refer to a certificate depending on whether that certificate is self-signed (like a certificat...
...cate signing key usage purpose. cka_trust_key_crl_sign ck_trust level of trust for crl signing key usage purpose. ck_trust is a ck_ulong which can contain one several values. it represents the level of trust. level of trust values. value description ck_untrusted explicitly untrusted. ck_unknown trust is unknown and should be determined elsewhere. ck_trusted explicitly trusts the certificate referred to in the trust object. ckt_trusted_delegator trusts the certificate as a certificate authority, and delegates trust (for the purpose) to other signed certificates. definitions definitions for all of the above values are defined in pkcs11n.h in the nss source. ...
Accessibility Inspector - Firefox Developer Tools
bility properties context menu item is grayed out. highlighting of ui items in the accessibility tab, when the mouse hovers over accessibility items, you can see a semi-transparent highlight appear over the ui items they relate to, if appropriate. the role and name of the item will be shown in a small information bar along with color contrast information if appropriate. this is useful for determining how the items in the accessibility tree relate to the ui items on the actual page. in the following example, you can see that the image has been highlighted and its role, graphic, name, "road, asphalt, sky, clouds, fall", and the color contrast ratio, 3.46, appears in the information bar above it. color contrast contrast ratio information is particularly useful when you are designing the ...
... ui items on the current page highlight objects in the accessibility tree. the accessibility tab element picker looks slightly different from the page inspector html pane picker, as shown below: when you "perform a pick", you see the accessibility object highlighted in the accessibility tree, and the picker is then deactivated. note, however, that if you hold the shift key down when "performing a pick", you can "preview" the accessibility object in the tree (and its properties in the right-hand pane), but then continue picking as many times as you like (the picker does not get cancelled) until you release the shift key. when the picker is activated, you can also deactivate it by pressing the picker button a second time, or pressing the esc key. typical use cases the accessibility in...
How to - Firefox Developer Tools
these articles describe how to use the debugger. ...
... these articles describe how to use the debugger. ...
Debugger.Frame - Firefox Developer Tools
itholder as its older property. invoke the debuggee code as appropriate for the given invocation function, with the "debugger" frame as its continuation. for example, debugger.frame.prototype.eval pushes an "eval" frame for code it runs, whereas debugger.object.prototype.call pushes a "call" frame. when the debuggee code completes, whether by returning, throwing an exception or being terminated, pop the "debugger" frame, and return an appropriate completion value from the invocation function to the debugger. when a debugger calls an invocation function to run debuggee code, that code’s continuation is the debugger, not the next debuggee code frame. pushing a "debugger" frame makes this continuation explicit, and makes it easier to find the extent of the stack created for the i...
... when a debugger handler function forces a frame to complete early, by returning a { return:... }, { throw:... }, or null resumption value, spidermonkey calls the frame’s onpop handler, if any. the completion value passed in this case reflects the resumption value that caused the frame to complete. when spidermonkey calls an onpop handler for a frame that is throwing an exception or being terminated, and the handler returns undefined, then spidermonkey proceeds with the exception or termination. that is, an undefined resumption value leaves the frame’s throwing and termination process undisturbed. if multiple debugger instances each have debugger.frame instances for a given stack frame with onpop handlers set, their handlers are run in an unspecified order. the resumption value each ...
Debugger.Script - Firefox Developer Tools
nd via the findscripts method on debugger instances. spidermonkey constructs exactly one debugger.script for each underlying webassembly module per debugger instance. a debugger.script instance is a strong reference to the underlying webassembly module; it protects the module it refers to from being garbage collected. please note at the time of this writing, support for webassembly is very preliminary. many properties and methods below throw. convention for descriptions of properties and methods below, if the behavior of the property or method differs between the instance referring to a jsscript or to a block of webassembly code, the text will be split into two sections, headed by “if the instance refers to a jsscript” and “if the instance refers to webassembly code”, respectively...
...he bytecode instruction atoffset in this script, reporting hits to the hit method ofhandler. ifoffset is not a valid offset in this script, throw an error. when execution reaches the given instruction, spidermonkey calls the hit method ofhandler, passing a debugger.frame instance representing the currently executing stack frame. the hit method’s return value should be a resumption value, determining how execution should continue. any number of breakpoints may be set at a single location; when control reaches that point, spidermonkey calls their handlers in an unspecified order. any number of breakpoints may use the samehandler object. breakpoint handler method calls are cross-compartment, intra-thread calls: the call takes place in the same thread that hit the breakpoint, and in the...
Debugger.Source - Firefox Developer Tools
representing the serialized text of a block of webassembly code, its properties provide the serialized text as a string. currently only entire modules evaluated via new webassembly.module are represented. spidermonkey constructs exactly one debugger.source for each underlying webassembly module per debugger instance. please note at the time of this writing, support for webassembly is very preliminary. many properties below return placeholder values. convention for descriptions of properties and methods below, if the behavior of the property or method differs between the instance referring to javascript source or to a block of webassembly code, the text will be split into two sections, headed by “if the instance refers to javascript source” and “if the instance refers to webassembly...
...onstructor, or a similar function isnot considered to be loaded from a url; the url accessor on debugger.source instances for such sources should return undefined.) if the instance refers to webassembly code, the url of the script that called new webassembly.module with the string "> wasm" appended. sourcemapurl if the instance refers to javascript source, if this source was produced by a minimizer or translated from some other language, and we know the url of a source map document relating the source positions in this source to the corresponding source positions in the original source, then this property’s value is that url. otherwise, this is null. (on the web, the translator may provide the source map url in a specially formatted comment in the javascript source code, or via a ...
DevTools API - Firefox Developer Tools
itchhost(hosttype) switches the location of the toolbox parameters: hosttype {toolbox.hosttype} - the type of the new host. return value: a promise that is fulfilled once the new host is ready. reloadtarget(force) reloads the current target of the toolbox. parameters: force {boolean} - if true the target is shift-reloaded i.e. the cache is bypassed during the reload. zoomin() increases the zoom level of the toolbox document. zoomout() decreases the zoom level of the toolbox document. zoomreset() resets the zoom level of the toolbox document. setzoom(value) set the zoom level to an arbitrary value. parameters: value {number} - the zoom level such as 1.2. destroy() closes the toolbox. return value: a promise that is resolved once the...
...ean, optional. if true the tool won't close if its keybinding is pressed while it is active. default: false inmenu boolean, optional. if true the tool will be shown in the developer menu. default: false menulabel string, optional. a label for the developer menu item. default: {label} accesskey string, optional. accesskey for the developer menu <xul:menuitem>. example here's a minimal definition for a tool. let def = { id: "my-tool", label: "my tool", icon: "chrome://browser/skin/devtools/tool-webconsole.svg", url: "about:blank", istargetsupported: target => true, build: (window, toolbox) => new mytoolpanel(window, toolbox) }; // register it. gdevtools.registertool(def); targettype fixme: hosttype fixme toolpanel the toolpanel is an interface the toolb...
Throttling - Firefox Developer Tools
us connection speeds so you can see how your app will behave under different connection types. throttling the toolbar includes a throttling dropdown, which allows you to throttle your network speed to emulate various different network speed conditions. simply choose an option from the menu, and it will persist across reloads. ...
... download speed upload speed minimum latency the table below lists the numbers associated with each network type, but please do not rely on this feature for exact performance measurements; it's intended to give an approximate idea of the user experience in different conditions. the speeds are expressed in multiples of bits per second. ...
UI Tour - Firefox Developer Tools
ition 77 and later) fonts view animations view the following image shows the 3-pane mode (available from firefox 62 onwards) which moves the css rules view into a separate pane in the center of the inspector. the following image shows 3-pane mode: as you can see, the css pane has moved into the center of the inspector. to learn more about the structure of the html pane, see the guide to examining and editing html. rules view the rules view lists all the rules that apply to the selected element, ordered from most-specific to least-specific. see above. see examine and edit css for more details. layout view the layout view displays the box model of the page. if the page includes any sections using either the flexbox display model or css grids, this view shows the flexbox or grid se...
...at apply to the selected element, ordered from most-specific to least-specific. see above. see examine and edit css for more details. layout view the layout view displays the box model of the page. 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. to learn more about the layout view, see examine and edit the box model. note that before firefox 50, the box model view did not appear in the "computed view" tab, but had its own tab. to learn more about the css declarations listed in this view, see examine computed css. changes view when you are editing in the rules view, you can see the changes you have made in the changes view. computed view the computed view shows you the complete ...
Animating CSS properties - Firefox Developer Tools
recording. you'll only need to record a few seconds. open up the first recording. exactly what you'll see depends a lot on your machine and system load, but it will be something like this: this is showing three distinct views: (a) an overview of the waterfall, (b) the frame rate, and (c) the timeline details. waterfall overview this is showing a compressed view of the waterfall. the predominance of green is telling us that we're spending a lot of time painting. frame rate this is showing frame rate. average frame rate here is 46.67fps, well below the target of 60fps. worse, though, is that the frame rate is very jagged, with lots of dips into the twenties and teens. it's unlikely you'll see a smooth animation here, especially when you add in user interaction. waterfall the rest...
...in the screenshot above we've highlighted a paint operation, and the box on the right tells us it took 13.11ms. with only 16.7ms in our total budget, it's not surprising we are missing a consistently high frame rate. you can experiment with this: try removing the box shadow using the page inspector, and see how that affects paint time. but next, we'll see how using transform instead of margin eliminates those expensive paints entirely. animating using transform now switch the radio button in the web page to "use transform", and make a new recording. it will look something like this: waterfall overview compared with the version that uses margin, we're seeing a lot less green and a lot more pink, which could be either layout or style recalculation. frame rate compared with the vers...
UI Tour - Firefox Developer Tools
an overview of the browser's responsiveness during the recording: see the separate article on frame rate. correlating events because these elements are synchronized, you can correlate events in one element with events in another. for example, in the screenshot below a long-running paint operation (shown as a green bar in the waterfall overview) corresponds to a drop in the frame rate: zooming in you can use the overview to select a slice of the recording to examine in more detail. select a slice, and the main view will be updated to contain just the part selected. in the screenshot below we've selected that drop in the frame rate, and can see the long-running paint operation in more detail: details pane the details pane shows whichever tool is currently selected. to switch to a ...
... drop in the frame rate, and can see the long-running paint operation in more detail: details pane the details pane shows whichever tool is currently selected. to switch to a different tool, use the buttons in the toolbar. waterfall the waterfall presents a view of the work the browser is doing during the recording: executing javascript, updating the css, updating the page layout, and performing repaints. the x-axis represents time, and the recorded operations are laid out as a waterfall, reflecting the serial nature of the browser's execution. to learn much more about the waterfall, see the separate waterfall page. call tree the call tree is a sampling profiler for javascript running in the page. it periodically samples the state of the javascript engine, and records the stack for...
Waterfall - Firefox Developer Tools
remental, the string indicates the reason non-incremental gc was performed. new in firefox 46: if the gc event was caused by allocation pressure, a link appears, labeled "show allocation triggers". click the link to see the allocation profile leading up to this gc event. see allocations and garbage collection for more details. cycle collection reclaiming c++ reference-counted data structures. like garbage collection, but for c++ objects. see kyle huey's blog post about cycle collection. type always "collect". cc graph reduction preparation/pre-optimization for cycle collection. type always "forgetskippable". console the period betwe...
...irly small increments, letting the program run in between. sometimes, though, it needs to perform a full non-incremental collection, and the program has to wait for it to finish. in trying to avoid gc events, and especially non-incremental gc events, it's wise not to try to optimize for the specific implementation of the javascript engine. spidermonkey uses a complex set of heuristics to determine when gc is needed, and when non-incremental gc in particular is needed. in general, though: gc is needed when a lot of memory is being allocated non-incremental gc is usually needed when the memory allocation rate is high enough that spidermonkey may run out of memory during incremental gc when the waterfall records a gc marker it indicates: whether the gc was incremental or not the re...
Performance - Firefox Developer Tools
he performance tool gives you insight into your site's general responsiveness, javascript and layout performance. with the performance tool you create a recording, or profile, of your site over a period of time. the tool then shows you an overview of the things the browser was doing to render your site over the profile, and a graph of the frame rate over the profile. ...
...with the performance tool you create a recording, or profile, of your site over a period of time. the tool then shows you an overview of the things the browser was doing to render your site over the profile, and a graph of the frame rate over the profile. you get four sub-tools to examine aspects of the profile in more detail: the waterfall shows the different operations the browser was performing, such as executing layout, javascript, repaints, and garbage collection the call tree shows the javascript functions in which the browser spent most of its time the flame chart shows the javascript call stack over the course of the recording the allocations view shows the heap allocations made by your code over the course of the recording. this view only appears if you checked "record allocat...
Settings - Firefox Developer Tools
nes of the console output. the rest of the settings are on the developer tools settings pane. to see the settings, open any of the developer tools, and then: click the "settings" command in the menu: or press f1 to toggle between the active tool and the settings pane the settings pane looks something like this: categories default firefox developer tools this group of checkboxes determines which tools are enabled in the toolbox. new tools are often included in firefox but not enabled by default. available toolbox buttons this group of checkboxes determines which tools get an icon in the toolbox's toolbar. as of firefox 62, if the option to "select an iframe as the currently targeted document" is checked, the icon will appear in the toolbar while the settings tab is displayed, ...
... play camera shutter sound when you click the icon for the screenshot tool, play a shutter sound. new in firefox 53. editor preferences preferences for the codemirror source editor, which is included in firefox and used by several developer tools, including scratchpad and the style editor. detect indentation auto-indent new lines based on the current indentation. autoclose brackets determines whether typing an opening character like [ or { will cause the editor to insert the matching closing character ] or } for you. indent using spaces when checked, indentation will be performed using spaces, when off, the editor will use tabs instead. tab size the frequency of tab stops in the editor. select 2, 4, or 8. keybindings choose the default codemirror keybindings or keybindings fro...
Shader Editor - Firefox Developer Tools
fragment shaders used by webgl. webgl is a javascript api for rendering interactive 3d graphics and 2d graphics in the browser without using plugins. with webgl you provide 2 programs called shaders which are called at the appropriate stages of the opengl rendering pipeline: a vertex shader, which computes the clip space coordinates of each vertex to be drawn, and a fragment shader, which determines the color for each pixel to be drawn. these shaders are written in opengl shading language, or glsl. 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 e...
...gl shading language, or glsl. 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. with the shader editor, you can examine and edit the source of the vertex and fragment shaders. here's another screencast, showing how you can use the shader editor for complex applications (in this case, the unreal engine demo): opening the shader editor the shader editor is disabled by default. to enable it, open the toolbox settings and check "shader editor" in the "default firefox developer tools" item. you'll now see "shader...
Rich output - Firefox Developer Tools
when the web console prints objects, it includes a richer set of information than just the object's name. in particular, it: provides extra information for certain types enables detailed examination of the object's properties provides richer information for dom elements, and enables you to select them in the inspector type-specific rich output the web console provides rich output for many object types, including the following: object array date promise regexp window document element event examining object properties when an object is logged to the console it has a right-pointing triangle next to it, indicating that it can be expanded. click on the tria...
...ing triangle next to it, indicating that it can be expanded. click on the triangle, and the object will be expanded to show its contents: starting with firefox 67 (available now in firefox developer) you can use the arrow keys on your keyboard to navigate through objects displayed in the console. the right-arrow key opens the details of an object and the left-arrow key closes open objects. examining request details similar to examining object details, you can see the details about a network request directly in the console. click on the arrow next to the request and a details panel will open that is equivalent to the headers panel in the network monitor tool. export output to the clipboard once you have output in the console window, you can save it to the clipboard by right-clicking o...
about:debugging (before Firefox 68) - Firefox Developer Tools
ing the add-on debugger the add-ons page in about:debugging lists all restartless add-ons that are currently installed (note that this list may include add-ons that came preinstalled with your firefox). next to each entry is a button labeled "debug". if the "debug" button is disabled, check the "enable add-on debugging" box. if you click "debug", you'll see a dialog asking you to accept an incoming connection. click "ok", and the add-on debugger will start in a separate window. note that sometimes the debugger window is hidden by the main firefox window. see the page on the add-on debugger for all the things you can do with this tool. the "enable add-on debugging" button works by turning on the devtools.chrome.enabled and devtools.debugger.remote-enabled preferences. both preferences ...
...hrome workers and dedicated workers you can connect the developer tools to each worker, and send push notifications to service workers. service worker state from firefox 52, the list of service workers shows the state of the service worker in its lifecycle. three states are distinguished: "registering": this covers all states between the service worker's initial registration, and its assuming control of pages. that is, it subsumes the "installing", "activating", and "waiting" states. "running": the service worker is currently running. it's installed and activated, and is currently handling events. "stopped": the service worker is installed and activated, but has been terminated after being idle. this section uses a simple serviceworker demo, hosted at https://serviceworke.rs/p...
Firefox Developer Tools
this section contains detailed guides to all of the tools as well as information on how to debug firefox for android, how to extend devtools, and how to debug the browser as a whole. if you have any feedback on devtools, or want to contribute to the project, you can join the devtools community. 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? for good starting points. ...
...tation for firefox web tools and the mozilla community. closes the developer tools page inspector view and edit page content and layout. visualise many aspects of the page including the box model, animations, and grid layouts. web console see messages logged by a web page and interact with the page using javascript. javascript debugger stop, step through, examine, and modify the javascript running in a page. network monitor see the network requests made when a page is loaded. performance tools analyze your site's general responsiveness, javascript, and layout performance. responsive design mode see how your website or app will look and behave on different devices and network types. accessibility inspector provides a means to a...
AmbientLightSensor - Web APIs
the ambientlightsensor interface of the the sensor apis returns the current light level or illuminance of the ambient light around the hosting device. to use this sensor, the user must grant permission to the 'ambient-light-sensor' device sensor through the permissions api. if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. constructor ambientlightsensor.ambientlightsensor() creates a new ambientlightsensor object. properties ambientlightsensor.illuminance returns the current light level in lux of the ambient light level around the hosting device. example if ( 'ambientlightsensor' in window ) { c...
... ambientlightsensor.ambientlightsensor() creates a new ambientlightsensor object. properties ambientlightsensor.illuminance returns the current light level in lux of the ambient light level around the hosting device. example if ( 'ambientlightsensor' in window ) { const sensor = new ambientlightsensor(); sensor.onreading = () => { console.log('current light level:', sensor.illuminance); }; sensor.onerror = (event) => { console.log(event.error.name, event.error.message); }; sensor.start(); } specifications specification status comment generic sensor api candidate recommendation defines sensors in general. ambient light sensorthe definition of 'ambientlightsensor' in that specification. candidate recommendation ...
AnalyserNode.maxDecibels - Web APIs
ng the maximum decibel value for scaling the fft analysis data, where 0 db is the loudest possible sound, -10 db is a 10th of that, etc. the default value is -30 db. when getting data from getfloatfrequencydata() or getbytefrequencydata(), any frequencies with an amplitude of maxdecibels or higher will be returned as +1.0 or 255, respectively. note: if a value less than or equal to analysernode.mindecibels is set, an indexsizeerror exception is thrown. example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js l...
...uestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); analyser.mindecibels = -90; analyser.maxdecibels = -10; ... analyser.fftsize = 256; var bufferlength = analyser.frequencybincount; console.log(bufferlength); var dataarray = new uint8array(bufferlength); canvasctx.clearrect(0, 0, width, height); function draw() { drawvisual = requestanimationframe(draw); analyser.getbytefrequencydata(dataarray); canvasctx.fillstyle = 'rgb(0, 0, 0)'; canvasctx.
Animation.pause() - Web APIs
Web › API › Animation › pause
ted playing yet) and the end time of the animation is positive infinity. ...
...ted with the element.animate() method immediately start playing and must be paused manually if you want to avoid that: // animation of the cupcake slowly getting eaten up 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 }); // doesn't actually need to be eaten until a click event, so pause it initially: nommingcake.pause(); additionally, when resetting : // an all-purpose function to pause the animations on alice, the cupcake, and the bottle that reads "drink me." var stopplayingalice = function() { alicechange.pause(); nommingcake.pause(); drinking.pause(); }; // when the user releases ...
Animation.play() - Web APIs
Web › API › Animation › play
it from the beginning. syntax animation.play(); parameters none. 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. ...
...ange) to play forward, causing her to get bigger, as well as triggering the cake's animation. two animation.play()s, one eventlistener: // the cake has its own 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 }); // pause the cake's animation so it doesn't play immediately. nommingcake.pause(); // this function will play when ever a user clicks or taps var growalice = function() { // play alice's animation. alicechange.play(); // play the cake's animation. nommingcake.play(); } // when a user holds their mouse down or taps, call growalice to make all the animations play. ca...
AnimationEvent - Web APIs
the animationevent interface represents events providing information related to animations. ...
... the animationevent interface represents events providing information related to animations. ...
AudioBuffer() - Web APIs
numberofchannels: the number of channels for the buffer. ...
...owed to go farther outside this range). deprecated parameters context a reference to an audiocontext. this parameter was removed from the spec. return value a new audiobuffer object instance. exceptions notsupportederror one or more of the options are negative or otherwise has an invalid value (such as numberofchannels being higher than supported, or a samplerate outside the nominal range). rangeerror there isn't enough memory available to allocate the buffer. specifications specification status comment web audio apithe definition of 'audiobuffer' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the...
AudioBufferSourceNode.AudioBufferSourceNode() - Web APIs
urcenode object instance. syntax var audiobuffersourcenode = new audiobuffersourcenode(context, options) parameters inherits parameters from the audionodeoptions dictionary. context a reference to an audiocontext. options optional options are as follows: buffer: an instance of audiobuffer to be played. detune: a value in cents to modulate the speed of audio stream rendering. its nominal range is (-∞ to +∞). the default is 0. loop: a boolean indicating whether the audio should play in a loop. the default is false. if the loop is dynamically modified during playback, the new value will take effect on the next processing block of audio. loopend: an optional value, in seconds, where looping should end if the loop attribute is true. the default is 0. its value is exclusive ...
... attribute is converted to an exact sample frame offset within the buffer, by multiplying by the buffer's sample rate and rounding to the nearest integer value. thus, its behavior is independent of the value of the playbackrate parameter. playbackrate: the speed at which to render the audio stream. its default value is 1. this parameter is k-rate. this is a compound parameter with detune. its nominal range is (-∞ to +∞). return value a new audiobuffersourcenode object instance. specifications specification status comment web audio apithe definition of 'audiobuffersourcenode()' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like ...
AudioContext() - Web APIs
ontext. available properties are as follows: latencyhint optional the type of playback that the context will be used for, as a value from the audiocontextlatencycategory enum or a double-precision floating-point value indicating the preferred maximum latency of the context in seconds. the user agent may or may not choose to meet this request; check the value of audiocontext.baselatency to determine the true latency after creating the context. samplerate optional the samplerate to be used by the audiocontext, specified in samples per second. the value may be any value supported by audiobuffer. if not specified, the preferred sample rate for the context's output device is used by default. return value the newly constructed audiocontext instance. exceptions notsupportederror the sp...
...udiobuffer. if not specified, the preferred sample rate for the context's output device is used by default. return value the newly constructed audiocontext instance. exceptions notsupportederror the specified samplerate isn't supported by the context. usage notes the specification doesn't go into a lot of detail about things like how many audio contexts a user agent should support, or minimum or maximum latency requirements (if any), so these details can vary from browser to browser. be sure to check the values if they matter to you. in particular, the specification doesn't indicate a maximum or minimum number of audio contexts that must be able to be open at the same time, so this is left up to the browser implementations to decide. google chrome per-tab audio context limitati...
AudioContext - Web APIs
me, and it's ok to use a single audiocontext for several different audio source and pipeline concurrently. ...
...and it's ok to use a single audiocontext for several different audio source and pipeline concurrently. ...
AudioContextOptions - Web APIs
the audiocontext() constructor. properties latencyhint optional the type of playback that the context will be used for, as a value from the audiocontextlatencycategory enum or a double-precision floating-point value indicating the preferred maximum latency of the context in seconds. the user agent may or may not choose to meet this request; check the value of audiocontext.baselatency to determine the true latency after creating the context. samplerate optional the samplerate to be used by the audiocontext, specified in samples per second. the value may be any value supported by audiobuffer. if not specified, the preferred sample rate for the context's output device is used by default. constants standard values for latencyhint the latencyhint property can be number specifying a pref...
...ive elements, such as responding to user actions or needing to coincide with visual cues such as a video or game action. the user agent should select the lowest possible latency that doesn't cause glitches in the audio. this is likely to require increased power consumption. this is the default value. "playback" the user agent should select a latency that will maximize playback time by minimizing power consumption at the expense of latency. useful for non-interactive playback, such as playing music. example this example instantiates an audio context for music playback (optimized for power consumption over latency), with the sample rate 48,000 hz. let musiccontext = new audiocontext({ latencyhint: "playback", samplerate: 48000 }); specifications specification...
AudioParam.exponentialRampToValueAtTime() - Web APIs
audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // set basic variables for example var myaudio = document.queryselector('audio'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; var exprampplus = document.queryselector('.exp-ramp-plus'); var exprampminus = document.queryselector('.exp-ramp-minus'); // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a gain node and set its gain value to 0.5 var gainnode = audioctx.creategain(); // connect the audiobuffersourcenode to the gainnode // and the gainnode to the destination gainnode.gain.setvalueattime(0, a...
... specifications specification status comment web audio apithe defini...
AudioParam.linearRampToValueAtTime() - Web APIs
text var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // set basic variables for example var myaudio = document.queryselector('audio'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; var linearrampplus = document.queryselector('.linear-ramp-plus'); var linearrampminus = document.queryselector('.linear-ramp-minus'); // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a gain node and set it's gain value to 0.5 var gainnode = audioctx.creategain(); // connect the audiobuffersourcenode to the gainnode // and the gainnode to the destination gainnode.gain.setvalueattime(...
... working draft ...
AudioParam.maxValue - Web APIs
the default value of maxvalue is the maximum positive single-precision floating-point value (+340,282,346,638,528,859,811,704,183,484,516,925,440). ...
... the default value of maxvalue is the maximum positive single-precision floating-point value (+340,282,346,638,528,859,811,704,183,484,516,925,440). ...
AudioParam.setTargetAtTime() - Web APIs
te audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // set basic variables for example var myaudio = document.queryselector('audio'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; var attimeplus = document.queryselector('.at-time-plus'); var attimeminus = document.queryselector('.at-time-minus'); // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a gain node and set it's gain value to 0.5 var gainnode = audioctx.creategain(); gainnode.gain.value = 0.5; var currgain = gainnode.gain.value; // connect the audiobuffersourcenode to the gainnode // and th...
... working draft ...
AudioParam.setValueAtTime() - Web APIs
diocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // set basic variables for example var myaudio = document.queryselector('audio'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; var targetattimeplus = document.queryselector('.set-target-at-time-plus'); var targetattimeminus = document.queryselector('.set-target-at-time-minus'); // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a gain node and set it's gain value to 0.5 var gainnode = audioctx.creategain(); gainnode.gain.value = 0.5; var currgain = gainnode.gain.value; // connect the audiobuffersourcenode to the gainnod...
... working draft ...
AudioParamDescriptor - Web APIs
omstring which represents the name of the audioparam. under this name the audioparam will be available in the parameters property of the node, and under this name the audioworkletprocessor.process method will acquire the calculated values of this audioparam. automationrate optional either "a-rate", or "k-rate" string which represents an automation rate of this audioparam. defaults to "a-rate". minvalue optional a float which represents minimum value of the audioparam. defaults to -3.4028235e38. maxvalue optional a float which represents maximum value of the audioparam. defaults to 3.4028235e38. defaultvalue optional a float which represents initial value of the audioparam. defaults to 0. examples to demonstrate creation and usage of custom audioparams, we'll expand the example from...
...le. we expand the processor by adding a static parameterdescriptors getter. it will be used internally by the audioworkletnode constructor to populate its parameters with instantiated audioparam objects. ...
AudioTrackList.onchange - Web APIs
the audiotracklist property onchange is an event handler which is called when the change event occurs, indicating that one or more of the audiotracks in the audiotracklist have been enabled or disabled. the event is passed into the event handler in the form of an event object; the event doesn't provide any additional information. to determine the new state of media's tracks, you'll have to look at their audiotrack.enabled flags. note: you can also add a handler for the change event using addeventlistener(). syntax audiotracklist.onchange = eventhandler; value set onchange to a function that should be called whenever tracks are enabled or disabled on the media element. example this snippet establishes a handler for the change event that looks at each of the tracks in the list, calli...
... specifications specification status comment html living standardthe definition of 'audiotracklist.onchange' in that specification. living standard html5the definition of 'audiotracklist.onchange' in that specification. recommendation ...
AudioWorkletProcessor.parameterDescriptors (static getter) - Web APIs
omstring which represents the name of the audioparam. under this name the audioparam will be available in the parameters property of the node, and under this name the audioworkletprocessor.process method will acquire the calculated values of this audioparam. automationrate optional either "a-rate", or "k-rate" string which represents an automation rate of this audioparam. defaults to "a-rate". minvalue optional a float which represents minimum value of the audioparam. defaults to -3.4028235e38. maxvalue optional a float which represents maximum value of the audioparam. defaults to 3.4028235e38. defaultvalue optional a float which represents initial value of the audioparam. defaults to 0. examples to demonstrate creation and usage of custom audioparams, we'll expand the example from...
...le. we expand the processor by adding a static parameterdescriptors getter. it will be used internally by the audioworkletnode constructor to populate its parameters with instantiated audioparam objects. ...
BaseAudioContext.createBuffer() - Web APIs
frames, samples and channels from our basic concepts guide. numofchannels an integer representing the number of channels this buffer should have. the default value is 1, and all user agents must support at least 32 channels. length an integer representing the size of the buffer in sample-frames (where each sample-frame is the size of a sample in bytes multiplied by numofchannels). to determine the length to use for a specific number of seconds of audio, use numseconds * samplerate. samplerate the sample rate of the linear audio data in sample-frames per second. all browsers must support sample rates in at least the range 8,000 hz to 96,000 hz. returns an audiobuffer configured based on the specified options. exceptions notsupportederror one or more of the options are negativ...
...of the linear audio data in sample-frames per second. all browsers must support sample rates in at least the range 8,000 hz to 96,000 hz. returns an audiobuffer configured based on the specified options. exceptions notsupportederror one or more of the options are negative or otherwise has an invalid value (such as numberofchannels being higher than supported, or a samplerate outside the nominal range). rangeerror there isn't enough memory available to allocate the buffer. examples first, a couple of simple trivial examples, to help explain how the parameters are used: var audioctx = new audiocontext(); var buffer = audioctx.createbuffer(2, 22050, 44100); if you use this call, you will get a stereo buffer (two channels), that, when played back on an audiocontext running at 44100...
BeforeInstallPromptEvent - Web APIs
pted to "install" a web site to a home screen on mobile. this interface inherits from the event interface. ...
... to "install" a web site to a home screen on mobile. this interface inherits from the event interface. ...
BeforeUnloadEvent - Web APIs
frame or any embedded frame receives a user gesture or user interaction. see browser compatibility for more information. ...
...me or any embedded frame receives a user gesture or user interaction. see browser compatibility for more information. ...
BluetoothDevice - Web APIs
e of the web bluetooth api represents a bluetooth device inside a particular script execution environment. ...
... the web bluetooth api represents a bluetooth device inside a particular script execution environment. ...
BroadcastChannel - Web APIs
at all broadcastchannel objects listening to the channel. note: this feature is available in web workers. ...
...ll broadcastchannel objects listening to the channel. note: this feature is available in web workers. ...
CDATASection - Web APIs
<![cdata[ ]]> will cause an error ]]> note that cdata sections should not be used within html; they only work in xml. ...
...[cdata[ ]]> will cause an error ]]> note that cdata sections should not be used within html; they only work in xml. ...
CSSCounterStyleRule - Web APIs
nts an @counter-style at-rule. ...
...an @counter-style at-rule. ...
CSSNumericValue - Web APIs
the cssnumericvalue interface of the css typed object model api represents operations that all numeric values can perform. interfaces based on cssnumericvalue below is a list of interfaces based on the cssnumericvalue interface. cssmathinvert cssmathmax cssmathmin cssmathnegate cssmathproduct cssmathsum cssmathvalue cssnumericarray cssperspective csspositionvalue cssrotate cssskew cssskeyx cssskeyw csstranslate cssunitvalue properties none. event handlers no methods cssnumericvalue.add adds a supplied number to the cssnumericvalue. cssnumericvalue.sub subtracts a supplied number from the cssnumericvalue. cssnumericvalue.mul multiplies the cssnumericvalue by the supplied value. cssnumericvalue.div divides the cssnumericvalue by the supplied value. css...
...cssskeyw csstranslate cssunitvalue properties none. event handlers no methods cssnumericvalue.add adds a supplied number to the cssnumericvalue. cssnumericvalue.sub subtracts a supplied number from the cssnumericvalue. cssnumericvalue.mul multiplies the cssnumericvalue by the supplied value. cssnumericvalue.div divides the cssnumericvalue by the supplied value. cssnumericvalue.min returns the minimum value passed cssnumericvalue.max returns the maximum value passed cssnumericvalue.equals true if all the values are the exact same type and value, in the same order. otherwise, false. cssnumericvalue.to converts value into another one with the specified unit. cssnumericvalue.tosum tbd cssnumericvalue.type tbd cssnumericvalue.parse allows a cssnumericvalue to be co...
CSSStyleDeclaration.setProperty() - Web APIs
ty() method, for example boxpararule.style.setproperty('border', newborder); html <div class="controls"> <button class="border">border</button> <button class="bgcolor">background</button> <button class="color">text</button> </div> <div class="box"> <p>box</p> </div> css html { background: orange; font-family: sans-serif; height: 100%; } body { height: inherit; width: 80%; min-width: 500px; max-width: 1000px; margin: 0 auto; } .controls { display: flex; justify-content: space-around; align-items: center; } div button { flex: 1; margin: 20px; height: 30px; line-height: 30px; } .box { display: flex; justify-content: center; align-items: center; height: calc(100% - 70px); } .box p { width: 50%; text-align: center; font-weight: bold; f...
... font-weight: bold; font-size: 40px; height: 150px; line-height: 150px; background: red; border: 5px solid purple; color: white; transition: all 1s; } javascript const borderbtn = document.queryselector('.border'); const bgcolorbtn = document.queryselector('.bgcolor'); const colorbtn = document.queryselector('.color'); const box = document.queryselector('.box'); function random(min,max) { const num = math.floor(math.random()*(max-min)) + min; return num; } function randomcolor() { return 'rgb(' + random(0,255) + ', ' + random(0,255) + ', ' + random(0,255) + ')'; } const stylesheet = document.stylesheets[1]; let boxpararule; for(let i = 0; i < stylesheet.cssrules.length; i++) { if(stylesheet.cssrules[i].selectortext === '.box p') { boxpararule = stylesheet.cs...
CSSValueList - Web APIs
has the value none. the items in the cssvaluelist are accessible via an integral index, starting from 0. ...
... the value none. the items in the cssvaluelist are accessible via an integral index, starting from 0. ...
CSS Object Model (CSSOM) - Web APIs
st mediaquerylist mediaquerylistevent mediaquerylistlistener screen stylesheet stylesheetlist transitionevent several other interfaces are also extended by the cssom-related specifications: document, window, element, htmlelement, htmlimageelement, range, mouseevent, and svgelement. ...
... managing screen orientation specifications specification status comment css typed om level 1 working draft css painting api level 1 working draft extended the css interface with the paintworklet static property. css object model (cssom) view modu...
Using the CSS Typed Object Model - Web APIs
e, csskeywordvalue, cssnumericvalue, csspositionvalue, csstransformvalue, and cssunparsedvalue. it has two methods: cssstylevalue.parse() cssstylevalue.parseall() as noted above, stylepropertymapreadonly.get('--customproperty') returns a cssunparsedvalue. we can parse cssunparsedvalue object instances with the inherited cssstylevalue.parse() and cssstylevalue.parseall() methods. let's examine a css example with several custom properties, transforms, calc()s, and other features. we'll take a look at that their types are by employing short javascript snippets outputting to console.log(): :root { --maincolor: hsl(198, 43%, 42%); --black: hsl(0, 0%, 16%); --white: hsl(0,0%,97%); --unit: 1.2rem; } button { --maincolor: hsl(198, 100%, 66%); display: inline-block; padd...
...rray with 2 cssunitvalues. the value of cssmathvalue.operator is sum: let btnwidth = allcomputedstyles.get('width') console.log( btnwidth ); // cssmathsum console.log( btnwidth.values ); // cssnumericarray {0: cssunitvalue, 1: cssunitvalue, length: 2} console.log( btnwidth.operator ); // 'sum' csstransformvalue with cssscale the display: inline-block; also enables transforming. in our css we have transform: scale(0.95);, which is a transform function. let transform = allcomputedstyles.get('transform'); console.log( transform ); // csstransformvalue {0: cssscale, 1: csstranslate, length: 2, is2d: true} console.log( transform.length ); // 1 console.log( transform[0] ); // cssscale {x: cssunitvalue, y: cssunitvalue, z: cssunitvalue, is2d: true} console.log(...
Cache - Web APIs
Web › API › Cache
of the serviceworkerglobalscope. it holds the cachestorage object, by which it can access the cachestorage interface. this is an implementation of the windoworworkerglobalscope mixin. note: in chrome, visit chrome://inspect/#service-workers and click on the "inspect" link below the registered service worker to view logging statements for the various actions the service-worker.js script is performing. var cache_version = 1; var current_caches = { font: 'font-cache-v' + cache_version }; self.addeventlistener('activate', function(event) { // delete all caches that aren't named in current_caches. // while there is only one cache in this example, the same logic will handle the case where // there are multiple versioned caches. var expectedcachenamesset = new set(object.values(current...
... // note that for opaque filtered responses (https://fetch.spec.whatwg.org/#concept-filtered-response-opaque) // we can't access to the response headers, so this check will always fail and the font won't be cached. // all of the google web fonts are served off of a domain that supports cors, so that isn't an issue here. // it is something to keep in mind if you're attempting to cache other resources from a cross-origin // domain that doesn't support cors, though! // we call .clone() on the response to save a copy of it to the cache. by doing so, we get to keep // the original response object which we will return back to the controlled page. // (see /docs/web/api/request/clone) console.l...
CanvasRenderingContext2D.addHitRegion() - Web APIs
to dom elements, and make it possible for users to explore the canvas without seeing it. syntax void ctx.addhitregion(options); options the options argument is optional. when provided, it is an object which can contain the following properties: path a path2d object describing the area of the hit region. if not provided, the current path is used. fillrule the algorithm by which to determine if a point is inside or outside the hit region. possible values: nonzero: the non-zero winding rule. default rule. evenodd: the even-odd winding rule. id the id for this hit region to reference it for later use in events, for example. parentid the id of the parent region for cursor fallback and navigation by accessibility tools. cursor the cursor to use when the mouse is over th...
... this region (defaults to inherit). inherits the cursor of the parent hit region, if any, or the canvas element's cursor. control an element (descendant of the canvas) to which events are to be routed. defaults to null. label a text label for accessibility tools to use as a description of the region, if there is no control. defaults to null. role an aria role for accessibility tools to determine how to represent this region, if there is no control. defaults to null. examples using the addhitregion method this example demonstrates the addhitregion() method. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); canvas.addeventlistener('mousemove', function(event) { if(event.region) { alert('ouch...
A basic ray-caster - Web APIs
sliver of canvas in the color of the wall they've hit, blended with a darker version of the color according to the distance to the wall. the height of the sliver is also modulated by the distance from the camera to the wall, and is drawn centered over the horizon line. the code i ended up with is a regurgitated amalgam of the raycaster chapters from an old andré lamothetricks of the game programming gurus book (isbn: 0672305070), and a java raycaster i found online, filtered through my compulsion to rename everything so it makes sense to me, and all the tinkering that had to be done to make things work well. results the canvas in safari 2.0.1 performed surprisingly well. with the blockiness factor cranked up to render slivers 8 pixels wide, i can run a 320 x 240 window at 24 fps on my app...
...urus book (isbn: 0672305070), and a java raycaster i found online, filtered through my compulsion to rename everything so it makes sense to me, and all the tinkering that had to be done to make things work well. results the canvas in safari 2.0.1 performed surprisingly well. with the blockiness factor cranked up to render slivers 8 pixels wide, i can run a 320 x 240 window at 24 fps on my apple mini. firefox 1.5 beta 1 is even faster; i can run 320 x 240 at 24 fps with 4 pixel slivers. not exactly a new member of the id software family, but pretty decent considering it's a fully interpreted environment, and i didn't have to worry about memory allocation or video modes or coding inner routines in assembler or anything. the code does attempt to be very efficient, using array look-ups of pre-c...
Compositing example - Web APIs
everything else is made transparent.', 'the new shape is drawn where it doesn\'t overlap the existing canvas content.', 'the new shape is only drawn where it overlaps the ex...
...isting canvas content.', 'the existing canvas content is kept where both the new shape and existing canvas content overlap. everything else is made transparent.', 'the existing content is kept where it doesn\'t overlap the new shape.', 'the existing canvas is only kept where it overlaps the new shape. the new shape is drawn behind the canvas content.', 'where both shapes overlap the color is determined by adding color values.', 'only the new shape is shown.', 'shapes are made transparent where both overlap and drawn normal everywhere else.', 'the pixels are of the top layer are multiplied with the corresponding pixel of the bottom layer. a darker picture is the result.', 'the pixels are inverted, multiplied, and inverted again. a lighter picture is the result (opposite of multiply)', 'a combi...
Drawing shapes with canvas - Web APIs
ctx.clearrect(45, 45, 60, 60); ctx.strokerect(50, 50, 50, 50); } } this example's output is shown below. screenshotlive sample the fillrect() function draws a large black square 100 pixels on each side. the clearrect() function then erases a 60x60 pixel square from the center, and then strokerect() is called to create a rectangular outline 50x50 pixels within the cleared square. in upcoming pages we'll see two alternative methods for clearrect(), and we'll also see how to change the color and stroke style of the rendered shapes. unlike the path functions we'll see in the next section, all three rectangle functions draw immediately to the canvas. drawing paths now let's look at paths. a path is a list of points, connected by segments of lines that can be of different shapes, curv...
...olumns of arcs. for each arc, we start a new path by calling beginpath(). in the code, each of the parameters for the arc is in a variable for clarity, but you wouldn't necessarily do that in real life. the x and y coordinates should be clear enough. radius and startangle are fixed. the endangle starts at 180 degrees (half a circle) in the first column and is increased by steps of 90 degrees, culminating in a complete circle in the last column. the statement for the clockwise parameter results in the first and third row being drawn as clockwise arcs and the second and fourth row as counterclockwise arcs. finally, the if statement makes the top half stroked arcs and the bottom half filled arcs. note: this example requires a slightly larger canvas than the others on this page: 150 x 200 pix...
Using images - Web APIs
nt img.addeventlistener('load', function() { // execute drawimage statements here }, false); img.src = 'myimage.png'; // set source path if you're only using one external image this can be a good approach, but once you need to track more than one we need to resort to something more clever. it's beyond the scope of this tutorial to look at image pre-loading tactics, but you should keep that in mind. embedding an image via data: url another possible way to include images is via the data: url. data urls allow you to completely define an image as a base64 encoded string of characters directly in your code. var img = new image(); // create new img element img.src = 'data:image/gif;base64,r0lgodlhcwalaiaaaaaa3pn/zih5baeaaaealaaaaaalaasaaaiuha+hkcuo4lmnvindo7qyrixigbyaow=='; one advantage...
... in a single image file and use this method to composite a complete drawing. for instance, if you want to make a chart you could have a png image containing all the necessary text in a single file and depending on your data could change the scale of your chart fairly easily. another advantage is that you don't need to load every image individually, which can improve load performance. example: framing an image in this example, we'll use the same rhino as in the previous example, but we'll slice out its head and composite it into a picture frame. the picture frame image is a 24-bit png which includes a drop shadow. because 24-bit png images include a full 8-bit alpha channel, unlike gif and 8-bit png images, it can be placed onto any background without worrying about a matte color. <html> <...
CharacterData - Web APIs
it is implemented by other interfaces, like text, comment, or processinginstruction which aren't abstract. ...
...s implemented by other interfaces, like text, comment, or processinginstruction which aren't abstract. ...
Comment - Web APIs
Web › API › Comment
as content between '<!--' and '-->'. in xml, the character sequence '--' cannot be used within a comment. ...
...content between '<!--' and '-->'. in xml, the character sequence '--' cannot be used within a comment. ...
CompositionEvent - Web APIs
the dom compositionevent represents events that occur due to the user indirectly entering text. ...
... the dom compositionevent represents events that occur due to the user indirectly entering text. ...
console - Web APIs
Web › API › Console
e. console.count() log the number of times this line has been called with the given label. console.countreset() resets the value of the counter with the given label. console.debug() outputs a message to the console with the log level debug. console.dir() displays an interactive listing of the properties of a specified javascript object. this listing lets you use disclosure triangles to examine the contents of child objects. console.dirxml() displays an xml/html element representation of the specified object if possible or the javascript object view if it is not possible. console.error() outputs an error message. you may use string substitution and additional arguments with this method. console.exception() an alias for error(). console.group() creates a new inline group, in...
...r stuff..."); console.timeend("answer time"); will log the time needed by the user to dismiss the alert box, log the time to the console, wait for the user to dismiss the second alert, and then log the ending time to the console: notice that the timer's name is displayed both when the timer is started and when it's stopped. note: it's important to note that if you're using this to log the timing for network traffic, the timer will report the total time for the transaction, while the time listed in the network panel is just the amount of time required for the header. if you have response body logging enabled, the time listed for the response header and body combined should match what you see in the console output. stack traces the console object also supports outputting a stack trace; ...
Content Index API - Web APIs
usage as it stands, offline web content is not easily discoverable by users. content indexing allows developers to tell the browser about their specific offline content. this allows users to discover and view what is available, whilst giving developers the ability to add and manage this content. examples could be a news website prefetching the latest articles in the background, or a content streaming app registering downloaded content. the content index api is an extension to service workers, which allows developers to add urls and metadata of already cached pages, under the scope of the current service worker. the browser can then use these entries to display offline reading to a user. as a developer you can also display these entries within your application. indexed entries do not automa...
...ration.index.add(item); self.registration.index.delete(item.id); const contentindexitems = self.registration.index.getall(); contentdelete event when an item is removed from the user agent interface, a contentdelete event is received by the service worker. self.addeventlistener('contentdelete', (event) => { console.log(event.id); // logs content index id, which can then be used to determine what content to delete from your cache }); the contentdelete event is only fired when the deletion happens due to interaction with the browser's built-in user interface. it is not fired when the contentindex.delete method is called. specifications specification status comment unknown unknown initial definition. ...
Credential Management API - Web APIs
nts have a particularly hard time dealing with federated identity providers or esoteric sign-in mechanisms that use more than just a username and password. to address these problems, the credential management api provides ways for a website to store and retrieve different types of credentials. this give users capabilities such as seeing the federated account they used to sign on to a site, or resuming a session without the explicit sign-in flow of an expired session. this api is restricted to top-level contexts. calls to get() and store() within an <iframe> element will resolve without effect. subdomain-shared credentials later version of the spec allow credentials to be retrieved from a different subdomain. for example, a password stored in login.example.com may be used to log in to www...
...version of the spec allow credentials to be retrieved from a different subdomain. for example, a password stored in login.example.com may be used to log in to www.example.com. to take advantage of this, a password must be explicitly stored by calling credentialscontainer.store(). 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. it does not require it. hence browsers may vary in their implementation. interfaces credential provides information about an entity as a prerequisite to a trust decision. credentialscontainer exposes methods to request credentials and notify the user agent when interesting events occur such as successful sign in or sign out. this interfaces is accessib...
Crypto.getRandomValues() - Web APIs
exceptions this method can throw an exception under error conditions. domexception (name: quotaexceedederror) the requested length exceeds 65,536 bytes. usage notes don't use getrandomvalues() to generate encryption keys. instead, use the generatekey() method. there are a few reasons for this; for example, getrandomvalues() is not guaranteed to be running in a secure context. there is no minimum degree of entropy mandated by the web cryptography specification. 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 ...
...ad 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. examples /* assuming that window.crypto.getrandomvalues is available */ var array = new uint32array(10); window.crypto.getrandomvalues(array); console.log("your lucky numbers:"); for (var i = 0; i < array.length; i++) { console.log(array[i]); } specification specification status comment web cryptography api recommendation initial definition ...
DOMRect - Web APIs
Web › API › DOMRect
s for one eye of a head mounted display should be rendered. it inherits from its parent, domrectreadonly. ...
...r one eye of a head mounted display should be rendered. it inherits from its parent, domrectreadonly. ...
DataTransfer - Web APIs
ed for dragging if a custom one is desired. gecko methods note: all of the methods in this section are gecko-specific. datatransfer.addelement() sets the drag source to the given element. deprecated methods datatransfer.mozcleardataat() removes the data associated with the given format for an item at the specified index. the index is in the range from zero to the number of items minus one. removed in firefox 71. datatransfer.mozgetdataat() retrieves the data associated with the given format for an item at the specified index, or null if it does not exist. the index should be in the range from zero to the number of items minus one. removed in firefox 71. datatransfer.mozsetdataat() a data transfer may store multiple items, each at a given zero-based index. mozsetdataa...
...n index argument less than mozitemcount in which case an existing item is modified, or equal to mozitemcount in which case a new item is added, and the mozitemcount is incremented by one. removed in firefox 71. datatransfer.moztypesat() holds a list of the format types of the data that is stored for an item at the specified index. if the index is not in the range from 0 to the number of items minus one, an empty string list is returned. removed in firefox 71. examples every method and property listed in this document has its own reference page and each reference page either directly includes an example of the interface or has a link to an example. specifications specification status comment html living standardthe definition of 'datatransfer' in that specifica...
Detecting device orientation - Web APIs
in particular, hand-held devices such as mobile phones can use this information to automatically rotate the display to remain upright, presenting a wide-screen view of the web content when the device is rotated so that its width is greater than its height. there are two javascript events that handle orientation information. the first one is the deviceorientationevent, which is sent when the accelerometer detects a change to the orientation of the device. ...
...nclude sensors in laptops to protect moving storage devices. deviceorientationevent is more commonly found in mobile devices. processing orientation events all you need to do in order to begin receiving orientation change is to listen to the deviceorientation event: note: gyronorm.js is a polyfill for normalizing the accelerometer and gyroscope data on mobile devices. this is useful for overcoming some of the differences in device support for device orientation. window.addeventlistener("deviceorientation", handleorientation, true); after registering your event listener (in this case, a javascript function called handleorientation()), your listener function periodically gets called with updated orientation data. the orientation event contains four values: deviceorientationevent.abs...
Using light sensors - Web APIs
he light intensity of the device's environment. the devicelightevent provides a value attribute with light intensity in lux which is generally treated as shown below. 10 ~ 50 lux : dim environment 100 ~ 1000 lux : normal > 10000 lux : bright it uses the addeventlistener method of the window object. ...
...s environment. the devicelightevent provides a value attribute with light intensity in lux which is generally treated as shown below. 10 ~ 50 lux : dim environment 100 ~ 1000 lux : normal > 10000 lux : bright it uses the addeventlistener method of the window object. ...
Document.fullscreen - Web APIs
the obsolete document interface's fullscreen read-only property reports whether or not the document is currently displaying content in full-screen mode. although this property is read-only, it will not throw if it is modified (even in strict mode); the setter is a no-operation and it will be ignored. note: since this property is deprecated, you can determine if full-screen mode is active on the document by checking to see if document.fullscreenelement is not null. syntax var isfullscreen = document.fullscreen; value a boolean value which is true if the document is currently displaying an element in full-screen mode; otherwise, the value is false. example this simple function reports whether or not full-screen mode is currently active, using the obsolete fullscreen property. fun...
...if the document is currently displaying an element in full-screen mode; otherwise, the value is false. example this simple function reports whether or not full-screen mode is currently active, using the obsolete fullscreen property. function isdocumentinfullscreenmode() { return document.fullscreen; } this next example, on the other hand, uses the current fullscreenelement property to determine the same thing: function isdocumentinfullscreenmode() { return document.fullscreenelement !== null; } if fullscreenelement isn't null, this returns true, indicating that full-screen mode is in effect. specifications specification status comment fullscreen apithe definition of 'document.fullscreen' in that specification. living standard initial definition (...
Document.visibilityState - Web APIs
nt.visibilitystate read-only property returns the visibility of the document, that is in which context this element is now visible. it is useful to know if the document is in the background or an invisible tab, or only loaded for pre-rendering. possible values are: 'visible' the page content may be at least partially visible. in practice this means that the page is the foreground tab of a non-minimized window. 'hidden' the page content is not visible to the user. in practice this means that the document is either a background tab or part of a minimized window, or the os screen lock is active. 'prerender' the page content is being prerendered and is not visible to the user (considered hidden for purposes of document.hidden). the document may start in this state, but will never transi...
...t will never transition to it from another value. note: this was removed from the standard. check compatibility table for details. when the value of this property changes, the visibilitychange event is sent to the document. typical use of this can be to prevent the download of some assets when the document is solely prerendered, or stop some activities when the document is in the background or minimized. syntax var string = document.visibilitystate examples document.addeventlistener("visibilitychange", function() { console.log( document.visibilitystate ); // modify behavior... }); specifications specification status comment page visibility (second edition)the definition of 'document.visibilitystate' in that specification. recommendation initial defin...
Document: wheel event - Web APIs
he content's scrolling direction. therefore, do not rely on the wheel event's delta* properties to get the scrolling direction. instead, detect value changes of scrollleft and scrolltop in the scroll event. examples scaling an element via the wheel this example shows how to scale an element using the mouse (or other pointing device) wheel. ...
...-height: 100vh; margin: 0; display: flex; align-items: center; justify-content: center; } div { width: 105px; height: 105px; background: #cdf; padding: 5px; } function zoom(event) { event.preventdefault(); if (event.deltay < 0) { // 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 ...
DocumentType - Web APIs
the documenttype interface represents a node containing a doctype. ...
... the documenttype interface represents a node containing a doctype. ...
Events and the DOM - Web APIs
another. there is an excellent diagram that clearly explains the three phases of event flow through the dom in the dom level 3 events draft. also see example 5: event propagation in the examples chapter for a more detailed example of how events move through the dom. registering event listeners there are 3 ways to register event handlers for a dom element. eventtarget.addeventlistener // assuming mybutton is a button element mybutton.addeventlistener('click', greet, false) function greet(event){ // print and have a look at the event object // always print arguments in case of overlooking any other arguments console.log('greet:', arguments) alert('hello world') } this is the method you should use in modern web pages. note: internet explorer 6–8 didn't support this me...
..."> the javascript code in the attribute is passed the event object via the event parameter. the return value is treated in a special way, described in the html specification. warning: this method should be avoided! it inflates the markup, and makes it less readable. concerns of content/structure and behavior are not well-separated, making a bug harder to find. dom element properties // assuming mybutton is a button element mybutton.onclick = function(event){alert('hello world')} the function can be defined to take an event parameter. the return value is treated in a special way, described in the html specification. the problem with this method is that only one handler can be set per element and per event. accessing event interfaces event handlers may be attached to various objects...
Traversing an HTML table with JavaScript and DOM Interfaces - Web APIs
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 using body.appendchild(tbl); remember this technique. you will use it frequently in programming for the w3c dom. first, you create elements from the top down; then you attach the children to the parents from the bottom up. here's the html markup generated by the javascript code: ... <table border="2"> <tbody> <tr><td>cell is row 0 column 0</td><td>cell is row 0 column 1</td></tr> <tr><td>cell is row 1 column 0</td><td>cell is row 1 column 1</td></tr> </tbody> </table> ... here's the do...
...e border="2"> <tbody> <tr><td>cell is row 0 column 0</td><td>cell is row 0 column 1</td></tr> <tr><td>cell is row 1 column 0</td><td>cell is row 1 column 1</td></tr> </tbody> </table> ... 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. remember to keep in mind the tree model for the structures you are planning to create; this will make it easier to write the necessary code. in the <table> tree of figure 1 the element <table> has one child: the element <tbody>. <tbody> has two children. each <tbody>'s child (<tr>) has two children (<td>). finally, each <td> has one child: a text node. example: setting the background color of a paragraph getelementsby...
DynamicsCompressorNode() - Web APIs
ion. that can occur when multiple sounds are played and multiplexed together at once. syntax var dynamicscompressornode = new dynamicscompressornode(context, options) parameters context a reference to an audiocontext. options optional options are as follows: attack: the amount of time (in seconds) to reduce the gain by 10db. its default value is 0.003. this parameter is k-rate. its nominal range is [0, 1]. knee: a decibel value representing the range above the threshold where the curve smoothly transitions to the "ratio" portion. its default value is 30. this parameter is k-rate. its nominal range is [0, 40]. ratio: the amount of db change in input for a 1 db change in output. its default value is 12. this parameter is k-rate. its nominal range is [1, 20]. release: the amou...
...ansitions to the "ratio" portion. its default value is 30. this parameter is k-rate. its nominal range is [0, 40]. ratio: the amount of db change in input for a 1 db change in output. its default value is 12. this parameter is k-rate. its nominal range is [1, 20]. release: the amount of time (in seconds) to increase the gain by 10db. its default value is 0.250. this parameter is k-rate. its nominal range is [0, 1]. threshold: the decibel value above which the compression will start taking effect. its default value is -24. this parameter is k-rate. its nominal range is [-100, 0]. specifications specification status comment web audio apithe definition of 'dynamicscompressornode()' in that specification. working draft initial definition. browser ...
Element: auxclick event - Web APIs
u will often want to explicitly prevent other default actions mapped to the down action of the middle mouse button. on windows this is usually autoscroll, and on macos and linux this is usually clipboard paste. this can be done by preventing the default behaviour of the mousedown or pointerdown event. additionally, you may need to avoid opening a system context menu after a right click. due to timing differences between operating systems, this too is not a preventable default behavior of auxclick. instead, this can be done by preventing the default behavior of the contextmenu event. examples in this example we define functions for two event handlers — onclick and onauxclick. the former changes the color of the button background, while the latter changes the button foreground (text) color...
... specification specification status ui eventsthe definition of 'auxclick' in that specification. working draft ...
Element.getElementsByClassName() - Web APIs
however the following code will not work as one might expect because "matches" will change as soon as any "colorbox" class is removed. var matches = element.getelementsbyclassname('colorbox'); for (var i=0; i<matches.length; i++) { matc...
...ch are also a descendant of the element that has the id of main: document.getelementbyid('main').getelementsbyclassname('test'); matching multiple classes to find elements whose class lists include both the red and test classes: element.getelementsbyclassname('red test'); examining the results you can use either the item() method on the returned htmlcollection or standard array syntax to examine individual elements in the collection. however the following code will not work as one might expect because "matches" will change as soon as any "colorbox" class is removed. var matches = element.getelementsbyclassname('colorbox'); for (var i=0; i<matches.length; i++) { matches[i].classlist.remove('colorbox'); matches.item(i).classlist.add('hueframe'); } instead, use another method, such...
Element.innerHTML - Web APIs
Web › API › Element › innerHTML
's descendants and replaces them with nodes constructed by parsing the html given in the string htmlstring. exceptions syntaxerror an attempt was made to set the value of innerhtml using a string which is not properly-formed html. nomodificationallowederror an attempt was made to insert the html into a node whose parent is a document. usage notes the innerhtml property can be used to examine the current html source of the page, including any changes that have been made since the page was initially loaded. reading the html contents of an element reading innerhtml causes the user agent to serialize the html or xml fragment comprised of the element's descendants. the resulting string is returned. let contents = myelement.innerhtml; this lets you look at the html markup of the eleme...
...te is replaced with the new documentfragment created in step 1. for all other elements, the element's contents are replaced with the nodes in the new documentfragment. security considerations it is not uncommon to see innerhtml used to insert text into a web page. there is potential for this to become an attack vector on a site, creating a potential security risk. const name = "john"; // assuming 'el' is an html dom element el.innerhtml = name; // harmless in this case // ... name = "<script>alert('i am john in an annoying alert!')</script>"; el.innerhtml = name; // harmless in this case although this may look like a cross-site scripting attack, the result is harmless. html5 specifies that a <script> tag inserted with innerhtml should not execute. however, there are ways to execute j...
Element.scrollWidth - Web APIs
the width is measured in the same way as clientwidth: it includes the element's padding, but not its border, margin or vertical scrollbar (if present). it can also include the width of pseudo-elements such as ::before or ::after. ...
... <div id="anotherdiv"> foobar-foobar-foobar-foobar </div> <button id="anotherbutton"> check for overflow </button> </body> <script> var buttonone = document.getelementbyid('abutton'), buttontwo = document.getelementbyid('anotherbutton'), divone = document.getelementbyid('adiv'), divtwo = document.getelementbyid('anotherdiv'); //check to determine if an overflow is happening function isoverflowing(element) { return (element.scrollwidth > element.offsetwidth); } function alertoverflow(element) { if (isoverflowing(element)) { alert('contents are overflowing the container.'); } else { alert('no overflows!'); } } buttonone.addeventlistener('click', function() { ...
Element: wheel event - Web APIs
crolling direction. therefore, do not rely on the wheel event's delta* properties to get the scrolling direction. instead, detect value changes of scrollleft and scrolltop of the target in the scroll event. examples scaling an element via the wheel this example shows how to scale an element using the mouse (or other pointing device) wheel. ...
...ng the mouse (or other pointing device) wheel. ...
Element - Web APIs
Web › API › Element
outside the realm of the web platform, like xul through the xulelement interface, also implement element. ...
...side the realm of the web platform, like xul through the xulelement interface, also implement element. ...
ErrorEvent - Web APIs
the errorevent interface represents events providing information related to errors in scripts or in files. ...
... the errorevent interface represents events providing information related to errors in scripts or in files. ...
Comparison of Event Targets - Web APIs
this article should clarify the use of the target properties. there are five targets to consider: property defined in purpose event.target dom event interface the dom element on the lefthand side of the call that triggered this event, eg: element.dispatchevent(event) event.currenttarget dom event interface the eventtarget whose eventlisteners are currently being processed. as the event capturing and bubbling occurs, this value changes. event.relatedtarget dom mouseevent interface identifies a secondary target for the event. ...
... html> <html> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>comparison of event targets</title> <style> table { border-collapse: collapse; height: 150px; width: 100%; } td { border: 1px solid #ccc; font-weight: bold; padding: 5px; min-height: 30px; } .standard { background-color: #99ff99; } .non-standard { background-color: #902d37; } </style> </head> <body> <table> <thead> <tr> <td class="standard">original target dispatching the event <small>event.target</small></td> <td class="standard">target who's event listener is ...
EventSource - Web APIs
the eventsource interface is web content's interface to server-sent events. an eventsource instance opens a persistent connection to an http server, which sends events in text/event-stream format. the connection remains open until closed by calling eventsource.close(). once the connection is opened, incoming messages from the server are delivered to your code in the form of events. if there is an event field in the incoming message, the triggered event is the same as the event field value. if no event field is present, then a generic message event is fired. unlike websockets, server-sent events are unidirectional; that is, data messages are delivered in one direction, from the server to the client (such as a user's web browser). that makes them an excellent choice when there's no need to s...
...an indicating whether the eventsource object was instantiated with cross-origin (cors) credentials set (true), or not (false, the default). event handlers eventsource.onerror is an eventhandler called when an error occurs and the error event is dispatched on an eventsource object. eventsource.onmessage is an eventhandler called when a message event is received, that is when a message is coming from the source. eventsource.onopen is an eventhandler called when an open event is received, that is when the connection was just opened. methods this interface also inherits methods from its parent, eventtarget. eventsource.close() closes the connection, if any, and sets the readystate attribute to closed. if the connection is already closed, the method does nothing. events error...
EventTarget.addEventListener() - Web APIs
ener before being dispatched to any eventtarget beneath it in the dom tree. events that are bubbling upward through the tree will not trigger a listener designated to use capture. event bubbling and capturing are two ways of propagating events that occur in an element that is nested within another element, when both elements have registered a handle for that event. the event propagation mode determines the order in which elements receive the event. see dom level 3 events and javascript event order for a detailed explanation. if not specified, usecapture defaults to false. note: for event listeners attached to the event target, the event is in the target phase, rather than the capturing and bubbling phases. events in the target phase will trigger all listeners on an element in the order the...
...sing addeventlistener(), the value of this inside the handler is a reference to the element. it is the same as the value of the currenttarget property of the event argument that is passed to the handler. my_element.addeventlistener('click', function (e) { console.log(this.classname) // logs the classname of my_element console.log(e.currenttarget === this) // logs `true` }) as a reminder, arrow functions do not have their own this context. my_element.addeventlistener('click', (e) => { console.log(this.classname) // warning: `this` is not `my_element` console.log(e.currenttarget === this) // logs `false` }) if an event handler (for example, onclick) is specified on an element in the html source, the javascript code in the attribute value is effectively wrapped i...
EventTarget - Web APIs
ements, documents, and windows) also support setting event handlers via onevent properties and attributes. ...
...ts, documents, and windows) also support setting event handlers via onevent properties and attributes. ...
ExtendableEvent - Web APIs
ve paragraph was fixed in firefox 43 (see bug 1180274.) this interface inherits from the event interface. ...
...aragraph was fixed in firefox 43 (see bug 1180274.) this interface inherits from the event interface. ...
File - Web APIs
Web › API › File
d() accept both blobs and files. see using files from web applications for more information and examples. ...
...accept both blobs and files. see using files from web applications for more information and examples. ...
FocusEvent - Web APIs
the focusevent interface represents focus-related events, including focus, blur, focusin, and focusout. ...
...he focusevent interface represents focus-related events, including focus, blur, focusin, and focusout. ...
Using the Geolocation API - Web APIs
ly: if('geolocation' in navigator) { /* geolocation is available */ } else { /* geolocation is not available */ } getting the current position to obtain the user's current location, you can call the getcurrentposition() method. this initiates an asynchronous request to detect the user's position, and queries the positioning hardware to get up-to-date information. when the position is determined, the defined callback function is executed. you can optionally provide a second callback function to be executed if an error occurs. a third, optional, parameter is an options object where you can set the maximum age of the position returned, the time to wait for a request, and if you want high accuracy for the position. note: by default, getcurrentposition() tries to answer as fast as possib...
..., optional, parameter is an options object where you can set the maximum age of the position returned, the time to wait for a request, and if you want high accuracy for the position. note: by default, getcurrentposition() tries to answer as fast as possible with a low accuracy result. it is useful if you need a quick answer regardless of the accuracy. devices with a gps, for example, can take a minute or more to get a gps fix, so less accurate data (ip location or wifi) may be returned to getcurrentposition(). navigator.geolocation.getcurrentposition((position) => { dosomething(position.coords.latitude, position.coords.longitude); }); the above example will cause the dosomething() function to execute when the location is obtained. watching the current position if the position data ch...
GlobalEventHandlers.onwheel - Web APIs
on, while onscroll handles scrolling of an object's content. syntax target.onwheel = functionref; value functionref is a function name or a function expression. the function receives a wheelevent object as its sole argument. examples this example shows how to scale an element using the mouse (or other pointing device) wheel. ...
... living standard ...
HTMLAnchorElement - Web APIs
ents. ...
.... ...
HTMLAreaElement - Web APIs
nt interface it also has available to it by inheritance) for manipulating the layout and presentation of <area> elements. ...
...nterface it also has available to it by inheritance) for manipulating the layout and presentation of <area> elements. ...
msAudioCategory - Web APIs
background capable? alert looping or longer running alert sounds: alarms ring tones ringing notification sounds that need to attenuate existing audio no backgroundcapablemedia for audio that needs to continue playing in the background. ...
... alert looping or longer running alert sounds: alarms ring tones ringing notification sounds that need to attenuate existing audio no backgroundcapablemedia for audio that needs to continue playing in the background. examples include the following local media playback scenarios: local playlist streaming radio streaming playlist music videos streaming audio/radio, youtube, netflix, etc. yes communications for streaming communication audio such as the following: voip real time chat or other type of phone calls should not be used in non-real-time or non-communication scenarios, such as audio and/or video playback, as playback startup latency is affected. *...
HTMLAudioElement - Web APIs
l as methods to manipulate them. it's based on, and inherits properties and methods from, the htmlmediaelement interface. ...
... methods to manipulate them. it's based on, and inherits properties and methods from, the htmlmediaelement interface. ...
HTMLBRElement - Web APIs
the htmlbrelement interface represents a html line break element (<br>). it inherits from htmlelement. ...
... the htmlbrelement interface represents a html line break element (<br>). it inherits from htmlelement. ...
HTMLBaseElement - Web APIs
ase uri for a document. this object inherits all of the properties and methods as described in the htmlelement interface. ...
...uri for a document. this object inherits all of the properties and methods as described in the htmlelement interface. ...
HTMLBodyElement - Web APIs
ides special properties (beyond those inherited from the regular htmlelement interface) for manipulating <body> elements. ...
... special properties (beyond those inherited from the regular htmlelement interface) for manipulating <body> elements. ...
HTMLButtonElement - Web APIs
(beyond the regular htmlelement interface it also has available to it by inheritance) for manipulating <button> elements. ...
...ond the regular htmlelement interface it also has available to it by inheritance) for manipulating <button> elements. ...
HTMLCanvasElement - Web APIs
<canvas> elements. the htmlcanvaselement interface also inherits the properties and methods of the htmlelement interface. ...
...vas> elements. the htmlcanvaselement interface also inherits the properties and methods of the htmlelement interface. ...
HTMLDListElement - Web APIs
gular htmlelement interface it also has available to it by inheritance) for manipulating definition list (<dl>) elements. ...
...r htmlelement interface it also has available to it by inheritance) for manipulating definition list (<dl>) elements. ...
HTMLDataElement - Web APIs
s (beyond the regular htmlelement interface it also has available to it by inheritance) for manipulating <data> elements. ...
...eyond the regular htmlelement interface it also has available to it by inheritance) for manipulating <data> elements. ...
HTMLDataListElement - Web APIs
element object interface it also has available to it by inheritance) to manipulate <datalist> elements and their content. ...
...ent object interface it also has available to it by inheritance) to manipulate <datalist> elements and their content. ...
HTMLDetailsElement - Web APIs
beyond the regular htmlelement interface it also has available to it by inheritance) for manipulating <details> elements. ...
...nd the regular htmlelement interface it also has available to it by inheritance) for manipulating <details> elements. ...
HTMLDialogElement - Web APIs
face provides methods to manipulate <dialog> elements. it inherits properties and methods from the htmlelement interface. ...
... provides methods to manipulate <dialog> elements. it inherits properties and methods from the htmlelement interface. ...
HTMLDivElement - Web APIs
es (beyond the regular htmlelement interface it also has available to it by inheritance) for manipulating <div> elements. ...
...beyond the regular htmlelement interface it also has available to it by inheritance) for manipulating <div> elements. ...
HTMLDocument - Web APIs
ds the window.htmldocument property to include methods and properties that are specific to html documents. ...
...he window.htmldocument property to include methods and properties that are specific to html documents. ...
HTMLElement.dir - Web APIs
Web › API › HTMLElement › dir
ge systems). arabic languages and hebrew are typical languages using the rtl directionality. an image can have its dir property set to "rtl" in which case the html attributes title and alt will be formatted and defined as "rtl". when a table has its dir set to "rtl", the column order is arranged from right to left. when an element has its dir set to "auto", the direction of the element is determined based on its first strong directionality character, or default to the directionality of its parent element. browsers might allow users to change the directionality of <input> and <textarea>s in order to assist with authoring content. chrome and safari provide a directionality option in the contextual menu of input fields while internet explorer and edge use the key combinations ctrl + left sh...
... elementnodereference.dir = newwritingdirection; currentwritingdirection is a string variable representing the text writing direction of the current element. newwritingdirection is a string variable representing the text writing direction value. possible values for dir are ltr, for left-to-right, rtl, for right-to-left, and auto for specifying that the direction of the element must be determined based on the contents of the element. example var parg = document.getelementbyid("para1"); parg.dir = "rtl"; // change the text direction on a paragraph identified as "para1" specifications specification status comment html living standardthe definition of 'dir' in that specification. living standard no change from document object model (dom) level 2 html ...
HTMLEmbedElement - Web APIs
bedelement interface as defined in the standard. it does not address earlier, non-standardized version of the interface. ...
...lement interface as defined in the standard. it does not address earlier, non-standardized version of the interface. ...
HTMLFieldSetElement - Web APIs
nterface it also has available to it by inheritance) for manipulating the layout and presentation of <fieldset> elements. ...
...face it also has available to it by inheritance) for manipulating the layout and presentation of <fieldset> elements. ...
HTMLFormControlsCollection - Web APIs
erface's elements property. this interface replaces one method from htmlcollection, on which it is based. ...
...ce's elements property. this interface replaces one method from htmlcollection, on which it is based. ...
HTMLHRElement - Web APIs
es (beyond those of the htmlelement interface it also has available to it by inheritance) for manipulating <hr> elements. ...
...beyond those of the htmlelement interface it also has available to it by inheritance) for manipulating <hr> elements. ...
HTMLHeadElement - Web APIs
metadata, for a document. this object inherits all of the properties and methods described in the htmlelement interface. ...
...adata, for a document. this object inherits all of the properties and methods described in the htmlelement interface. ...
HTMLHeadingElement - Web APIs
nts the different heading elements, <h1> through <h6>. it inherits methods and properties from the htmlelement interface. ...
...the different heading elements, <h1> through <h6>. it inherits methods and properties from the htmlelement interface. ...
HTMLIFrameElement.referrerPolicy - Web APIs
s specified. the url is sent as a referrer when the protocol security level stays the same (http→http, https→https), but isn't sent to a less secure destination (https→http). origin only send the origin of the document as the referrer in all cases. the document https://example.com/page.html will send the referrer https://example.com/. origin-when-cross-origin send a full url when performing a same-origin request, but only send the origin of the document for other cases. same-origin a referrer will be sent for same-site origins, but cross-origin requests will contain no referrer information. strict-origin only send the origin of the document as the referrer when the protocol security level stays the same (https→https), but don't send it to a less secure destination (https→ht...
...for other cases. same-origin a referrer will be sent for same-site origins, but cross-origin requests will contain no referrer information. strict-origin only send the origin of the document as the referrer when the protocol security level stays the same (https→https), but don't send it to a less secure destination (https→http). strict-origin-when-cross-origin send a full url when performing a same-origin request, only send the origin when the protocol security level stays the same (https→https), and send no header to a less secure destination (https→http). unsafe-url send a full url when performing a same-origin or cross-origin request. this policy will leak origins and paths from tls-protected resources to insecure origins. carefully consider the impact of this setting. ...
HTMLIFrameElement - Web APIs
erface it also has available to it by inheritance) for manipulating the layout and presentation of inline frame elements. ...
...ce it also has available to it by inheritance) for manipulating the layout and presentation of inline frame elements. ...
HTMLImageElement.alt - Web APIs
age. syntax htmlimageelement.alt = alttext; let alttext = htmlimageelement.alt; value a domstring which contains the alternate text to display when the image is not loaded or for use by assistive devices. the alt attribute is officially mandatory; it's meant to always be specified. if the image doesn't require a fallback (such as for an image which is simply decorative or an advisory icon of minimal importance), you may specify an empty string (""). 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. usage notes the fundamental guideline for the alt attribute is that every image's alternate text should be able to replace the image without altering the meaning of the page. you should never use...
...the /me image is in a bitmapped format such as png or jpeg or in a vector format like svg. for a map, the alt text could be directions to the place indicated by the map, similarly to how you would explain it verbally. for a chart, the text could describe the items in the chart and their values. for a diagram, the text could be an explanation of the concept presented by the diagram. keep in mind that any text included in diagrams and charts presented in svg format may be read by screen readers. this may impact the decisions you make shen writing the alt text for the diagram. icons or logos logos (such as corporate or brand logos) and informational icons should use the corresponding text in their alt strings. that is, if an image is a corporate logo, the alt text should be the name of ...
HTMLImageElement.sizes - Web APIs
en more amazing content text. it's really spectacular. and fascinating. oh, it's also clever and witty. award-winning stuff, i'm sure.</p> <img src="/files/16870/new-york-skyline-wide.jpg" srcset="/files/16870/new-york-skyline-wide.jpg 3724w, /files/16869/new-york-skyline-4by3.jpg 1961w, /files/16871/new-york-skyline-tall.jpg 1060w" sizes="((min-width: 50em) and (max-width: 60em)) 50em, ((min-width: 30em) and (max-width: 50em)) 30em, (max-width: 30em) 20em"> <p>then there's even more amazing stuff to say down here. can you believe it? i sure can't.</p> <button id="break40">last width: 40em</button> <button id="break50">last width: 50em</button> </article> css article { margin: 1em; max-width:...
...0em) and (max-width: 60em)) 50em, ((min-width: 30em) and (max-width: 50em)) 30em, (max-width: 30em) 20em"> <p>then there's even more amazing stuff to say down here. ...
HTMLLIElement - Web APIs
hose defined by regular htmlelement interface it also has available to it by inheritance) for manipulating list elements. ...
... defined by regular htmlelement interface it also has available to it by inheritance) for manipulating list elements. ...
HTMLLabelElement - Web APIs
ccess to properties specific to <label> elements. it inherits methods and properties from the base htmlelement interface. ...
...s to properties specific to <label> elements. it inherits methods and properties from the base htmlelement interface. ...
HTMLLegendElement - Web APIs
llowing to access properties of the <legend> elements. it inherits properties and methods from the htmlelement interface. ...
...ing to access properties of the <legend> elements. it inherits properties and methods from the htmlelement interface. ...
HTMLLinkElement - Web APIs
s represented by htmlanchorelement). this object inherits all of the properties and methods of the htmlelement interface. ...
...presented by htmlanchorelement). this object inherits all of the properties and methods of the htmlelement interface. ...
HTMLMapElement - Web APIs
ement interface it also has available to it by inheritance) for manipulating the layout and presentation of map elements. ...
...t interface it also has available to it by inheritance) for manipulating the layout and presentation of map elements. ...
HTMLMarqueeElement - Web APIs
thods to manipulate <marquee> elements. it inherits properties and methods from the htmlelement interface. ...
...s to manipulate <marquee> elements. it inherits properties and methods from the htmlelement interface. ...
HTMLMediaElement.captureStream() - Web APIs
the capturestream() property of the htmlmediaelement interface returns a mediastream object which is streaming a real-time capture of the content being rendered in the media element. this can be used, for example, as a source for a webrtc rtcpeerconnection. syntax var mediastream = mediaelement.capturestream() parameters none. return value a mediastream object which can be used as a source for audio and/or video data by other media processing code, or as a source for webrtc. example in this example, an event handler is established so that clicking a button starts capturing the contents of a media element with the id "playback" into a mediastream. ...
...eturn value a mediastream object which can be used as a source for audio and/or video data by other media processing code, or as a source for webrtc. example in this example, an event handler is established so that clicking a button starts capturing the contents of a media element with the id "playback" into a mediastream. the stream can then be used for other purposes—like a source for streaming over webrtc, to allow sharing prerecorded videos with another person during a video call. document.queryselector('.playandrecord').addeventlistener('click', function() { var playbackelement = document.getelementbyid("playback"); var capturestream = playbackelement.capturestream(); playbackelement.play(); }); see recording a media element for a longer and more intricate example and expla...
HTMLMediaElement.onencrypted - Web APIs
event occurs, denoting the media is encrypted. this interface inherits from the extendableevent interface. ...
...t occurs, denoting the media is encrypted. this interface inherits from the extendableevent interface. ...
HTMLMediaElement.onwaitingforkey - Web APIs
s blocked while waiting for an encryption key. this interface inherits from the extendableevent interface. ...
...ocked while waiting for an encryption key. this interface inherits from the extendableevent interface. ...
HTMLMenuElement - Web APIs
efined on the regular htmlelement interface it also has available to it by inheritance) for manipulating <menu> elements. ...
...ed on the regular htmlelement interface it also has available to it by inheritance) for manipulating <menu> elements. ...
HTMLMenuItemElement - Web APIs
ed on the regular htmlelement interface it also has available to it by inheritance) for manipulating <menuitem> elements. ...
...n the regular htmlelement interface it also has available to it by inheritance) for manipulating <menuitem> elements. ...
HTMLMetaElement - Web APIs
criptive metadata about a document. it inherits all of the properties and methods described in the htmlelement interface. ...
...tive metadata about a document. it inherits all of the properties and methods described in the htmlelement interface. ...
HTMLModElement - Web APIs
terface they also have available to them by inheritance) for manipulating modification elements, that is <del> and <ins>. ...
...ace they also have available to them by inheritance) for manipulating modification elements, that is <del> and <ins>. ...
HTMLOListElement - Web APIs
on the regular htmlelement interface it also has available to it by inheritance) for manipulating ordered list elements. ...
...the regular htmlelement interface it also has available to it by inheritance) for manipulating ordered list elements. ...
HTMLObjectElement - Web APIs
to it by inheritance) for manipulating the layout and presentation of <object> element, representing external resources. ...
...it by inheritance) for manipulating the layout and presentation of <object> element, representing external resources. ...
HTMLOptGroupElement - Web APIs
ace they also have available to them by inheritance) for manipulating the layout and presentation of <optgroup> elements. ...
...they also have available to them by inheritance) for manipulating the layout and presentation of <optgroup> elements. ...
Option() - Web APIs
irst loaded. if this is not specified, a default value of false is used. note that a value of true does not set the option to selected if it is not already selected. selected optional a boolean that sets the option's selected state; the default is false (not selected). if omitted, even if the defaultselected argument is true, the option is not selected. ...
...d). if omitted, even if the defaultselected argument is true, the option is not selected. ...
HTMLOptionElement - Web APIs
mloptionelement interface represents <option> elements and inherits all classes and methods of the htmlelement interface. ...
...tionelement interface represents <option> elements and inherits all classes and methods of the htmlelement interface. ...
HTMLOptionsCollection - Web APIs
as well as optionally altering its items. this object is returned only by the options property of select. ...
...ell as optionally altering its items. this object is returned only by the options property of select. ...
HTMLOutputElement - Web APIs
and methods (beyond those inherited from htmlelement) for manipulating the layout and presentation of <output> elements. ...
... methods (beyond those inherited from htmlelement) for manipulating the layout and presentation of <output> elements. ...
HTMLParagraphElement - Web APIs
special properties (beyond those of the regular htmlelement object interface it inherits) for manipulating <p> elements. ...
...cial properties (beyond those of the regular htmlelement object interface it inherits) for manipulating <p> elements. ...
HTMLParamElement - Web APIs
manipulating <param> elements, representing a pair of a key and a value that acts as a parameter for an <object> element. ...
...pulating <param> elements, representing a pair of a key and a value that acts as a parameter for an <object> element. ...
HTMLPictureElement - Web APIs
he htmlpictureelement interface represents a <picture> html element. it doesn't implement specific properties or methods. ...
...tmlpictureelement interface represents a <picture> html element. it doesn't implement specific properties or methods. ...
HTMLPreElement - Web APIs
htmlelement interface it also has available to it by inheritance) for manipulating a block of preformatted text (<pre>). ...
...lelement interface it also has available to it by inheritance) for manipulating a block of preformatted text (<pre>). ...
HTMLQuoteElement - Web APIs
available to it by inheritance) for manipulating quoting elements, like <blockquote> and <q>, but not the <cite> element. ...
...lable to it by inheritance) for manipulating quoting elements, like <blockquote> and <q>, but not the <cite> element. ...
HTMLScriptElement.referrerPolicy - Web APIs
ed. the url is sent as a referrer when the protocol security level stays the same (e.g.http→http, https→https), but isn't sent to a less secure destination (e.g. https→http). origin only send the origin of the document as the referrer in all cases. the document https://example.com/page.html will send the referrer https://example.com/. origin-when-cross-origin send a full url when performing a same-origin request, but only send the origin of the document for other cases. same-origin a referrer will be sent for same-site origins, but cross-origin requests will contain no referrer information. strict-origin only send the origin of the document as the referrer when the protocol security level stays the same (e.g. https→https), but don't send it to a less secure destination (e.g. ...
...cases. same-origin a referrer will be sent for same-site origins, but cross-origin requests will contain no referrer information. strict-origin only send the origin of the document as the referrer when the protocol security level stays the same (e.g. https→https), but don't send it to a less secure destination (e.g. https→http). strict-origin-when-cross-origin send a full url when performing a same-origin request, only send the origin when the protocol security level stays the same (e.g. https→https), and send no header to a less secure destination (e.g. https→http). unsafe-url send a full url when performing a same-origin or cross-origin request. this policy will leak origins and paths from tls-protected resources to insecure origins. carefully consider the impact of this set...
HTMLScriptElement - Web APIs
udio/*), or text/csv. if the script is blocked, its element receives an error event; otherwise, it receives a load event. ...
.../*), or text/csv. if the script is blocked, its element receives an error event; otherwise, it receives a load event. ...
HTMLShadowElement - Web APIs
the htmlshadowelement interface represents a <shadow> html element, which is used in shadow dom. ...
... the htmlshadowelement interface represents a <shadow> html element, which is used in shadow dom. ...
HTMLSourceElement - Web APIs
the regular htmlelement object interface it also has available to it by inheritance) for manipulating <source> elements. ...
... regular htmlelement object interface it also has available to it by inheritance) for manipulating <source> elements. ...
HTMLSpanElement - Web APIs
<span> element and derives from the htmlelement interface, but without implementing any additional properties or methods. ...
...n> element and derives from the htmlelement interface, but without implementing any additional properties or methods. ...
HTMLStyleElement - Web APIs
ing dynamic styling information for an overview of the objects used to manipulate specified css properties using the dom. ...
...dynamic styling information for an overview of the objects used to manipulate specified css properties using the dom. ...
HTMLTableCaptionElement - Web APIs
nd the regular htmlelement interface it also has available to it by inheritance) for manipulating table caption elements. ...
...he regular htmlelement interface it also has available to it by inheritance) for manipulating table caption elements. ...
HTMLTableCellElement - Web APIs
heritance) for manipulating the layout and presentation of table cells, either header or data cells, in an html document. ...
...tance) for manipulating the layout and presentation of table cells, either header or data cells, in an html document. ...
HTMLTableColElement - Web APIs
htmlelement interface it also has available to it inheritance) for manipulating single or grouped table column elements. ...
...lelement interface it also has available to it inheritance) for manipulating single or grouped table column elements. ...
HTMLTableElement - Web APIs
e it also has available to it by inheritance) for manipulating the layout and presentation of tables in an html document. ...
... also has available to it by inheritance) for manipulating the layout and presentation of tables in an html document. ...
HTMLTableRowElement - Web APIs
erface it also has available to it by inheritance) for manipulating the layout and presentation of rows in an html table. ...
...ce it also has available to it by inheritance) for manipulating the layout and presentation of rows in an html table. ...
HTMLTableSectionElement - Web APIs
ritance) for manipulating the layout and presentation of sections, that is headers, footers and bodies, in an html table. ...
...nce) for manipulating the layout and presentation of sections, that is headers, footers and bodies, in an html table. ...
HTMLTemplateElement - Web APIs
the htmltemplateelement interface enables access to the contents of an html <template> element. ...
... the htmltemplateelement interface enables access to the contents of an html <template> element. ...
HTMLTimeElement - Web APIs
s (beyond the regular htmlelement interface it also has available to it by inheritance) for manipulating <time> elements. ...
...eyond the regular htmlelement interface it also has available to it by inheritance) for manipulating <time> elements. ...
HTMLTitleElement - Web APIs
contains the title for a document. this element inherits all of the properties and methods of the htmlelement interface. ...
...tains the title for a document. this element inherits all of the properties and methods of the htmlelement interface. ...
HTMLTrackElement - Web APIs
a child of either <audio> or <video> to specify a text track containing information such as closed captions or subtitles. ...
...ild of either <audio> or <video> to specify a text track containing information such as closed captions or subtitles. ...
HTMLUListElement - Web APIs
n the regular htmlelement interface it also has available to it by inheritance) for manipulating unordered list elements. ...
...e regular htmlelement interface it also has available to it by inheritance) for manipulating unordered list elements. ...
HTMLUnknownElement - Web APIs
d html element and derives from the htmlelement interface, but without implementing any additional properties or methods. ...
...ml element and derives from the htmlelement interface, but without implementing any additional properties or methods. ...
In depth: Microtasks and the JavaScript runtime environment - Web APIs
that's what this section covers introduction javascript is an inherently single-threaded language. it was designed in an era in which this was a positive choice; there were few multi-processor computers available to the general public, and the expected amount of code that would be handled by javascript was relatively low at that time. ...
...nt loop a worklet event loop is the event loop used to drive agents which run the code for the workelets for a given agent. this includes worklets of type worklet, audioworklet, and paintworklet. several windows loaded from the same origin may be running on the same event loop, each queueing tasks onto the event loop so that their tasks take turns with the processor, one after another. keep in mind that web parlance, the word "window" actually means "browser-level container that web content runs within," including an actual window, a tab, or a frame. there are specific circumstances in which this sharing of an event loop among windows with a common origin is possible, such as: if one window opened the other window, they are likely to be sharing an event loop. if a window is actually a...
Using microtasks in JavaScript with queueMicrotask() - Web APIs
be added to the task queue. the event loop driving your code handles these tasks one after another, in the order in which they were enqueued. only tasks which were already in the task queue when the event loop pass began will be executed during the current iteration. the rest will have to wait until the following iteration. microtasks at first the difference between microtasks and tasks seems minor. and they are similar; both are made up of javascript code which gets placed on a queue and run at an appropriate time. however, whereas the event loop runs only the tasks present on the queue when the iteration began, one after another, it handles the microtask queue very differently. there are two key differences. first, each time a task exits, the event loop checks to see if the task is re...
...ow or worker interface, depending on the current execution context. queuemicrotask(() => { /* code to run in the microtask here */ }); the microtask function itself takes no parameters, and does not return a value. when to use microtasks in this section, we'll take a look at scenarios in which microtasks are particularly useful. generally, it's about capturing or checking results, or performing cleanup, after the main body of a javascript execution context exits, but before any event handlers, timeouts and intervals, or other callbacks are processed. when is that useful? the main reason to use microtasks is simply that: to ensure consistent ordering of tasks, even when results or data is available synchronously, but while simultaneously reducing the risk of user-discernible delays in...
Dragging and Dropping Multiple Items - Web APIs
output(" " + types[t] + ": "); try { var data = dt.mozgetdataat(types[t], i); output("(" + (typeof data) + ") : <" + data + " >\n"); } catch (ex) { output("<<error>>\n"); dump(ex); } } } } function output(text) { document.getelementbyid("output").textcontent += text; dump(text); } </script> </head> <body> <div id="output" style="min-height: 100px; white-space: pre; border: 1px solid black;" ondragenter="document.getelementbyid('output').textcontent = ''; event.stoppropagation(); event.preventdefault();" ondragover="event.stoppropagation(); event.preventdefault();" ondrop="event.stoppropagation(); event.preventdefault(); dodrop(event);"> <div> fix</div> </div> </body> </html> this example cancels both the ...
...his allows a drop to occur on that element. the dodrop event hander is called when dropping an item. it checks the mozitemcount property to check how many items have been dropped and iterates over them. for each item, the moztypesat() method is called to get the list of types. this list is iterated over to get all of the data associated with the drag. this processing is useful if you wish to examine the data that a drag is holding. simply drop an item on the drop target in the example to see what items, formats and data was being dragged. see also html drag and drop api (overview) drag operations recommended drag types html5 living standard: drag and drop ...
HashChangeEvent - Web APIs
url has changed. the fragment identifier is the part of the url that follows (and includes) the # symbol. ...
...has changed. the fragment identifier is the part of the url that follows (and includes) the # symbol. ...
IDBCursorWithValue - Web APIs
ns are performed on the underlying index or object store. note: this feature is available in web workers. ...
...re performed on the underlying index or object store. note: this feature is available in web workers. ...
IDBDatabase: abort event - Web APIs
st = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; db.addeventlistener('abort', () => { console.log('transaction aborted'); }); // open a...
...st = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; db.onabort = () => { console.log('transaction aborted'); }; // open a read/write db tr...
IDBDatabase: close event - Web APIs
st = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; db.addeventlistener('close', () => { console.log('database connection closed'); }); }; ...
...st = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; db.onclose = () => { console.log('database connection closed'); }; }; ...
IDBDatabase: error event - Web APIs
st = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const db = dbopenrequest...
...st = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const db = dbopenrequest...
IDBDatabase: versionchange event - Web APIs
st = 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 objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.addeventlistener('success', event => { const db = event.target.result; db.addeventlistener('versionchange', event => { console.log('the version of thi...
...st = 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 objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = event => { const db = event.target.result; db.onversionchange = event => { console.log('the version of this database has changed'); }; ...
IDBObjectStore.add() - Web APIs
the add() method of the idbobjectstore interface returns an idbrequest object, and, in a separate thread, creates a structured clone of the value, and stores the cloned value in the object store. this is for adding new records to an object store. to determine if the add operation has completed successfully, listen for the transaction’s complete event in addition to the idbobjectstore.add request’s success event, because the transaction may still fail after the success event fires. in other words, the success event is only triggered when the transaction has been successfully queued. the add method is an insert only method. if a record already exists in the object store with the key parameter as its key, then an error constrainerror event is fired on the returned request object. for up...
...event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBObjectStore.createIndex() - Web APIs
note that this method must be called only from a versionchange transaction mode callback. note: this feature is available in web workers. ...
...= event.target.result; db.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; // 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 }); objectstore.createindex("day", "day", { unique: false }); objectstore.createindex("month", "month", { unique: false }); objectstore.createindex("year", "year", { unique: false }); objectstore.createindex("notified", "notified", { unique: false }); }; specifications specification status comment indexed database api 2.0the de...
IDBObjectStore.name - Web APIs
event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
... opera full support yessafari ? webview android fu...
IDBObjectStore - Web APIs
db = event.target.result; db.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; // 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 }); objectstore.createindex("day", "day", { unique: false }); objectstore.createindex("month", "month", { unique: false }); objectstore.createindex("year", "year", { unique: false }); objectstore.createindex("notified", "notified", { unique: false }); note.innerhtml += '<li>object store created.</li>'; }; // create a new item to add in to the object s...
...ndex("day", "day", { unique: false }); objectstore.createindex("month", "month", { unique: false }); objectstore.createindex("year", "year", { unique: false }); objectstore.createindex("notified", "notified", { unique: false }); note.innerhtml += '<li>object store created.</li>'; }; // create a new item to add in to the object store var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: 'december', year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed.</li>'; }; transaction.onerror = ...
IDBOpenDBRequest: blocked event - Web APIs
ed = (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 }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { 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 c...
...ed = (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 }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { 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 c...
IDBRequest: success event - Web APIs
ed = (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 }); 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...
...ed = (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 }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; openrequest.onsuccess = (event) => { console.log('database opened successfully!'); }; ...
IDBTransaction: abort event - Web APIs
eded = 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 }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transacti...
...eded = 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 }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transacti...
IdleDeadline - Web APIs
to learn more about how request callbacks work, see collaborative scheduling of background tasks. ...
... to learn more about how request callbacks work, see collaborative scheduling of background tasks. ...
IndexedDB API - Web APIs
erefore the entry point for the api. idbopendbrequest represents a request to open a database. idbdatabase represents a connection to a database. it's the only way to get a transaction on the database. retrieving and modifying data idbtransaction represents a transaction. you create a transaction on a database, specify the scope (such as which object stores you want to access), and determine the kind of access (read only or readwrite) that you want. idbrequest generic interface that handles database requests and provides access to results. idbobjectstore represents an object store that allows access to a set of data in an indexeddb database, looked up via primary key. idbindex also allows access to a subset of data in an indexeddb database, but uses an index to retrieve the re...
...quest represents a request to change the version of a database. the way to change the version of the database has since changed (by calling idbfactory.open without also calling idbdatabase.setversion), and the interface idbopendbrequest now has the functionality of the removed idbversionchangerequest. idbdatabaseexception represents exception conditions that can be encountered while performing database operations. idbtransactionsync sync version of idbtransaction. idbobjectstoresync sync version of idbobjectstore. idbindexsync sync version of idbindex. idbfactorysync sync version of idbfactory. idbenvironmentsync sync version of idbenvironment. idbdatabasesync sync version of idbdatabase. idbcursorsync sync version of idbcursor. examples elibri: a powe...
InputEvent - Web APIs
the inputevent interface represents an event notifying of editable content change. ...
... the inputevent interface represents an event notifying of editable content change. ...
InstallEvent - Web APIs
event are not dispatched during installation. this interface inherits from the extendableevent interface. ...
...t are not dispatched during installation. this interface inherits from the extendableevent interface. ...
KeyboardEvent.code - Web APIs
t devices. 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. be aware, however, that you can't use the value reported by keyboardevent.code to determine the character generated by the keystroke, because the keycode's name may not match the actual character that's printed on the key or that's generated by the computer when the key is pressed. for example, the code returned is "keyq" for the q key on a qwerty layout keyboard, but the same code value also represents the ' key on dvorak keyboards and the a key on azerty keyboards. that makes it imp...
...e, because the keycode's name may not match the actual character that's printed on the key or that's generated by the computer when the key is pressed. for example, the code returned is "keyq" for the q key on a qwerty layout keyboard, but the same code value also represents the ' key on dvorak keyboards and the a key on azerty keyboards. 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. to determine what character corresponds with the key event, use the keyboardevent.key property instead. code values the code values for windows, linux, and macos are list on the keyboardevent: code values page. examples exercising keyboardevent html <p>press keys on the keyboard to see what the keybo...
KeyboardEvent.key - Web APIs
Web › API › KeyboardEvent › key
if the pressed key has a printed representation, the returned value is a non-empty unicode character string containing the printable representation of the key. if the pressed key is a control or special character, the returned value is one of the pre-defined key values. ...
...edia on multimedia keyboards) don't generate key codes on windows; instead, they trigger wm_appcommand events. these events get mapped to dom keyboard events, and are listed among the "virtual key codes" for windows, even though they aren't actually key codes. if the key cannot be identified, the returned value is unidentified. keyboardevent sequence every keyboardevent is fired in a pre-determined sequence. for a given key press, the sequence of keyboardevents fired is as follows assuming that event.preventdefault is not called: a keydown event is first fired. if the key is held down further and the key produces a character key, then the event continues to be emitted in a platform implementation dependent interval and the keyboardevent.repeat read only property is set to true. if the...
KeyboardEvent - Web APIs
is using an alternate means of entering text, such as a handwriting system on a tablet or graphics tablet. ...
...sing an alternate means of entering text, such as a handwriting system on a tablet or graphics tablet. ...
Keyboard API - Web APIs
associated with the key labeled w on an english qwerty keyboard. if (navigator.keyboard) { var keyboard = navigator.keyboard; keyboard.getlayoutmap() .then(keyboardlayoutmap => { var upkey = keyboardlayoutmap.get('keyw'); window.alert('press ' + upkey + ' to move up.'); }); } else { // do something else. } keyboard locking richly interactive web pages, games, and remote-streaming experiences often require access to special keys and keyboard shortcuts while in full-screen mode. examples of such key/key combinations include escape, alt+tab, and ctrl+n. those keys and key combinations are typically captured by the user agent or the underlying operating system, as illustrated in the following example. to capture the "w", "a", "s", and "d" keys, call lock() with a list that ...
... typically captured by the user agent or the underlying operating system, as illustrated in the following example. to capture the "w", "a", "s", and "d" keys, call lock() with a list that contains the key code attribute value for each of these keys: navigator.keyboard.lock(["keyw", "keya", "keys", "keyd"]); this captures these keys regardless of which modifiers are used with the key press. assuming a standard united states qwerty layout, registering keyw ensures that "w", shift+"w", control+"w", control+shift+"w", and all other key modifier combinations with "w" are sent to the app. the same applies to for keya, keys and keyd. writing system keys the codes passed keyboard.lock and the various methods of the keyboardlayoutmap interface are called “writing system keys”. “writing sys...
KeyframeEffect.KeyframeEffect() - Web APIs
tion optional whether the animation runs forwards (normal), backwards (reverse), switches direction after each iteration (alternate), or runs backwards and switches direction after each iteration (alternate-reverse). defaults to "normal". duration optional the number of milliseconds each iteration of the animation takes to complete. defaults to 0. although this is technically optional, keep in mind that your animation will not run if this value is 0. easing optional the rate of the animation's change over time. accepts the pre-defined values "linear", "ease", "ease-in", "ease-out", and "ease-in-out", or a custom "cubic-bezier" value like "cubic-bezier(0.42, 0, 0.58, 1)". defaults to "linear". enddelay optional the number of milliseconds to delay after the end of an animation. this is p...
...art. 0.5 would indicate starting halfway through the first iteration for example, and with this value set, an animation with 2 iterations would end halfway through a third iteration. defaults to 0.0. iterations optional the number of times the animation should repeat. defaults to 1, and can also take a value of infinity to make it repeat for as long as the element exists. composite determines how values are combined between this animation and the element's underlying values. iterationcomposite determines how values build from iteration to iteration in the current animation. the second type of constructor (see above) creates a clone of an existing keyframeeffect object instance. its parameter is as follows: sourcekeyframes a keyframeeffect object that you want to clone...
KeyframeEffect - Web APIs
mposite gets and sets the iteration composite operation for resolving the property value changes of this keyframe effect. keyframeeffect.composite gets and sets the composite operation property for resolving the property value changes between this and other keyframe effects. methods this interface inherits some of its methods from its parent, animationeffect. animationeffect.getcomputedtiming() returns the calculated, current timing values for this keyframe effect. keyframeeffect.getkeyframes() returns the computed keyframes that make up this effect along with their computed keyframe offsets. animationeffect.gettiming() the effecttiming object associated with the animation containing all the animation's timing values. keyframeeffect.setkeyframes() replaces the set of keyfra...
...this keyframe effect. keyframeeffect.getkeyframes() returns the computed keyframes that make up this effect along with their computed keyframe offsets. animationeffect.gettiming() the effecttiming object associated with the animation containing all the animation's timing values. keyframeeffect.setkeyframes() replaces the set of keyframes that make up this effect. animationeffect.updatetiming() updates the specified timing properties. examples in the follow the white rabbit example, the keyframeeffect constructor is used to create a set of keyframes that dictate how the white rabbit should animate down the hole: var rabbitdownkeyframes = new keyframeeffect( whiterabbit, // element to animate [ { transform: 'translatey(0%)' }, // keyframe { transform: 'trans...
LargestContentfulPaint - Web APIs
the largestcontentfulpaint interface of the largest contentful paint api provides details about the largest image or text paint before user input on a web page. the timing of this paint is a good heuristic for when the main page content is available during load. properties largestcontentfulpaint.element the element that is the current largest contentful paint. largestcontentfulpaint.rendertime the time the element was rendered to the screen. may not be available if the element is a cross-origin image loaded without the timing-allow-origin header. largestcontentfulpaint.loadtime the time the element was loaded. largestcontentfulpaint.size the intrinsic size of the element returned as the area (width * height). largestcontentfulpaint.id the id of the element. this property ...
...ug.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`. (note: `rendertime` may not be available on // image elements loaded cross-origin without the `timing-allow-origin` header.) lcp = lastentry.rendertime || lastentry.loadtime; }); po.observe({type: 'largest-contentful-paint', buffered: true}); // send data to the server. addeventlistener('visibilitychange', function fn() { if (lcp && document.visibilitystate === 'hidden') { console.log('lcp:', lcp); removeeventlistener('visibilitychange', fn, true); } }, true);...
MediaError.message - Web APIs
syntax var errormessage = mediaerror.message; value a domstring providing a detailed, specific explanation of what went wrong and possibly how it might be fixed. ...
...rred."; break; } let message = err.message; if (message && message.length) { s += " " + message; } displayerrormessage("<strong>error " + err.code + ":</strong> " + s + "<br>"); }; this gets the mediaerror object describing the error from the error property on the htmlaudioelement representing the audio player. the error's code attribute is checked to determine a generic error message to display, and, if message is not empty, it's appended to provide additional details. then the resulting text is output to the log. result you can try out this example below, and can see the example in action outside this page here. specifications specification status comment html living standardthe definition of 'mediaerror.message' in that...
MediaKeyMessageEvent - Web APIs
tains the content and related data when the content decryption module generates a message for the session. ...
...s the content and related data when the content decryption module generates a message for the session. ...
MediaKeySession.onkeystatuseschange - Web APIs
n the keys or their statuses within a session. this interface inherits from the extendableevent interface. ...
...e keys or their statuses within a session. this interface inherits from the extendableevent interface. ...
MediaKeySession.onmessage - Web APIs
is generated by the content decryption module. this interface inherits from the extendableevent interface. ...
...enerated by the content decryption module. this interface inherits from the extendableevent interface. ...
MediaRecorder.mimeType - Web APIs
the mimetype read-only property returns the mime media type that was specified when creating the mediarecorder object, or, if none was specified, which was chosen by the browser. this is the file format of the file that would result from writing all of the recorded data to disk. 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. see our media type and format guide for information about container and codec support across browsers. note: the term "mime type" is officially considered to be historical; these strings are now officially known as media types. mdn web docs content uses the terms interchangeably. syn...
... 'video/mp4' ... }) .catch(function(error) { console.log(error.message); }); changing line 14 to the following causes mediarecorder to try to use avc constrained baseline profile level 4 for video and aac-lc (low complexity) for audio, which is good for mobile and other possible resource-constrained situations. mimetype: 'video/mp4; codecs="avc1.424028, mp4a.40.2"' assuming this configuration is acceptable to the user agent, the value returned later by m.mimetype would then be video/mp4; codecs="avc1.424028, mp4a.40.2". specifications specification status comment mediastream recordingthe definition of 'mediarecorder.mimetype' in that specification. working draft initial definition ...
MediaRecorderErrorEvent.error - Web APIs
syntax error = mediarecordererrorevent.error; value a domexception describing the error represented by the event. ...
... syntax error = mediarecordererrorevent.error; value a domexception describing the error represented by the event. ...
Media Session action types - Web APIs
user's headset or earbuds. examples adding action handlers this example implements seek forward and backward actions for an audio player by setting up the seekforward and seekbackward action handlers. let skiptime = 10; // time to skip in seconds navigator.mediasession.setactionhandler('seekforward', evt => { // user clicked "seek forward" media notification icon. audio.currenttime = math.min(audio.currenttime + skiptime, audio.duration); }); navigator.mediasession.setactionhandler('seekbackward', evt => { // user clicked "seek backward" media notification icon. audio.currenttime = math.max(audio.currenttime - skiptime, 0); }); supporting multiple actions in one handler function you can also, if you prefer, use a single function to handle multiple action types, ...
... specifications specification status comment media session standardthe definition of 'media session ac...
MediaSessionActionDetails - Web APIs
user's headset or earbuds. examples adding action handlers this example implements seek forward and backward actions for an audio player by setting up the seekforward and seekbackward action handlers. let skiptime = 10; // time to skip in seconds navigator.mediasession.setactionhandler('seekforward', evt => { // user clicked "seek forward" media notification icon. audio.currenttime = math.min(audio.currenttime + skiptime, audio.duration); }); navigator.mediasession.setactionhandler('seekbackward', evt => { // user clicked "seek backward" media notification icon. audio.currenttime = math.max(audio.currenttime - skiptime, 0); }); supporting multiple actions in one handler function you can also, if you prefer, use a single function to handle multiple action types, ...
... specifications specification status comment media session standardthe definition of 'media session ac...
MediaSettingsRange - Web APIs
the mediasettingsrange interface of the the mediastream image capture api provides the possible range and value size of photocapabilities.imageheight and photocapabilities.imagewidth. a photocapabilities object can be retrieved by calling imagecapture.photocapabilities(). properties mediasettingsrange.max returns the maximum value of this settings. mediasettingsrange.min returns the minimum value of this setting. mediasettingsrange.step returns the minimum difference between consecutive values of this setting. example the following example, extracted from chrome's image capture / photo resolution sample, uses the results from getphotocapabilities().imagewidth to modify the size of an input range. const input = document.queryselector('input[type="range"]'); var imagecapt...
...e="range"]'); var imagecapture; navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); return imagecapture.getphotocapabilities(); }) .then(photocapabilities => { const settings = imagecapture.track.getsettings(); input.min = photocapabilities.imagewidth.min; input.max = photocapabilities.imagewidth.max; input.step = photocapabilities.imagewidth.step; return imagecapture.getphotosettings(); }) .then(photosettings => { input.value = photosettings.imagewidth; }) .catch(error => console.log('argh!', error.name || error)); specifications specification status comment mediastream image c...
MediaSource.endOfStream() - Web APIs
this can be used create a custom error handler related to media streams. ...
...u might have a function that handles media chunk requests, separate from other network requests. when you make an xmlhttprequest call for a media chunk, and onabort or onerror triggers, you might want to call endofstream('network'), display a descriptive message in the ui, and maybe retry the network request immediately or wait until the network is back up (via some kind of polling.) decode: terminates playback and signals that a decoding error has occured. 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. return value undefined exceptions exception explanation invalidstateerror mediasource.readystate is not equal to ...
MediaSource - Web APIs
element object. a mediasource object can be attached to a htmlmediaelement to be played in the user agent. ...
...ent object. a mediasource object can be attached to a htmlmediaelement to be played in the user agent. ...
MediaStreamTrackEvent - Web APIs
m through calls to media stream api methods. these events are sent to the stream when these changes occur. ...
...rough calls to media stream api methods. these events are sent to the stream when these changes occur. ...
Using the MediaStream Recording API - Web APIs
o the basic app setup section. keeping the interface constrained to the viewport, regardless of device height, with calc() the calc() function is one of those useful little utility features that's cropped up in css that doesn't look like much initially, but soon starts to make you think "wow, why didn't we have this before? why was css2 layout so awkward?" it allows you do a calculation to determine the computed value of a css unit, mixing different units in the process. for example, in web dictaphone we have three main ui areas, stacked vertically. we wanted to give the first two (the header and the controls) fixed heights: header { height: 70px; } .main-controls { padding-bottom: 0.7rem; height: 170px; } however, we wanted to make the third area (which contains the recorded samp...
... padding-bottom: 0.7rem; height: 170px; } however, we wanted to make the third area (which contains the recorded samples you can play back) take up whatever space is left, regardless of the device height. flexbox could be the answer here, but it's a bit overkill for such a simple layout. instead, the problem was solved by making the third container's height equal to 100% of the parent height, minus the heights and padding of the other two: .sound-clips { box-shadow: inset 0 3px 4px rgba(0,0,0,0.7); background-color: rgba(0,0,0,0.1); height: calc(100% - 240px - 0.7rem); overflow: scroll; } note: calc() has good support across modern browsers too, even going back to internet explorer 9. checkbox hack for showing/hiding this is fairly well documented already, but we thought we'...
MediaTrackConstraints.aspectRatio - Web APIs
however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. ...
...080, or 1.7777777778. if this value is a number, the user agent will attempt to obtain media whose aspect ratio is as close as possible to this number given the capabilities of the hardware and the other constraints specified. otherwise, the value of this constraindouble will guide the user agent in its efforts to provide an exact match to the required aspect ratio (if exact is specified or both min and max are provided and have the same value) or to a best-possible value. example see example: constraint exerciser in capabilities, constraints, and settings for an example. specifications specification status comment media capture and streamsthe definition of 'aspectratio' in that specification. candidate recommendation initial specification. ...
MediaTrackConstraints.channelCount - Web APIs
however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. ...
...= constraint; value if this value is a number, the user agent will attempt to obtain media whose channel count is as close as possible to this number given the capabilities of the hardware and the other constraints specified. otherwise, the value of this constrainlong will guide the user agent in its efforts to provide an exact match to the required channel count (if exact is specified or both min and max are provided and have the same value) or to a best-possible value. the channel count is 1 for monaural sound, 2 for stereo, and so forth. example see example: constraint exerciser in capabilities, constraints, and settings for an example. specifications specification status comment media capture and streamsthe definition of 'channelcount' in that specifica...
MediaTrackConstraints.cursor - Web APIs
the mediatrackconstraints dictionary's cursor property is a constraindomstring describing the requested or mandatory constraints placed upon the value of the cursor constrainable property, which is used to specify whether or not the cursor should be included in the captured video. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.cursor as returned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var constraintsobject = { cursor: constraint }; constraintsobject.cursor = constraint; value a constraindomstring which specifies whether or not the mouse cursor should be rendered into the v...
...e user agent after the display media has been created by getdisplaymedia() by calling getsettings() on the display media's video mediastreamtrack, then checking the value of the returned mediatracksettings object's cursor object. 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. later code can detect this flag's value and if it's true, can manually look at some metadata that might b...
MediaTrackConstraints.deviceId - Web APIs
however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. ...
... constraint }; constraintsobject.deviceid = constraint; value an object based on constraindomstring specifying one or more acceptable, ideal, and/or exact (mandatory) device ids which are acceptable as the source of media content. device ids are unique for a given origin, and are guaranteed to be the same across browsing sessions on the same origin. however, the value of the deviceid is determined by the source of the track's content, and there's no particular format mandated by the specification (although some kind of guid is recommended). that means that a given track will only return one value for the deviceid when you call getcapabilities(). because of this, there's no use for the device id when calling mediastreamtrack.applyconstraints(), since there is only one possible value; how...
MediaTrackConstraints.displaySurface - Web APIs
the mediatrackconstraints dictionary's displaysurface property is a constraindomstring describing the requested or mandatory constraints placed upon the value of the displaysurface constrainable property. this is used to specify the type or types of display surfaces which getdisplaymedia() will let the user select among for sharing purposes. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.displaysurface as returned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var constraintsobject = { displaysurface: constraint }; constraintsobject.displaysurface = constraint; value a constraind...
...aysurface = displaystream.getvideotracks()[0].getsettings().displaysurface; if (displaysurface === "monitor" || displaysurface ==="application") { mayhavebackdropflag = true; } following this code, mayhavebackdrop is true if the display surface contained in the stream is of type monitor or application; either of these may have non-content backdrop areas. later code can use this flag to determine whether or not to perform special processing, such as to remove or replace the backdrop, or to "cut" the individual display areas out of the received frames of video. examples here are some example constraints objects for getdisplaymedia() that make use of the displaysurface property. in addition, see example: constraint exerciser in capabilities, constraints, and settings for a complete examp...
MediaTrackConstraints.frameRate - Web APIs
however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. ...
...te, in frames per second. if this value is a number, the user agent will attempt to obtain media whose frame rate is as close as possible to this number given the capabilities of the hardware and the other constraints specified. otherwise, the value of this constraindouble will guide the user agent in its efforts to provide an exact match to the required frame rate (if exact is specified or both min and max are provided and have the same value) or to a best-possible value. example see example: constraint exerciser in capabilities, constraints, and settings for an example. specifications specification status comment media capture and streamsthe definition of 'framerate' in that specification. candidate recommendation initial specification. ...
MediaTrackConstraints.groupId - Web APIs
however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. ...
...media sources that come from the same physical device. for example, the microphone and speaker on the same headset would share a group id. this makes it possible to use the group id to ensure that the audio and input devices are on the same headset by retrieving the group id of the input device and specifying it when asking for an output device, perhaps. however, the value of the groupid is determined by the source of the track's content, and there's no particular format mandated by the specification (although some kind of guid is recommended). that means that a given track will only return one value for the groupid when you call getcapabilities(), and keep in mind that this value will change for each browsing session. because of this, there's no use for the group id when calling mediastrea...
MediaTrackConstraints.height - Web APIs
however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. ...
...object.height = constraint; value if this value is a number, the user agent will attempt to obtain media whose height is as close as possible to this number given the capabilities of the hardware and the other constraints specified. otherwise, the value of this constrainlong will guide the user agent in its efforts to provide an exact match to the required height (if exact is specified or both min and max are provided and have the same value) or to a best-possible value. example see example: constraint exerciser in capabilities, constraints, and settings for an example. specifications specification status comment media capture and streamsthe definition of 'height' in that specification. candidate recommendation initial specification. ...
MediaTrackConstraints.latency - Web APIs
however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. ...
...acceptable. if this property's value is a number, the user agent will attempt to obtain media whose latency tends to be as close as possible to this number given the capabilities of the hardware and the other constraints specified. otherwise, the value of this constraindouble will guide the user agent in its efforts to provide an exact match to the required latency (if exact is specified or both min and max are provided and have the same value) or to a best-possible value. latency is always prone to some variation due to hardware usage demands, network constraints, and so forth, so even in an "exact" match, some variation should be expected. example see example: constraint exerciser in capabilities, constraints, and settings for an example. specifications specification sta...
MediaTrackConstraints.sampleRate - Web APIs
however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. ...
...ate = constraint; value if this value is a number, the user agent will attempt to obtain media whose sample rate is as close as possible to this number given the capabilities of the hardware and the other constraints specified. otherwise, the value of this constrainlong will guide the user agent in its efforts to provide an exact match to the required sample rate (if exact is specified or both min and max are provided and have the same value) or to a best-possible value. example see example: constraint exerciser in capabilities, constraints, and settings for an example. specifications specification status comment media capture and streamsthe definition of 'samplerate' in that specification. candidate recommendation initial specification. ...
MediaTrackConstraints.sampleSize - Web APIs
however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. ...
...f this value is a number, the user agent will attempt to obtain media whose sample size (in bits per linear sample) is as close as possible to this number given the capabilities of the hardware and the other constraints specified. otherwise, the value of this constrainlong will guide the user agent in its efforts to provide an exact match to the required sample size (if exact is specified or both min and max are provided and have the same value) or to a best-possible value. since this property can only represent linear sample sizes, this constraint can only be met by devices that can produce audio with linear samples. example see example: constraint exerciser in capabilities, constraints, and settings for an example. specifications specification status comment ...
MediaTrackControls.volume - Web APIs
however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. ...
... is the highest supported volume. if this value is a number, the user agent will attempt to obtain media whose volume is as close as possible to this number given the capabilities of the hardware and the other constraints specified. otherwise, the value of this constraindouble will guide the user agent in its efforts to provide an exact match to the required volume (if exact is specified or both min and max are provided and have the same value) or to a best-possible value. any constraint set which only permits values outside the range 0.0 to 1.0 cannot be satisfied and will result in failure. example see example: constraint exerciser in capabilities, constraints, and settings for an example. ...
MediaTrackConstraints.width - Web APIs
however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. ...
...ntsobject.width = constraint; value if this value is a number, the user agent will attempt to obtain media whose width is as close as possible to this number given the capabilities of the hardware and the other constraints specified. otherwise, the value of this constrainlong will guide the user agent in its efforts to provide an exact match to the required width (if exact is specified or both min and max are provided and have the same value) or to a best-possible value. example see example: constraint exerciser in capabilities, constraints, and settings for an example. specifications specification status comment media capture and streamsthe definition of 'width' in that specification. candidate recommendation initial specification. ...
MediaTrackSettings.autoGainControl - Web APIs
the mediatracksettings dictionary's autogaincontrol property is a boolean value whose value indicates whether or not automatic gain control (agc) is enabled on an audio track. this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.autogaincontrol property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). ...
...ol property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). automatic gain control is a feature in which a sound source automatically manages changes in the volume of its source media to maintain a steady overall volume level. this feature is typically used on microphones, although it can be provided by other input sources as well. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.autogaincontrol as returned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var autogaincontrol = mediatracksettings.autogaincontrol; value a boolean value which is tr...
MediaTrackSettings.deviceId - Web APIs
the mediatracksettings dictionary's deviceid property is a domstring which uniquely identifies the source for the corresponding mediastreamtrack for the origin corresponding to the browsing session. this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.deviceid property you provided when calling either getusermedia(). if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.deviceid as returned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. because rtp doesn't include this information, tracks associ...
...viceid = mediatracksettings.deviceid; value a domstring whose value is an origin-unique identifier for the track's source. this id is valid across multiple browsing sessions for the same origin and is guaranteed to be different for all other origins, so you can safely use it to request the same source be used for multiple sessions, for example. the actual value of the string, however, is determined by the source of the track, and there is no guarantee what form it will take, although the specification does recommend it be a guid. since there is a one-to-one pairing of id with each source, all tracks with the same source will share the same id for any given origin, so mediastreamtrack.getcapabilities() will always return exactly one value for deviceid. that makes the device id not useful ...
MediaTrackSettings.echoCancellation - Web APIs
the mediatracksettings dictionary's echocancellation property is a boolean value whose value indicates whether or not echo cancellation is enabled on an audio track. this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.echocancellation property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). echo cancellation is a feature which attempts to prevent echo effects on a two-way audio connection by attempting to reduce or eliminate crosstalk between the user's output device and their input device. for example, it might apply a filter that negates the sound being produced on the speakers from being included in the input track generated from the microphone...
...aints(). echo cancellation is a feature which attempts to prevent echo effects on a two-way audio connection by attempting to reduce or eliminate crosstalk between the user's output device and their input device. for example, it might apply a filter that negates the sound being produced on the speakers from being included in the input track generated from the microphone. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.echocancellation as returned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. because rtp doesn't include this information, tracks associated with a webrtc rtcpeerconnection will ...
MediaTrackSettings.groupId - Web APIs
the mediatracksettings dictionary's groupid property is a browsing-session unique domstring which identifies the group of devices which includes the source for the mediastreamtrack. this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.groupid property you provided when calling either getusermedia(). if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.groupid as returned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. because rtp doesn't include this information, tracks associated with a webrtc ...
...and a speaker which can serve as an output for audio. the group id is not usable across multiple browsing sessions. however, it can be used to ensure that audio input and output are both being performed on the same headset, for example, or to ensure that the built-in camera and microphone on a phone are being used for video conferencing purposes. the actual value of the string, however, is determined by the source of the track, and there is no guarantee what form it will take, although the specification does recommend it be a guid. since this property isn't stable across browsing sessions, its usefulness when calling getusermedia() is generally limited to ensuring that tasks performed during the same browsing session use devices from the same group (or that they don't use devices from the ...
MediaTrackSettings.noiseSuppression - Web APIs
the mediatracksettings dictionary's noisesuppression property is a boolean value whose value indicates whether or not noise suppression technology is enabled on an audio track. this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.noisesuppression property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). ...
...n calling either getusermedia() or mediastreamtrack.applyconstraints(). noise suppression automatically filters the audio to remove background noise, hum caused by equipment, and the like from the sound before delivering it to your code. this feature is typically used on microphones, although it is technically possible it could be provided by other input sources as well. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.noisesuppression as returned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var noisesuppression = mediatracksettings.noisesuppression; value a boolean value which is...
MediaTrackSettings - Web APIs
camera on the device, used for general photography. "left" a camera facing toward the environment to the user's left. "right" a camera facing toward the environment to the user's right. framerate a double-precision floating point value indicating the current value of the framerate property, specifying how many frames of video per second the track includes. if the value can't be determined for any reason, the value will match the vertical sync rate of the device the user agent is running on. height a long integer value indicating the current value of the height property, specifying the height of the track's video data in pixels. width a long integer value indicating the current value of the width property, specifying the width of the track's video data in pixels. resizemode ...
...m's video track contains the entire contents of one or more of the user's screens. window the stream contains a single window selected by the user for sharing. logicalsurface a boolean value which, if true, indicates that the video contained in the stream's video track contains a background rendering context, rather than a user-visible one. this is false if the video being captured is coming from a foreground (user-visible) source. specifications specification status comment screen capturethe definition of 'mediatracksettings' in that specification. working draft initial definition ...
MessageEvent - Web APIs
event (e.g. using an onmessage handler as listed above). note: this feature is available in web workers. ...
...nt (e.g. using an onmessage handler as listed above). note: this feature is available in web workers. ...
msFirstPaint - Web APIs
t could not be loaded. ...
...numerical value reported represents the number of milliseconds between the recorded time and midnight january 1, 1970 (utc). this property is supported only for documents displayed in ie9 standards mode. example the following example shows how to calculate the time that is required to request the document before the document begins to display for the user. var otiming = window.performance.timing; var itimems = otiming.msfirstpaint - otiming.navigationstart; ...
NavigatorConcurrentHardware - Web APIs
note: this feature is available in web workers. the number of logical processor cores is a way to measure the number of threads which can effectively be run at once without them having to share cpus. 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. ...
...8. the browser may, however, choose to reduce the number in order to represent more accurately the number of workers that can run at once properties navigatorconcurrenthardware.hardwareconcurrency read only returns the number of logical processors which may be available to the user agent. this value is always at least 1, and will be 1 if the actual number of logical processors can't be determined. methods the navigatorconcurrenthardware mixin has no methods. specifications specification status comment html living standardthe definition of 'navigatorconcurrenthardware' in that specification. living standard initial definition. ...
Node.namespaceURI - Web APIs
Web › API › Node › namespaceURI
the node.namespaceuri read-only property returns the namespace uri of the node, or null if the node is not in a namespace. when the node is a document, it returns the xml namespace for the current document. in dom4 this api was moved from node to the element and attr interfaces. syntax namespace = node.namespaceuri example in this snippet, a node is being examined for its node.localname and its namespaceuri. if the namespaceuri returns the xul namespace and the localname returns "browser", then the node is understood to be a xul <browser/>. if (node.localname == "browser" && node.namespaceuri == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul") { // this is a xul browser } notes this is not a computed value that is the result of a namespace lookup based on an...
... namespaceuri. if the namespaceuri returns the xul namespace and the localname returns "browser", then the node is understood to be a xul <browser/>. if (node.localname == "browser" && node.namespaceuri == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul") { // this is a xul browser } notes this is not a computed value that is the result of a namespace lookup based on an examination of the namespace declarations in scope. the namespace uri of a node is frozen at the node creation time. in firefox 3.5 and earlier, the namespace uri for html elements in html documents is null. in later versions, in compliance with html5, it is https://www.w3.org/1999/xhtml as in xhtml. for nodes of any node.nodetype other than element_node and attribute_node the value of namespaceuri i...
Node - Web APIs
Web › API › Node
for example, attempting to add children to a node type that cannot have children will throw an exception. ...
... example, attempting to add children to a node type that cannot have children will throw an exception. ...
PageTransitionEvent - Web APIs
ailable inside handler functions for the pageshow and pagehide events, fired when a document is being loaded or unloaded. ...
...ble inside handler functions for the pageshow and pagehide events, fired when a document is being loaded or unloaded. ...
PannerNode.coneInnerAngle - Web APIs
ians); // we hard-code the y component to 0, as y is the axis of rotation return [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which it can be heard: // this value determines the size of the area in which the sound volume is constant // if coneinnerangle == 30, it means that when the sound is rotated // by at most 15 (30/2) degrees either direction, the volume won't change panner.coneinnerangle = 30; // this value determines the size of the area in which the sound volume decreases gradually // if coneoute...
... direction, the volume won't change panner.coneinnerangle = 30; // this value determines the size of the area in which the sound volume decreases gradually // if coneouterangle == 45 and coneinnerangle == 30, it means that when the sound is rotated // by between 15 (30/2) and 22.5 (45/2) degrees either direction, // the volume will decrease gradually panner.coneouterangle = 45; // this value determines the volume of the sound outside of both inner and outer cone // setting it to 0 means there is no sound, so we can clearly hear when we leave the cone // 0 is also the default panner.coneoutergain = 0; // increase the z position to ensure the cone has an effect // (otherwise the sound is located at the same position as the listener) panner.positionz.setvalueattime(1, context.currenttime); havi...
PannerNode.coneOuterAngle - Web APIs
ians); // we hard-code the y component to 0, as y is the axis of rotation return [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which it can be heard: // this value determines the size of the area in which the sound volume is constant // if coneinnerangle == 30, it means that when the sound is rotated // by at most 15 (30/2) degrees either direction, the volume won't change panner.coneinnerangle = 30; // this value determines the size of the area in which the sound volume decreases gradually // if coneoute...
... direction, the volume won't change panner.coneinnerangle = 30; // this value determines the size of the area in which the sound volume decreases gradually // if coneouterangle == 45 and coneinnerangle == 30, it means that when the sound is rotated // by between 15 (30/2) and 22.5 (45/2) degrees either direction, // the volume will decrease gradually panner.coneouterangle = 45; // this value determines the volume of the sound outside of both inner and outer cone // setting it to 0 means there is no sound, so we can clearly hear when we leave the cone // 0 is also the default panner.coneoutergain = 0; // increase the z position to ensure the cone has an effect // (otherwise the sound is located at the same position as the listener) panner.positionz.setvalueattime(1, context.currenttime); havi...
PannerNode.coneOuterGain - Web APIs
ians); // we hard-code the y component to 0, as y is the axis of rotation return [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which it can be heard: // this value determines the size of the area in which the sound volume is constant // if coneinnerangle == 30, it means that when the sound is rotated // by at most 15 (30/2) degrees either direction, the volume won't change panner.coneinnerangle = 30; // this value determines the size of the area in which the sound volume decreases gradually // if coneoute...
... direction, the volume won't change panner.coneinnerangle = 30; // this value determines the size of the area in which the sound volume decreases gradually // if coneouterangle == 45 and coneinnerangle == 30, it means that when the sound is rotated // by between 15 (30/2) and 22.5 (45/2) degrees either direction, // the volume will decrease gradually panner.coneouterangle = 45; // this value determines the volume of the sound outside of both inner and outer cone // setting it to 0 means there is no sound, so we can clearly hear when we leave the cone // 0 is also the default panner.coneoutergain = 0; // increase the z position to ensure the cone has an effect // (otherwise the sound is located at the same position as the listener) panner.positionz.setvalueattime(1, context.currenttime); havi...
PannerNode.orientationX - Web APIs
ians); // we hard-code the y component to 0, as y is the axis of rotation return [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which it can be heard: // this value determines the size of the area in which the sound volume is constant // if coneinnerangle == 30, it means that when the sound is rotated // by at most 15 (30/2) degrees either direction, the volume won't change panner.coneinnerangle = 30; // this value determines the size of the area in which the sound volume decreases gradually // if coneoute...
... direction, the volume won't change panner.coneinnerangle = 30; // this value determines the size of the area in which the sound volume decreases gradually // if coneouterangle == 45 and coneinnerangle == 30, it means that when the sound is rotated // by between 15 (30/2) and 22.5 (45/2) degrees either direction, // the volume will decrease gradually panner.coneouterangle = 45; // this value determines the volume of the sound outside of both inner and outer cone // setting it to 0 means there is no sound, so we can clearly hear when we leave the cone // 0 is also the default panner.coneoutergain = 0; // increase the z position to ensure the cone has an effect // (otherwise the sound is located at the same position as the listener) panner.positionz.setvalueattime(1, context.currenttime); havi...
PannerNode.orientationY - Web APIs
ians); // we hard-code the y component to 0, as y is the axis of rotation return [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which it can be heard: // this value determines the size of the area in which the sound volume is constant // if coneinnerangle == 30, it means that when the sound is rotated // by at most 15 (30/2) degrees either direction, the volume won't change panner.coneinnerangle = 30; // this value determines the size of the area in which the sound volume decreases gradually // if coneoute...
... direction, the volume won't change panner.coneinnerangle = 30; // this value determines the size of the area in which the sound volume decreases gradually // if coneouterangle == 45 and coneinnerangle == 30, it means that when the sound is rotated // by between 15 (30/2) and 22.5 (45/2) degrees either direction, // the volume will decrease gradually panner.coneouterangle = 45; // this value determines the volume of the sound outside of both inner and outer cone // setting it to 0 means there is no sound, so we can clearly hear when we leave the cone // 0 is also the default panner.coneoutergain = 0; // increase the z position to ensure the cone has an effect // (otherwise the sound is located at the same position as the listener) panner.positionz.setvalueattime(1, context.currenttime); havi...
PannerNode.orientationZ - Web APIs
ians); // we hard-code the y component to 0, as y is the axis of rotation return [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which it can be heard: // this value determines the size of the area in which the sound volume is constant // if coneinnerangle == 30, it means that when the sound is rotated // by at most 15 (30/2) degrees either direction, the volume won't change panner.coneinnerangle = 30; // this value determines the size of the area in which the sound volume decreases gradually // if coneoute...
... direction, the volume won't change panner.coneinnerangle = 30; // this value determines the size of the area in which the sound volume decreases gradually // if coneouterangle == 45 and coneinnerangle == 30, it means that when the sound is rotated // by between 15 (30/2) and 22.5 (45/2) degrees either direction, // the volume will decrease gradually panner.coneouterangle = 45; // this value determines the volume of the sound outside of both inner and outer cone // setting it to 0 means there is no sound, so we can clearly hear when we leave the cone // 0 is also the default panner.coneoutergain = 0; // increase the z position to ensure the cone has an effect // (otherwise the sound is located at the same position as the listener) panner.positionz.setvalueattime(1, context.currenttime); havi...
PannerNode - Web APIs
cribing the angle, in degrees, of a cone outside of which the volume will be reduced by a constant value, defined by the coneoutergain attribute. pannernode.coneoutergain a double value describing the amount of volume reduction outside the cone defined by the coneouterangle attribute. its default value is 0, meaning that no sound can be heard. pannernode.distancemodel an enumerated value determining which algorithm to use to reduce the volume of the audio source as it moves away from the listener. possible values are "linear", "inverse" and "exponential". the default value is "inverse". pannernode.maxdistance a double value representing the maximum distance between the audio source and the listener, after which the volume is not reduced any further. pannernode.orientationx represents ...
...g its value property. the default is value is 0. pannernode.orientationz represents the longitudinal (back and forth) position of the audio source's vector in a right-hand cartesian coordinate system. the default is 0. while this audioparam cannot be directly changed, its value can be altered using its value property. the default is value is 0. pannernode.panningmodel an enumerated value determining which spatialisation algorithm to use to position the audio in 3d space. pannernode.positionx represents the horizontal position of the audio in a right-hand cartesian coordinate system. the default is 0. while this audioparam cannot be directly changed, its value can be altered using its value property. the default is value is 0. pannernode.positiony represents the vertical position of th...
PaymentAddress.region - Web APIs
this region has different names in different countries, such as: state, province, oblast, prefecture, or county. usage notes in some countries, like belgium, it's uncommon for people to provide a region as part of their postal address. ...
...this region has different names in different countries, such as: state, province, oblast, prefecture, or county. usage notes in some countries, like belgium, it's uncommon for people to provide a region as part of their postal address. ...
PaymentAddress.regionCode - Web APIs
e paymentaddress interface returns a one-, two-, or three-alphanumeric code (domstring) representing the region of the address (e.g., "ca" for california, or "11" for lisbon, portugal). the code is derived from the iso 3166-2 standard, which defines codes for identifying the subdivisions (e.g., states, provinces, autonomous regions, etc.) of all countries in the world. if the browser can't determine the region code, or the country doesn't use regions for postal addresses, it returns an empty string. syntax var regioncode = paymentaddress.regioncode; value a domstring indicating the one to three character alphanumeric code representing the region portion of the address. this should correspond to region, but should be the iso 3166--2 standard's region code. the string is empty if the regi...
... ...
PaymentCurrencyAmount.value - Web APIs
the paymentcurrencyamount property value is a string containing the decimal numeric value of the payment, specified in the currency units indicated by the currency property. the contents of this string must be a valid decimal number; that is, some number of digits between 0 and 9 with up to one optional decimal point. an optional leading minus sign ("-") can be included to indicate a negative value, such as to represent a refund or discount. 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. you must convert the entered text to this form or it will not be valid. syntax value = paymentcurrencyamount.value; value a domstring indicating the numer...
...s 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. you must convert the entered text to this form or it will not be valid. syntax value = paymentcurrencyamount.value; value a domstring indicating the numeric value of the payment. this must be a valid decimal number, with an optional leading minus sign ("-"), then one or more decimal digits 0 through 9, optionally with a decimal point (".") with at least one digit following it to represent fractional units. there must not be any leading or trailing whitespace in the string. for uniformity and consistency, the value is always given using the period (".") as the decimal character, regardless of the user's locale. you need to convert the v...
PaymentRequest.canMakePayment() - Web APIs
syntax paymentrequest.canmakepayment() .then( canpay => { ... ...
... syntax paymentrequest.canmakepayment() .then( canpay => { ... ...
Payment processing concepts - Web APIs
payee (or merchant) the merchant—either a person or an organization—whose web site or app wishes to receive money through the payment request api. payer the person or organization making a purchase using a web site or app. the payer authenticates themselves, then authorizes payment, as required by the payment method. ...
...mplete(). specifications specification status comment payment request api candidate recommendation initial definition. basic card payment working draft defines basiccardrequest and basiccardresponse. payment method identifiers candidate recommendation defines payment method identifiers and how they are validated, and, where applicable, minted and formally registered with the w3c. ...
Payment Request API - Web APIs
a consistent user experience for both merchants and users. it is not a new way for paying for things; rather, it's a way for users to select their preferred way of paying for things, and make that information available to a merchant. payment request concepts and usage many problems related to online shopping-cart abandonment can be traced to checkout forms, which can be difficult and time consuming to fill out and often require multiple steps to complete. the payment request api is meant to reduce the number of steps needed to complete a payment online, potentially doing away with checkout forms. it aims to make the checkout process easier, by remembering a user's details, which are then passed along to a merchant hopefully without requiring a html form. advantages of using the payment re...
... ...
performance.mark() - Web APIs
Web › API › Performance › mark
d by one of the performance interface's getentries*() methods (getentries(), getentriesbyname() or getentriesbytype()). the mark()'s stores its data internally as performanceentry. note: this feature is available in web workers. syntax performance.mark(name); arguments name a domstring representing the name of the mark. if the name given to this method already exists in the performancetiming interface, syntaxerror is thrown. return value void example the following example shows how to use mark() to create and retrieve performancemark entries. // create a bunch of marks. performance.mark("squirrel"); performance.mark("squirrel"); performance.mark("monkey"); performance.mark("monkey"); performance.mark("dog"); performance.mark("dog"); // get all of the performancemark entr...
...emark entries. const allentries = performance.getentriesbytype("mark"); console.log(allentries.length); // 6 // get all of the "monkey" performancemark entries. const monkeyentries = performance.getentriesbyname("monkey"); console.log(monkeyentries.length); // 2 // clear out all of the marks. performance.clearmarks(); specifications specification status comment user timing level 2the definition of 'mark()' in that specification. working draft clarifies mark() processing model. user timingthe definition of 'mark()' in that specification. recommendation basic definition. ...
PerformanceEntry.duration - Web APIs
he value returned by this property depends on the performance entry's type: "frame" - returns a timestamp indicating the difference between the starttimes of two successive frames. "mark" - returns "0" (a mark has no duration). "measure" - returns the timestamp that is the duration of the measure. "navigation" - returns the timestamp that is the difference between the performancenavigationtiming.loadeventend and performanceentry.starttime properties, respectively. "resource" - returns the difference between the resource's responseend timestamp and its starttime timestamp. this property is read only . syntax entry.duration; return value a domhighrestimestamp representing the duration of the performance entry. if the duration concept doesn't apply for a particular performance metri...
...its starttime timestamp. this property is read only . syntax entry.duration; return value a domhighrestimestamp representing the duration of the performance entry. if the duration concept doesn't apply for a particular performance metric, the browser may choose to return a duration of 0. note: if the performance entry has an entrytype of "resource" (i.e. the entry is a performanceresourcetiming object), this property returns the difference between the performanceentry.responseend and performanceentry.starttime timestamps. example the following example shows the use of the duration property. function run_performanceentry() { log("performanceentry support ..."); if (performance.mark === undefined) { log("... performance.mark not supported"); return; } // create some ...
PerformanceEntry.entryType - Web APIs
lable in web workers. syntax var type = entry.entrytype; return value the return value depends on the subtype of the performanceentry object and affects the value of the performanceentry.name property as shown by the table below. performance entry type names value subtype type of name property description of name property frame, navigation performanceframetiming, performancenavigationtiming url the document's address. resource performanceresourcetiming url the resolved url of the requested resource. this value doesn't change even if the request is redirected. mark performancemark domstring the name used when the mark was created by calling performance.mark(). measure performancemeasure domstring ...
... url the resolved url of the requested resource. this value doesn't change even if the request is redirected. mark performancemark domstring the name used when the mark was created by calling performance.mark(). measure performancemeasure domstring name used when the measure was created by calling performance.measure(). paint performancepainttiming domstring either 'first-paint' or 'first-contentful-paint'. longtask performancelongtasktiming domstring reports instances of long tasks example the following example shows the use of the entrytype property. function run_performanceentry() { // check for feature support before continuing if (performance.mark === undefined) { console.log("perform...
PerformanceEntry.name - Web APIs
anceentry.entrytype property. this property is read only. note: this feature is available in web workers. syntax var name = entry.name; return value the return value depends on the subtype of the performanceentry object and the value of performanceentry.entrytype, as shown by the table below. value subtype entrytype values description url performanceframetiming, performancenavigationtiming frame, navigation the document's address. url performanceresourcetiming resource the resolved url of the requested resource. this value doesn't change even if the request is redirected. domstring performancemark mark the name used when the mark was created by calling performance.mark(). domstring performancemeasur...
...rce the resolved url of the requested resource. this value doesn't change even if the request is redirected. domstring performancemark mark the name used when the mark was created by calling performance.mark(). domstring performancemeasure measure name used when the measure was created by calling performance.measure(). domstring performancepainttiming paint either 'first-paint' or 'first-contentful-paint'. example the following example shows the use of the name property. function run_performanceentry() { log("performanceentry support ..."); if (performance.mark === undefined) { log("... performance.mark not supported"); return; } // create some performance entries via the mark() method performance.mark("begi...
PerformanceNavigation.type - Web APIs
the legacy performancenavigation.type read-only property returns an unsigned short containing a constant describing how the navigation to this page was done. possible values are: value constant name meaning 0 type_navigate the page was accessed by following a link, a bookmark, a form submission, a script, or typing the url in the address bar. 1 type_reload the page was accessed by clicking the reload button or via the location.reload() method. ...
...ddress bar. 1 type_reload the page was accessed by clicking the reload button or via the location.reload() method. 2 type_back_forward the page was accessed by navigating into the history. 255 type_reserved any other way. syntax type = performancenavigation.type; specifications specification status comment navigation timingthe definition of 'performancenavigation.type' in that specification. recommendation initial definition. ...
PerformanceNavigation - Web APIs
the legacy performancenavigation interface represents information about how the navigation to the current document was done. an object of this type can be obtained by calling the performance.navigation read-only attribute. properties the performancenavigation interface doesn't inherit any properties. performancenavigation.type read only an unsigned short which indicates how the navigation to this page was done. possible values are: type_navigate (0) the page was accessed by following a link, a bookmark, a form submission, or a script, or by typing the url in the address bar. ...
... recommendation initial definition. ...
PerformanceObserverEntryList.getEntries() - Web APIs
the list is available in the observer's callback function (as the first parameter in the callback). this method is exposed to window and worker interfaces. ...
...anceentryfilteroptionsoptional is a performanceentryfilteroptions dictionary, having the following fields: "name", the name of a performance entry. "entrytype", the entry type. the valid entry types are listed in the performanceentry.entrytype method. "initiatortype", the type of the initiating resource (for example an html element). the values are defined by the performanceresourcetiming.initiatortype interface. this parameter is currently not supported on chrome or opera. return value a list of explicitly observed performanceentry objects that meets the criteria of the filter. the items will be in chronological order based on the entries' starttime. if no objects that meet the filter are found, an empty list is returned. if no argument is given, all entries are returned. ...
PerformanceObserverEntryList.getEntriesByName() - Web APIs
the list is available in the observer's callback function (as the first parameter in the callback). this method is exposed to window and worker interfaces. syntax entries = list.getentriesbyname(name, type); parameters name a domstring representing the name of the entry to retrieve. ...
...me a domstring representing the name of the entry to retrieve. type optional a domstring representing the type of entry to retrieve such as "mark". the valid entry types are listed in performanceentry.entrytype. return value a list of explicitly observed performance entry objects that have the specified name and type. if the type argument is not specified, only the name will be used to determine the entries to return. the items will be in chronological order based on the entries' starttime. if no objects meet the specified criteria, an empty list is returned. example function print_perf_entry(pe) { console.log("name: " + pe.name + "; entrytype: " + pe.entrytype + "; starttime: " + pe.starttime + "; duration: " + pe.duration); } ...
Pointer Lock API - Web APIs
it is ideal for first person 3d games, for example. ...
... exitpointerlock() the pointer lock api also extends the document interface, adding both a new property and a new method. the new property is used for accessing the currently locked element (if any), and is named pointerlockelement and the new method on document is exitpointerlock() and, as the name implies, it is used to exit the pointer lock. the pointerlockelement property is useful for determining if any element is currently pointer locked (e.g., for doing a boolean check) and also for obtaining a reference to the locked element, if any. 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 ...
ProcessingInstruction - Web APIs
(see, for example, <?xml-stylesheet ?>). the processinginstruction interface inherits methods and properties from node. ...
...e, for example, <?xml-stylesheet ?>). the processinginstruction interface inherits methods and properties from node. ...
PromiseRejectionEvent - Web APIs
lemetry and debugging purposes. for details on promise rejection events, see promise rejection events in using promises. ...
...try and debugging purposes. for details on promise rejection events, see promise rejection events in using promises. ...
RTCDTMFSender - Web APIs
tween two webrtc-based devices, because there is no mechanism provided by webrtc for receiving dtmf codes. ...
...n two webrtc-based devices, because there is no mechanism provided by webrtc for receiving dtmf codes. ...
RTCDtlsTransport - Web APIs
used to obtain information about the underlying transport and the security added to it by the dtls layer. ...
...d to obtain information about the underlying transport and the security added to it by the dtls layer. ...
RTCError - Web APIs
Web › API › RTCError
ror event. datachannel.addeventlistener("error", (event) => { let error = event.error; if (error.errordetail === "sdp-syntax-error") { let errline = error.sdplinenumber; let errmessage = error.message; let alertmessage = `a syntax error occurred interpreting line ${errline} of the sdp: ${errmessage}`; showmyalertmessage("data channel error", alertmessage); } else { terminatemyconnection(); } }); if the error is an sdp syntax error—indicated by its errordetail property being sdp-syntax-error—, a message string is constructed to present the error message and the line number within the sdp at which the error occurred. this message is then displayed using a function called showmyalertmessage(), which stands in for whatever output mechanism this code might use.
... error is an sdp syntax error—indicated by its errordetail property being sdp-syntax-error—, a message string is constructed to present the error message and the line number within the sdp at which the error occurred. 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. the above example uses addeventlistener() to add the handler for error events. you can also use the rtcdatachannel object's onerror event handler property, like this: datachannel.onerror = (event) => { let error = event.error; /* and so forth */ }; specifications specification status comment webrtc 1...
RTCErrorEvent.error - Web APIs
ror event. datachannel.addeventlistener("error", (event) => { let error = event.error; if (error.errordetail === "sdp-syntax-error") { let errline = error.sdplinenumber; let errmessage = error.message; let alertmessage = `a syntax error occurred interpreting line ${errline} of the sdp: ${errmessage}`; showmyalertmessage("data channel error", alertmessage); } else { terminatemyconnection(); } }); if the error is an sdp syntax error—indicated by its errordetail property being sdp-syntax-error—, a message string is constructed to present the error message and the line number within the sdp at which the error occurred. this message is then displayed using a function called showmyalertmessage(), which stands in for whatever output mechanism this code might use.
... error is an sdp syntax error—indicated by its errordetail property being sdp-syntax-error—, a message string is constructed to present the error message and the line number within the sdp at which the error occurred. 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. the above example uses addeventlistener() to add the handler for error events. you can also use the rtcdatachannel object's onerror event handler property, like this: datachannel.onerror = (event) => { let error = event.error; /* and so forth */ }; specifications specification status comment webrtc 1...
RTCIceCandidate.usernameFragment - Web APIs
t try to inject themselves into an ice exchange. note: there is no api to obtain the ice password, for what should be fairly obvious security reasons. the usernamefragment and password both change every time an ice restart occurs. example although the webrtc infrastructure will filter out obsolete candidates for you after an ice restart, you can do it yourself if you're trying to absolutely minimize the number of messages going back and forth. to do so, you can compare the value of usernamefragment to the current usernamefragment being used for the connection after receiving the candidate from the signaling server and before caling addicecandidate() to add it to the set of possible candidates. when the web app receives a message from the signaling server that includes a candidate to b...
... server and before caling addicecandidate() to add it to the set of possible candidates. when the web app receives a message from the signaling server that includes a candidate to be added to the rtcpeerconnection, you can (and generally should) simply call addicecandidate(). there's not typically a need to manually worry about filtering the candidates. however, let's imagine that we do need to minimize traffic. the function below, ssnewcandidate(), is called when a message, signalmsg, arrives from the signaling server that contains an ice candidate to be added to the rtcpeerconnection. to avoid including candidates obsoleted by an ice restart, we can use code like this: const ssnewcandidate = signalmsg => { let candidate = new rtcicecandidate(signalmsg.candidate); let receivers = pc.g...
RTCIceCandidatePairStats.readable - Web APIs
the obsolete rtcicecandidatepairstats property readable reports whether or not the connection described by the candidate pair has received at least one valid incoming ice request. syntax isreadable = rtcicecandidatepairstats.readable; value a boolean value which is true if the connection described by this candidate pair has received at least one valid ice request, and is therefore ready to be read from. ...
... by the candidate pair has received at least one valid incoming ice request. syntax isreadable = rtcicecandidatepairstats.readable; value a boolean value which is true if the connection described by this candidate pair has received at least one valid ice request, and is therefore ready to be read from. ...
RTCIceCandidatePairStats.writable - Web APIs
ion described by the candidate pair is writable. syntax iswritable = rtcicecandidatepairstats.writable; value a boolean value which is true if the connection described by this candidate pair has received acknowledgement of receipt (ack) for at least one ice request and that stun consent hasn't expired. ...
...ate pair is writable. syntax iswritable = rtcicecandidatepairstats.writable; value a boolean value which is true if the connection described by this candidate pair has received acknowledgement of receipt (ack) for at least one ice request and that stun consent hasn't expired. ...
RTCIceCandidateStats.address - Web APIs
candidate. if the value of address is comprised entirely of digits from 0-9 with periods as separators, the value is interpreted as an ipv4 address. if the value is entirely comprised of hexadecimal digits and colon (":") characters, it is interpreted as an ipv6 address. 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). if multiple ip addresses are returned in response to the query, the user agent selects one, which is then used for the duration of ice processing. usage notes the address property was previously known as ip, and only permitted ipv4 and ipv6 addresses to be used. the addition of support for ful...
...device onlu supports ipv4). if multiple ip addresses are returned in response to the query, the user agent selects one, which is then used for the duration of ice processing. usage notes the address property was previously known as ip, and only permitted ipv4 and ipv6 addresses to be used. the addition of support for fully-qualified domain names to be used for the address brought about the renaming of the property. specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcicecandidatestats.address' in that specification. candidate recommendation initial specification. ...
RTCIceTcpCandidateType - Web APIs
"so" the transport will try to open a connection simultaneously with its peer. usage notes the rtcicetcpcandidatetype type is used by the tcptype property of rtcicecandidate objects. ...
... "so" the transport will try to open a connection simultaneously with its peer. usage notes the rtcicetcpcandidatetype type is used by the tcptype property of rtcicecandidate objects. ...
RTCInboundRtpStreamStats.firCount - Web APIs
behind and needs to skip frames in order to catch up. syntax var fircount = rtcinboundrtpstreamstats.fircount; value an integer value indicating how many fir packets have been received by the sender during the current connection. this statistic is available only for video tracks. ...
... specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcinboundrtpstreamstats.fircount' in that specification. candidate recommendation initial definition. ...
RTCOutboundRtpStreamStats.firCount - Web APIs
ad of a delta frame. available only on video media. syntax var fircount = rtcoutboundrtpstreamstats.fircount; value an integer value indicating how many fir packets have been received by the sender during the current connection. this statistic is available only for video tracks. ...
... specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcoutboundrtpstreamstats.fircount' in that specification. candidate recommendation initial definition. ...
RTCPeerConnection.addTrack() - Web APIs
each track: async opencall(pc) { const gumstream = await navigator.mediadevices.getusermedia( {video: true, audio: true}); for (const track of gumstream.gettracks()) { pc.addtrack(track); } } the result is a set of tracks being sent to the remote peer, with no stream associations. the handler for the track event on the remote peer will be responsible for determining what stream to add each track to, even if that means simply adding them all to the same stream. the ontrack handler might look like this: let inboundstream = null; pc.ontrack = ev => { if (ev.streams && ev.streams[0]) { videoelem.srcobject = ev.streams[0]; } else { if (!inboundstream) { inboundstream = new mediastream(); videoelem.srcobject = inboundstream; } ...
...g tracks with specific streams by specifying a stream and allowing rtcpeerconnection to create streams for you, the streams' track associations are automatically managed for you by the webrtc infrastructure. this includes things like changes to the transceiver's direction and tracks being halted using removetrack(). ...
RTCPeerConnection.createAnswer() - Web APIs
ailed. options optional an optional rtcofferoptions object providing options requested for the answer. exceptions notreadableerror the identity provider wasn't able to provide an identity assertion. operationerror generation of the sdp failed for some reason; this is a general failure catch-all exception. ...
...in this case, a websocket connection is used to send a json message with a type field with the value "video-answer" to the other peer, carrying the answer to the device which sent the offer to connect. ...
RTCPeerConnection.onconnectionstatechange - Web APIs
rconnection.onconnectionstatechange = eventhandler; value a function which is called by the browser when the connectionstatechange event occurs on the rtcpeerconnection. the function receives as input a single parameter, which is an object of type event. ...
...o special information of note; you can look at the value of the peer connection's connectionstate property to determine what the new state is. example pc.onconnectionstatechange = function(event) { switch(pc.connectionstate) { case "connected": // the connection has become fully connected break; case "disconnected": case "failed": // one or more transports has terminated unexpectedly or in an error break; case "closed": // the connection has been closed break; } } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.onconnectionstatechange' in that specification. candidate recommendation initial specification. ...
RTCPeerConnection.onicegatheringstatechange - Web APIs
t the ice agent is actively gathering candidates—changes. you don't need to watch for this event unless you have specific reasons to want to closely monitor the state of ice gathering. syntax rtcpeerconnection.onicegatheringstatechange = eventhandler; value a function you provide which is passed a single parameter: an event object containing the icegatheringstatechange event. you can determine the new state of ice gathering by looking at the value of the rtcpeerconnection.icegatheringstate property. example this example updates status information presented to the user to let them know what's happening by examining the current value of the icegatheringstate property each time it changes and changing the contents of a status display based on the new information. the status is simply ...
...of a status display based on the new information. the status is simply presented as text in a <div> element: <div id="icestatus"></div> the actual event handler looks like this: pc.onicegatheringstatechange = function() { let label = "unknown"; switch(pc.icegatheringstate) { case "new": case "complete": label = "idle"; break; case "gathering": label = "determining route"; break; } document.getelementbyid("icestatus").innerhtml = label; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.onicegatheringstatechange' in that specification. candidate recommendation initial specification. ...
RTCPeerConnection.ontrack - Web APIs
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. the function receives as input the event object, of type rtctrackevent; this event is sent when a new incoming mediastreamtrack has been created and associated with an rtcrtpreceiver object which has been added to the set of receivers on connection. syntax rtcpeerconnection.ontrack = eventhandler; value set ontrack to be a function you provide that accepts as input a rtctrackevent object describing the new track and how it's being used. this information includes the mediastreamtrack object representing the new track, the rtcrtpreceiver and rtcrtptransceiver, and a list of mediastream objects which ...
...a rtctrackevent object describing the new track and how it's being used. this information includes the mediastreamtrack object representing the new track, the rtcrtpreceiver and rtcrtptransceiver, and a list of mediastream objects which indicates which stream or streams the track is part of.. example this example, taken from the code for the article signaling and video calling, connects the incoming track to the <video> element which will be used to display the incoming video. pc.ontrack = function(event) { document.getelementbyid("received_video").srcobject = event.streams[0]; document.getelementbyid("hangup-button").disabled = false; }; the first line of our ontrack event handler takes the first stream in the incoming track and sets the srcobject attribute to that. this connects th...
RTCPeerConnection - Web APIs
o a remote peer, maintain and monitor the connection, and close the connection once it's no longer needed. ...
...remote peer, maintain and monitor the connection, and close the connection once it's no longer needed. ...
RTCRtpCapabilities - Web APIs
the rtcrtpcapabilities dictionary is a data type used to describe the capabilities of an rtcrtpsender or rtcrtpreceiver in response to a call to the rtcrtpsender.getcapabilities() or rtcrtpreceiver.getcapabilities() static functions, both of which return an array of rtcrtpcapabilities objects. ...
... describing the capabilities of one codec) and an array of the supported rtp header extensions for that codec. properties codecs an array of rtcrtpcodeccapability objects, each describing one of the codecs supported by the rtcrtpsender or rtcrtpreceiver. there are some special entries in this array, described below in the section the codecs array. headerextensions an array of objects conforming to the rtcrtpheaderextensioncapability dictionary. each object contains a single domstring, uri, specifying the uri of the header extension, as described in rfc 5285. description the codecs array the codecs array is an array of objects conforming to the dictionary rtcrtpcodeccapability. each of these objects describes a single codec and its basic capabilities. its properties are: the brow...
RTCRtpStreamStats.firCount - Web APIs
behind and has to skip frames in order to catch up. syntax var fircount = rtcrtpstreamstats.fircount; value an integer value indicating how many fir packets have been received by the sender during the current connection. this value is available only on receivers for video tracks. ...
... specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcinboundrtpstreamstats: fircount' in that specification. candidate recommendation initial definition. identifiers for webrtc's statistics apithe definition of 'rtcoutboundrtpstreamstats: fircount' in that specification. ...
RTCRtpStreamStats - Web APIs
resenting the associated mediastreamtrack. this is not the same as the value of mediastreamtrack.id. transportid a domstring uniquely identifying the object which was inspected to produce the rtctransportstats object associated with this rtp stream. obsolete fields mediatype renamed to kind in the specification in february 2018. see browser compatibility in rtcrtpstreamstats.kind to determine when browsers made the transition. local-only measurements these properties are computed locally, and are only available to the device receiving the media stream. their primary purpose is to examine the error resiliency of the connection, as they provide information about lost packets, lost frames, and how heavily compressed the data is. fircount a count of the total number of full intra ...
...um of the quantization parameter (qp) values associated with every frame received to date on the video track described by this rtcrtpstreamstats object. in general, the higher this number is, the more heavily compressed the video track was. combined with rtcreceivedrtpstreamstats.framesdecoded or rtcsentrtpstreamstats.framesencoded, you can approximate the average qp over those frames, keeping in mind that codecs often vary the quantizer values even within frames. also keep in mind that the values of qp can vary from codec to codec, so this value is only potentially useful when compared against the same codec. 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 ...
RTCRtpTransceiver.currentDirection - Web APIs
syntax var direction = rtcrtptransceiver.currentdirection value a domstring whose value is one of the strings which are a member of the rtcrtptransceiverdirection enumerated type. the rtcrtptransceiverdirection type is an enumeration of string values. ...
...ne of the sender's encodings is active1. does not offer to receive rtp data and will not do so. "recvonly" does not offer to send rtp data, and will not do so. offers to receive rtp data, and will do so if the other peer offers. "inactive" does not offer to send rtp data, and will not do so. does not offer to receive rtp data and will not do so. [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. specifications specification status comment webrtc 1.0: real-time communication between browsersthe de...
RTCRtpTransceiver - Web APIs
of the m-line associated with this transceiver. this association is established, when possible, whenever either a local or remote description is applied. this field is null if neither a local or remote description has been applied, or if its associated m-line is rejected by either a remote offer or any answer. receiver read only the rtcrtpreceiver object that handles receiving and decoding incoming media. sender read only the rtcrtpsender object responsible for encoding and sending data to the remote peer. 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(). methods setcodecpreferences() a list of rtcrtpcodecparameters objects which overri...
...disabled, either due to sdp offer/answer, or due to a call to stop(). methods setcodecpreferences() a list of rtcrtpcodecparameters objects which override the default preferences used by the user agent for the transceiver's codecs. stop() permanently stops the rtcrtptransceiver. the associated sender stops sending data, and the associated receiver likewise stops receiving and decoding incoming data. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtptransceiver' in that specification. candidate recommendation ...
RTCSessionDescription() - Web APIs
the rtcsessiondescription() constructor creates a new rtcsessiondescription with its properties initialized as described in the specified object. this constructor has been deprecated because rtcpeerconnection.setlocaldescription() and other methods which take sdp as input now directly accept an object conforming to the rtcsessiondescriptioninit dictionary, so you don't have to instantiate an rtcsessiondescription yourself. syntax sessiondescription = new rtcsessiondescription(rtcsessiondescriptioninit); values rtcsessiondescriptioninit optional an object providing the default values for the session description; the object conforms to the rtcsessiondescriptioninit dictionary. that dictionary has the following properties: type required. a string which is a member of the rtc...
...sdp a string containing a sdp message describing the session. this value is an empty string ("") by default and may not be null. example this example uses the constructor to convert an sdp offer into an rtcsessiondescription object. this is no longer necessary, however; rtcpeerconnection.setlocaldescription() and other methods which take sdp as input now directly accept an object conforming to the rtcsessiondescriptioninit dictionary, so you don't have to instantiate an rtcsessiondescription yourself. navigator.getusermedia({video: true}, function(stream) { pc.onaddstream({stream: stream}); // adding a local stream won't trigger the onaddstream callback pc.addstream(stream); pc.createoffer(function(offer) { pc.setlocaldescription(new rtcsessiondescription(offer), fun...
RTCStatsType - Web APIs
values candidate-pair an rtcicecandidatepairstats object providing statistics related to an rtcicetransport. candidate pairs other than the currently active pair for the transport are deleted when the rtcpeerconnection changes its rtcpeerconnection.icegatheringstate to new during an ice restart. ...
...l, the type of relay being used, and so forth. remote-inbound-rtp the report is an rtcremoteinboundrtpstreamstats object providing statistics about your outbound rtp data stream, but from the perspective of the remote peer. that is, this information is about your outbound-rtp stream, but as seen by the remote device that's handling the stream. you can use this information to do things like determine how well the remote peer is receiving data. remote-outbound-rtp the report is an rtcremoteoutboundrtpstreamstats object that contains statistics about your inbound rtp (inbound-rtp) stream, but from the perspective of the remote peer. sender an object containing statistics about the rtcrtpsender for a stream on the rtcpeerconnection. if kind is "audio", this object is of type rtcaudiosenders...
RadioNodeList - Web APIs
the radionodelist interface represents a collection of radio elements in a <form> or a <fieldset> element. ...
...radionodelist interface represents a collection of radio elements in a <form> or a <fieldset> element. ...
Request.cache - Web APIs
Web › API › Request › cache
sting when dealing with a // properly configured server that will send the correct etag // and date headers and properly handle if-modified-since and // if-none-match request headers, therefore we can rely on the // validation to guarantee a fresh response. fetch("some.json", {cache: "no-cache"}) .then(function(response) { /* consume the response */ }); // download a resource with economics in mind! prefer a cached // albeit stale response to conserve as much bandwidth as possible. fetch("some.json", {cache: "force-cache"}) .then(function(response) { /* consume the response */ }); // naive stale-while-revalidate client-level implementation. // prefer a cached albeit stale response; but update if it's too old. // abortcontroller and signal to allow better memory cleaning. // in reality;...
... return res }) .then(function(response) { /* consume the (possibly stale) response */ }) .catch(error => { /* can be an aborterror/domerror or a typeerror */ }); specifications specification status comment fetchthe definition of 'cache' in that specificatio...
ResizeObserverEntry.borderBoxSize - Web APIs
he writing-mode is vertical, this is the vertical dimension, or height. note: for more explanation of writing modes and block and inline dimensions, read handling different text directions. ...
... editor's draft initial definition. ...
ResizeObserverEntry.contentBoxSize - Web APIs
proportion to the size of the box. 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. ...
...s that scale with the box size. const resizeobserver = new resizeobserver(entries => { for (let entry of entries) { if(entry.contentboxsize) { entry.target.style.borderradius = math.min(100, (entry.contentboxsize.inlinesize/10) + (entry.contentboxsize.blocksize/10)) + 'px'; } else { entry.target.style.borderradius = math.min(100, (entry.contentrect.width/10) + (entry.contentrect.height/10)) + 'px'; } } }); resizeobserver.observe(document.queryselector('div')); specifications specification status comment resize observerthe definition of 'target' in that specification. editor's draft initial definition. ...
ResizeObserverEntry.target - Web APIs
square corners that scale with the box size. to grab a reference to the observed element so we can update its border-radius value after each change, we make use of the target property of each entry — entry.target.style.borderradius. ...
...ntry.target.style.borderradius. const resizeobserver = new resizeobserver(entries => { for (let entry of entries) { if(entry.contentboxsize) { entry.target.style.borderradius = math.min(100, (entry.contentboxsize.inlinesize/10) + (entry.contentboxsize.blocksize/10)) + 'px'; } else { entry.target.style.borderradius = math.min(100, (entry.contentrect.width/10) + (entry.contentrect.height/10)) + 'px'; } } }); resizeobserver.observe(document.queryselector('div')); specifications specification status comment resize observerthe definition of 'target' in that specification. editor's draft initial definition. ...
Resize Observer API - Web APIs
to change width. this shows that you can respond to changes in an element’s size, even if they have nothing to do with the viewport. ...
... ...
SVGAltGlyphDefElement - Web APIs
the svgaltglyphdefelement interface corresponds to the <altglyphdef> element. ...
... the svgaltglyphdefelement interface corresponds to the <altglyphdef> element. ...
SVGAltGlyphItemElement - Web APIs
the svgaltglyphitemelement interface corresponds to the <altglyphitem> element. ...
... the svgaltglyphitemelement interface corresponds to the <altglyphitem> element. ...
SVGAnimateColorElement - Web APIs
the svganimatecolorelement interface corresponds to the <animatecolor> element. ...
... the svganimatecolorelement interface corresponds to the <animatecolor> element. ...
SVGAnimateElement - Web APIs
the svganimateelement interface corresponds to the <animate> element. ...
... the svganimateelement interface corresponds to the <animate> element. ...
SVGAnimateMotionElement - Web APIs
the svganimatemotionelement interface corresponds to the <animatemotion> element. ...
... the svganimatemotionelement interface corresponds to the <animatemotion> element. ...
SVGAnimateTransformElement - Web APIs
the svganimatetransformelement interface corresponds to the <animatetransform> element. ...
... the svganimatetransformelement interface corresponds to the <animatetransform> element. ...
SVGAnimationElement - Web APIs
teelement, svgsetelement, svganimatecolorelement, svganimatemotionelement and svganimatetransformelement. ...
...ement, svgsetelement, svganimatecolorelement, svganimatemotionelement and svganimatetransformelement. ...
SVGClipPathElement - Web APIs
nterface provides access to the properties of <clippath> elements, as well as methods to manipulate them. ...
...face provides access to the properties of <clippath> elements, as well as methods to manipulate them. ...
SVGComponentTransferFunctionElement - Web APIs
ferfunctionelement interface defines a base interface used by the component transfer function interfaces. ...
...unctionelement interface defines a base interface used by the component transfer function interfaces. ...
SVGCursorElement - Web APIs
interface provides access to the properties of <cursor> elements, as well as methods to manipulate them. ...
...erface provides access to the properties of <cursor> elements, as well as methods to manipulate them. ...
SVGDefsElement - Web APIs
the svgdefselement interface corresponds to the <defs> element. ...
... the svgdefselement interface corresponds to the <defs> element. ...
SVGDescElement - Web APIs
the svgdescelement interface corresponds to the <desc> element. ...
... the svgdescelement interface corresponds to the <desc> element. ...
SVGElement - Web APIs
interfaces that correspond directly to elements in the svg language derive from the svgelement interface. ...
...erfaces that correspond directly to elements in the svg language derive from the svgelement interface. ...
SVGEllipseElement - Web APIs
the svgellipseelement interface provides access to the properties of <ellipse> elements. ...
... the svgellipseelement interface provides access to the properties of <ellipse> elements. ...
SVGExternalResourcesRequired - Web APIs
h applies to all elements where this element or one of its descendants can reference an external resource. ...
...plies to all elements where this element or one of its descendants can reference an external resource. ...
SVGFEBlendElement - Web APIs
the svgfeblendelement interface corresponds to the <feblend> element. ...
... the svgfeblendelement interface corresponds to the <feblend> element. ...
SVGFEComponentTransferElement - Web APIs
the svgfecomponenttransferelement interface corresponds to the <fecomponenttransfer> element. ...
... the svgfecomponenttransferelement interface corresponds to the <fecomponenttransfer> element. ...
SVGFECompositeElement - Web APIs
the svgfecompositeelement interface corresponds to the <fecomposite> element. ...
... the svgfecompositeelement interface corresponds to the <fecomposite> element. ...
SVGFEConvolveMatrixElement - Web APIs
the svgfeconvolvematrixelement interface corresponds to the <feconvolvematrix> element. ...
... the svgfeconvolvematrixelement interface corresponds to the <feconvolvematrix> element. ...
SVGFEDiffuseLightingElement - Web APIs
the svgfediffuselightingelement interface corresponds to the <fediffuselighting> element. ...
... the svgfediffuselightingelement interface corresponds to the <fediffuselighting> element. ...
SVGFEDisplacementMapElement - Web APIs
the svgfedisplacementmapelement interface corresponds to the <fedisplacementmap> element. ...
... the svgfedisplacementmapelement interface corresponds to the <fedisplacementmap> element. ...
SVGFEDistantLightElement - Web APIs
the svgfedistantlightelement interface corresponds to the <fedistantlight> element. ...
... the svgfedistantlightelement interface corresponds to the <fedistantlight> element. ...
SVGFEDropShadowElement - Web APIs
the svgfedropshadowelement interface corresponds to the <fedropshadow> element. ...
... the svgfedropshadowelement interface corresponds to the <fedropshadow> element. ...
SVGFEFloodElement - Web APIs
the svgfefloodelement interface corresponds to the <feflood> element. ...
... the svgfefloodelement interface corresponds to the <feflood> element. ...
SVGFEFuncAElement - Web APIs
the svgfefuncaelement interface corresponds to the <fefunca> element. ...
... the svgfefuncaelement interface corresponds to the <fefunca> element. ...
SVGFEFuncBElement - Web APIs
the svgfefuncbelement interface corresponds to the <fefuncb> element. ...
... the svgfefuncbelement interface corresponds to the <fefuncb> element. ...
SVGFEFuncGElement - Web APIs
the svgfefuncgelement interface corresponds to the <fefuncg> element. ...
... the svgfefuncgelement interface corresponds to the <fefuncg> element. ...
SVGFEFuncRElement - Web APIs
the svgfefuncrelement interface corresponds to the <fefuncr> element. ...
... the svgfefuncrelement interface corresponds to the <fefuncr> element. ...
SVGFEGaussianBlurElement - Web APIs
the svgfegaussianblurelement interface corresponds to the <fegaussianblur> element. ...
... the svgfegaussianblurelement interface corresponds to the <fegaussianblur> element. ...
SVGFEImageElement - Web APIs
the svgfeimageelement interface corresponds to the <feimage> element. ...
... the svgfeimageelement interface corresponds to the <feimage> element. ...
SVGFEMergeElement - Web APIs
the svgfemergeelement interface corresponds to the <femerge> element. ...
... the svgfemergeelement interface corresponds to the <femerge> element. ...
SVGFEMergeNodeElement - Web APIs
the svgfemergenodeelement interface corresponds to the <femergenode> element. ...
... the svgfemergenodeelement interface corresponds to the <femergenode> element. ...
SVGFEMorphologyElement - Web APIs
the svgfemorphologyelement interface corresponds to the <femorphology> element. ...
... the svgfemorphologyelement interface corresponds to the <femorphology> element. ...
SVGFEOffsetElement - Web APIs
the svgfeoffsetelement interface corresponds to the <feoffset> element. ...
... the svgfeoffsetelement interface corresponds to the <feoffset> element. ...
SVGFEPointLightElement - Web APIs
the svgfepointlightelement interface corresponds to the <fepointlight> element. ...
... the svgfepointlightelement interface corresponds to the <fepointlight> element. ...
SVGFESpecularLightingElement - Web APIs
the svgfespecularlightingelement interface corresponds to the <fespecularlighting> element. ...
... the svgfespecularlightingelement interface corresponds to the <fespecularlighting> element. ...
SVGFESpotLightElement - Web APIs
the svgfespotlightelement interface corresponds to the <fespotlight> element. ...
... the svgfespotlightelement interface corresponds to the <fespotlight> element. ...
SVGFETileElement - Web APIs
the svgfetileelement interface corresponds to the <fetile> element. ...
... the svgfetileelement interface corresponds to the <fetile> element. ...
SVGFETurbulenceElement - Web APIs
the svgfeturbulenceelement interface corresponds to the <feturbulence> element. ...
... the svgfeturbulenceelement interface corresponds to the <feturbulence> element. ...
SVGFilterElement - Web APIs
interface provides access to the properties of <filter> elements, as well as methods to manipulate them. ...
...erface provides access to the properties of <filter> elements, as well as methods to manipulate them. ...
SVGFilterPrimitiveStandardAttributes - Web APIs
ibutes interface defines the set of dom attributes that are common across the filter primitive interfaces. ...
...es interface defines the set of dom attributes that are common across the filter primitive interfaces. ...
SVGFontElement - Web APIs
lements. object-oriented access to the attributes of the <font> element via the svg dom is not possible. ...
...nts. object-oriented access to the attributes of the <font> element via the svg dom is not possible. ...
SVGFontFaceElement - Web APIs
ts. object-oriented access to the attributes of the <font-face> element via the svg dom is not possible. ...
... object-oriented access to the attributes of the <font-face> element via the svg dom is not possible. ...
SVGFontFaceFormatElement - Web APIs
ject-oriented access to the attributes of the <font-face-format> element via the svg dom is not possible. ...
...-oriented access to the attributes of the <font-face-format> element via the svg dom is not possible. ...
SVGFontFaceNameElement - Web APIs
object-oriented access to the attributes of the <font-face-name> element via the svg dom is not possible. ...
...ct-oriented access to the attributes of the <font-face-name> element via the svg dom is not possible. ...
SVGFontFaceSrcElement - Web APIs
object-oriented access to the attributes of the <font-face-src> element via the svg dom is not possible. ...
...ect-oriented access to the attributes of the <font-face-src> element via the svg dom is not possible. ...
SVGFontFaceUriElement - Web APIs
object-oriented access to the attributes of the <font-face-uri> element via the svg dom is not possible. ...
...ect-oriented access to the attributes of the <font-face-uri> element via the svg dom is not possible. ...
SVGForeignObjectElement - Web APIs
ace provides access to the properties of <foreignobject> elements, as well as methods to manipulate them. ...
...provides access to the properties of <foreignobject> elements, as well as methods to manipulate them. ...
SVGGElement - Web APIs
the svggelement interface corresponds to the <g> element. ...
... the svggelement interface corresponds to the <g> element. ...
SVGGlyphElement - Web APIs
element. object-oriented access to the attributes of the <glyph> element via the svg dom is not possible. ...
...ent. object-oriented access to the attributes of the <glyph> element via the svg dom is not possible. ...
SVGGlyphRefElement - Web APIs
the svgglyphrefelement interface corresponds to the <glyphref> elements. ...
... the svgglyphrefelement interface corresponds to the <glyphref> elements. ...
SVGGradientElement - Web APIs
svggradient interface is a base interface used by svglineargradientelement and svgradialgradientelement. ...
...gradient interface is a base interface used by svglineargradientelement and svgradialgradientelement. ...
SVGGraphicsElement - Web APIs
e svggraphicselement interface represents svg elements whose primary purpose is to directly render graphics into a group. ...
...ggraphicselement interface represents svg elements whose primary purpose is to directly render graphics into a group. ...
SVGHKernElement - Web APIs
ements. object-oriented access to the attributes of the <hkern> element via the svg dom is not possible. ...
...ts. object-oriented access to the attributes of the <hkern> element via the svg dom is not possible. ...
SVGImageElement - Web APIs
the svgimageelement interface corresponds to the <image> element. ...
... the svgimageelement interface corresponds to the <image> element. ...
SVGLineElement - Web APIs
nt interface provides access to the properties of <line> elements, as well as methods to manipulate them. ...
...nterface provides access to the properties of <line> elements, as well as methods to manipulate them. ...
SVGLinearGradientElement - Web APIs
the svglineargradientelement interface corresponds to the <lineargradient> element. ...
... the svglineargradientelement interface corresponds to the <lineargradient> element. ...
SVGMPathElement - Web APIs
the svgmpathelement interface corresponds to the <mpath> element. ...
... the svgmpathelement interface corresponds to the <mpath> element. ...
SVGMaskElement - Web APIs
nt interface provides access to the properties of <mask> elements, as well as methods to manipulate them. ...
...nterface provides access to the properties of <mask> elements, as well as methods to manipulate them. ...
SVGMeshElement - Web APIs
the svgmeshelement interface provides access to the properties of <mesh> elements. ...
... the svgmeshelement interface provides access to the properties of <mesh> elements. ...
SVGMetadataElement - Web APIs
the svgmetadataelement interface corresponds to the <metadata> element. ...
... the svgmetadataelement interface corresponds to the <metadata> element. ...
SVGMissingGlyphElement - Web APIs
object-oriented access to the attributes of the <missing-glyph> element via the svg dom is not possible. ...
...ect-oriented access to the attributes of the <missing-glyph> element via the svg dom is not possible. ...
SVGPathElement - Web APIs
the svgpathelement interface corresponds to the <path> element. ...
... the svgpathelement interface corresponds to the <path> element. ...
SVGPatternElement - Web APIs
the svgpatternelement interface corresponds to the <pattern> element. ...
... the svgpatternelement interface corresponds to the <pattern> element. ...
SVGPolygonElement - Web APIs
interface provides access to the properties of <polygon> elements, as well as methods to manipulate them. ...
...rface provides access to the properties of <polygon> elements, as well as methods to manipulate them. ...
SVGPolylineElement - Web APIs
nterface provides access to the properties of <polyline> elements, as well as methods to manipulate them. ...
...face provides access to the properties of <polyline> elements, as well as methods to manipulate them. ...
SVGRadialGradientElement - Web APIs
the svgradialgradientelement interface corresponds to the <radialgradient> element. ...
... the svgradialgradientelement interface corresponds to the <radialgradient> element. ...
SVGRectElement - Web APIs
nt interface provides access to the properties of <rect> elements, as well as methods to manipulate them. ...
...nterface provides access to the properties of <rect> elements, as well as methods to manipulate them. ...
SVGRenderingIntent - Web APIs
t interface defines the enumerated list of possible values for rendering-intent attributes or descriptors. ...
...terface defines the enumerated list of possible values for rendering-intent attributes or descriptors. ...
SVGSVGElement - Web APIs
ods, such as matrix operations and the ability to control the time of redraw on visual rendering devices. ...
... such as matrix operations and the ability to control the time of redraw on visual rendering devices. ...
SVGScriptElement - Web APIs
the svgscriptelement interface corresponds to the svg <script> element. ...
... the svgscriptelement interface corresponds to the svg <script> element. ...
SVGSetElement - Web APIs
the svgsetelement interface corresponds to the <set> element. ...
... the svgsetelement interface corresponds to the <set> element. ...
SVGSolidcolorElement - Web APIs
the svgsolidcolorelement interface corresponds to the <solidcolor> element. ...
... the svgsolidcolorelement interface corresponds to the <solidcolor> element. ...
SVGStopElement - Web APIs
the svgstopelement interface corresponds to the <stop> element. ...
... the svgstopelement interface corresponds to the <stop> element. ...
SVGStyleElement - Web APIs
svg style interface the svgstyleelement interface corresponds to the svg <style> element. ...
... svg style interface the svgstyleelement interface corresponds to the svg <style> element. ...
SVGSwitchElement - Web APIs
the svgswitchelement interface corresponds to the <switch> element. ...
... the svgswitchelement interface corresponds to the <switch> element. ...
SVGSymbolElement - Web APIs
the svgsymbolelement interface corresponds to the <symbol> element. ...
... the svgsymbolelement interface corresponds to the <symbol> element. ...
SVGTRefElement - Web APIs
lements. object-oriented access to the attributes of the <tref> element via the svg dom is not possible. ...
...nts. object-oriented access to the attributes of the <tref> element via the svg dom is not possible. ...
SVGTSpanElement - Web APIs
the svgtspanelement interface represents a <tspan> element. ...
... the svgtspanelement interface represents a <tspan> element. ...
SVGTextContentElement - Web APIs
t-related interfaces, such as svgtextelement, svgtspanelement, svgtrefelement, svgaltglyphelement and svgtextpathelement. ...
...lated interfaces, such as svgtextelement, svgtspanelement, svgtrefelement, svgaltglyphelement and svgtextpathelement. ...
SVGTextElement - Web APIs
the svgtextelement interface corresponds to the <text> elements. ...
... the svgtextelement interface corresponds to the <text> elements. ...
SVGTextPathElement - Web APIs
the svgtextpathelement interface corresponds to the <textpath> element. ...
... the svgtextpathelement interface corresponds to the <textpath> element. ...
SVGTextPositioningElement - Web APIs
sition individual text glyphs. it is inherited by svgtextelement, svgtspanelement, svgtrefelement and svgaltglyphelement. ...
...on individual text glyphs. it is inherited by svgtextelement, svgtspanelement, svgtrefelement and svgaltglyphelement. ...
SVGTitleElement - Web APIs
the svgtitleelement interface corresponds to the <title> element. ...
... the svgtitleelement interface corresponds to the <title> element. ...
SVGURIReference - Web APIs
e svgurireference interface is used to reflect the href attribute and the deprecated xlink:href attribute. ...
...gurireference interface is used to reflect the href attribute and the deprecated xlink:href attribute. ...
SVGUnitTypes - Web APIs
used set of constants used for reflecting gradientunits, patterncontentunits and other similar attributes. ...
... set of constants used for reflecting gradientunits, patterncontentunits and other similar attributes. ...
SVGUseElement - Web APIs
svg use dom interface the svguseelement interface corresponds to the <use> element. ...
... svg use dom interface the svguseelement interface corresponds to the <use> element. ...
SVGVKernElement - Web APIs
ements. object-oriented access to the attributes of the <vkern> element via the svg dom is not possible. ...
...ts. object-oriented access to the attributes of the <vkern> element via the svg dom is not possible. ...
SVGZoomAndPan - Web APIs
ct the zoomandpan attribute, and is mixed in to other interfaces for elements that support this attribute. ...
...he zoomandpan attribute, and is mixed in to other interfaces for elements that support this attribute. ...
SourceBuffer - Web APIs
mlmediaelement and played, via a mediasource object. this can be made up of one or several media segments. ...
...diaelement and played, via a mediasource object. this can be made up of one or several media segments. ...
SourceBufferList - Web APIs
source buffers can be accessed using array operator (i.e. []) or functions such as foreach() for example. ...
...rce buffers can be accessed using array operator (i.e. []) or functions such as foreach() for example. ...
StaticRange - Web APIs
roperties and methods as abstractrange. abstractrange and staticrange are not available from web workers. ...
...rties and methods as abstractrange. abstractrange and staticrange are not available from web workers. ...
StorageEvent - Web APIs
s sent to a window when a storage area it has access to is changed within the context of another document. ...
...nt to a window when a storage area it has access to is changed within the context of another document. ...
Streams API concepts - Web APIs
the streams api adds a very useful set of tools to the web platform, providing objects allowing javascript to programmatically access streams of data received over the network and process them as desired by the developer. some of the concepts and terminology associated with streams might be new to you — this article explains all you need to know. readable streams a readable stream is a data source represented in javascript by a readablestream object that flows from an underlying source — this is a resource somewhere on the network or elsewhere on your domain that you want to get data from. there are two types of underlying source: push sources constantly push data at you when you’ve accessed them, and it is up to you to start, pause, or cancel access to the stream. examples inclu...
...g section below) note that there are two different types of readable stream. as well as the conventional readable stream there is a type called a byte stream — this is an extended version of a conventional stream for reading underlying byte sources (otherwise known as byob, or “bring your own buffer”) sources. these allow streams to be read straight into a buffer supplied by the developer, minimizing the copying required. which underlying stream (and by extension, reader and controller) your code will use depends on how the stream was created in the first place (see the readablestream() constructor page). important: byte streams are not implemented anywhere as yet, and questions have been raised as to whether the spec details are in a finished enough state for them to be implemented.
StylePropertyMap - Web APIs
el api provides a representation of a css declaration block that is an alternative to cssstyledeclaration. ...
...pi provides a representation of a css declaration block that is an alternative to cssstyledeclaration. ...
SyncEvent - Web APIs
Web › API › SyncEvent
serviceworkerglobalscope of a serviceworker. this interface inherits from the extendableevent interface. ...
...viceworkerglobalscope of a serviceworker. this interface inherits from the extendableevent interface. ...
SyncManager.register() - Web APIs
cmanager interface returns a promise that resolves to a syncregistration instance. syntax syncmanager.register([options]).then(function(syncregistration) { ... }) returns a promise that resolves to an instance of syncregistration. parameters options optional an object that sets options for an instance of syncregistration. the available options are: allowonbattery: a boolean that determines whether synchronization is allowed when the user agent is on a battery-powered device. the default is true. id: the unique identifier of the specified syncregistration object. idlerequired: a boolean that determines whether synchronization is allowed when the user agent's device is idle. the default is false. maxdelay: the maximum delay in milliseconds before the next sync event (or the f...
...he default is true. id: the unique identifier of the specified syncregistration object. idlerequired: a boolean that determines whether synchronization is allowed when the user agent's device is idle. the default is false. maxdelay: the maximum delay in milliseconds before the next sync event (or the first sync event if it is periodic). the default is 0, meaning there is no maximum delay. mindelay: the minimum delay in milliseconds before the next sync event (or the first sync event if it is periodic). the default is 0. minperiod: the minimum time in milliseconds between periodic sync events. the default is 0, meaning events are not periodic. minrequirednetwork: the network condition under which background synchronization will occur. valid values are 'network-any', 'network-offlin...
Text - Web APIs
Web › API › Text
. the node.normalize() method merges adjacent text objects back into a single node for each block of text. ...
...e node.normalize() method merges adjacent text objects back into a single node for each block of text. ...
TimeEvent - Web APIs
Web › API › TimeEvent
rface, a part of svg smil animation, provides specific contextual information associated with time events. ...
...e, a part of svg smil animation, provides specific contextual information associated with time events. ...
Using Touch Events - Web APIs
on the semantics of the application's gestures. for example, if an application supports a single touch (tap) on one element, it would use the targettouches list in the touchstart event handler to process the touch point in an application-specific manner. if an application supports two-finger swipe for any two touch points, it will use the changedtouches list in the touchmove event handler to determine if two touch points had moved and then implement the semantics of that gesture in an application-specific manner. browsers typically dispatch emulated mouse and click events when there is only a single active touch point. multi-touch interactions involving two or more active touch points will usually only generate touch events. to prevent the emulated mouse events from being sent, use the preve...
...ocess each event 'target' for (var i=0; i < ev.targettouches.length; i++) { process_target(ev.targettouches[i].target); } }, false); prevent the browser from processing emulated mouse events. // touchmove handler function process_touchmove(ev) { // set call preventdefault() ev.preventdefault(); } best practices here are some best practices to consider when using touch events: minimize the amount of work that is done in the touch handlers. add the touch point handlers to the specific target element (rather than the entire document or nodes higher up in the document tree). add touchmove, touchend and touchcancel event handlers within the touchstart. the target touch element or node should be large enough to accommodate a finger touch. if the target area is too small, tou...
Touch events - Web APIs
this is done by looking at each touch's touch.identifier property. this property is a unique integer for each touch and remains consistent for each event during the duration of each finger's contact with the surface. this lets us get the coordinates of the previous position of each touch and use the appropriate context methods to...
... evt.shiftkey, evt.metakey, 0, null); evt.originaltarget.dispatchevent(newevt); } calling preventdefault() only on a second touch one technique for preventing things like pinchzoom on a page is to call preventdefault() on the second touch in a series. this behavior is not well defined in the touch events spec and results in different behavior for different browsers (i.e., ios will prevent zooming but still allow panning with both fingers; android will allow zooming but not panning; opera and firefox currently prevent all panning and zooming.) currently, it's not recommended to depend on any particular behavior in this case, but rather to depend on meta viewport to prevent zooming. specifications specification status comment touch events – level 2the definition...
TransformStream - Web APIs
amples anything-to-uint8array stream in the following example, a transform stream passes through all chunks it receives as uint8array values. const transformcontent = { start() {}, // required. ...
...jstes_wm.set(this, t) } get encoding() {return _jstds_wm.get(this).decoder.encoding} get fatal() {return _jstds_wm.get(this).decoder.fatal} get ignorebom() {return _jstds_wm.get(this).decoder.ignorebom} } chaining multiple readablestreams together this is a useful one, where multiple streams can be conjoined. examples include building a pwa with progressive loading and progressive streaming. let responses = [ /* conjoined response tree */ ] let {readable, writable} = new transformstream responses.reduce( (a, res, i, arr) => a.then(() => res.pipeto(writable, {preventclose: (i+1) !== arr.length})), promise.resolve() ) note that this is not resilient to other influences. specifications specification status comment streamsthe definition of 'transformst...
UIEvent - Web APIs
Web › API › UIEvent
this one: mouseevent, touchevent, focusevent, keyboardevent, wheelevent, inputevent, and compositionevent. ...
... one: mouseevent, touchevent, focusevent, keyboardevent, wheelevent, inputevent, and compositionevent. ...
validityState.tooShort - Web APIs
specifications specification status comment html living standardthe definition of 'validitystate.tooshort' in that specification. ...
... specifications specification status comment html living standardthe definition of 'validitystate.tooshort' in that specification. ...
ValidityState - Web APIs
f true, the element matches the :invalid css pseudo-class. rangeoverflow read only a boolean that is true if the value is greater than the maximum specified by the max attribute, or false if it is less than or equal to the maximum. if true, the element matches the :invalid and :out-of-range and css pseudo-classes. rangeunderflow read only a boolean that is true if the value is less than the minimum specified by the min attribute, or false if it is greater than or equal to the minimum. if true, the element matches the :invalid and :out-of-range css pseudo-classes. stepmismatch read only a boolean that is true if the value does not fit the rules determined by the step attribute (that is, it's not evenly divisible by the step value), or false if it does fit the step rule. if true, the e...
...inputelement or htmltextareaelement objects, or false if its length is less than or equal to the maximum length. note: this property is never true in gecko, because elements' values are prevented from being longer than maxlength. if true, the element matches the the :invalid and :out-of-range css pseudo-classes. tooshort read only a boolean that is true if the value fails to meet the specified minlength for htmlinputelement or htmltextareaelement objects, or false if its length is greater than or equal to the minimum length. if true, the element matches the :invalid and :out-of-range css pseudo-classes. typemismatch read only a boolean that is true if the value is not in the required syntax (when type is email or url), or false if the syntax is correct. if true, the element matches the ...
VideoPlaybackQuality.corruptedVideoFrames - Web APIs
interface's read-only corruptedvideoframes property the number of corrupted video frames that have been received since the <video> element was last loaded or reloaded. syntax corruptframefount = videoplaybackquality.corruptedvideoframes; value the number of corrupted video frames that have been received since the <video> element was last loaded or reloaded. ...
...efount = videoplaybackquality.corruptedvideoframes; value the number of corrupted video frames that have been received since the <video> element was last loaded or reloaded. it is up to the user agent to determine whether or not to display a corrupted video frame. if a corrupted frame is dropped, then both corruptedvideoframes and droppedvideoframes are incremented. example this example determines the percentage of frames which have been corrupted, and if the value is greater than 5%, calls a funciton called downgradevideo() that would be implemented to switch to a different video that might tax the network less. var videoelem = document.getelementbyid("my_vid"); var quality = videoelem.getvideoplaybackquality(); if (quality.corruptedvideoframes/quality.totalvideoframes > 0.05) { dow...
VideoTrackList.onchange - Web APIs
the videotracklist property onchange is an event handler which is called when the change event occurs, indicating that a videotrack in the videotracklist has been made active. the event is passed into the event handler in the form of an event object; the event doesn't provide any additional information. to determine the new state of media's tracks, you'll have to look at their videotrack.selected flags. note: you can also add a handler for the change event using addeventlistener(). syntax videotracklist.onchange = eventhandler; value set onchange to a function that should be called whenever a track is made active. example this snippet establishes a handler for the change event that looks at each of the tracks in the list, calling a function to update the state of a user interface c...
... specifications specification status comment html living standardthe definition of 'videotracklist: onchange' in that specification. living standard ...
WakeLock.request() - Web APIs
Web › API › WakeLock › request
return value a promise that resolves with a wakelocksentinel object. exceptions notallowederror thrown when wake lock is not available, which can happen because: document is not allowed to use screen wake lock due to screen-wake-lock policy. ...
... return value a promise that resolves with a wakelocksentinel object. exceptions notallowederror thrown when wake lock is not available, which can happen because: document is not allowed to use screen wake lock due to screen-wake-lock policy. ...
WebGLContextEvent - Web APIs
g context. inheritance this interface inherits properties and methods from its parent interface, event. ...
...ntext. inheritance this interface inherits properties and methods from its parent interface, event. ...
WebGLRenderingContext.getSupportedExtensions() - Web APIs
eringcontext.getsupportedextensions() method returns a list of all the supported webgl extensions. syntax gl.getsupportedextensions(); return value an array of strings with all the supported webgl extensions. ...
...gl = canvas.getcontext('webgl'); var extensions = gl.getsupportedextensions(); // array [ 'angle_instanced_arrays', 'ext_blend_minmax', ... ] see also the webglrenderingcontext.getextension() method to get a specific extension object. webgl extensions extensions for the webgl api are registered in the webgl extension registry. ...
WebGLRenderingContext.getTexParameter() - Web APIs
ure_2d_array: a two-dimensional array texture. pname a glenum specifying the information to query. possible values: pname return type description possible return values available in a webgl 1 context gl.texture_mag_filter glenum texture magnification filter gl.linear (default value), gl.nearest. gl.texture_min_filter glenum texture minification filter gl.linear, gl.nearest, gl.nearest_mipmap_nearest, gl.linear_mipmap_nearest, gl.nearest_mipmap_linear (default value), gl.linear_mipmap_linear. gl.texture_wrap_s glenum wrapping function for texture coordinate s gl.repeat (default value), gl.clamp_to_edge, gl.mirrored_repeat. gl.texture_wrap_t glenum ...
...e_format glboolean immutability of the texture format and size true or false. gl.texture_immutable_levels gluint ? any uint values. gl.texture_max_level glint maximum texture mipmap array level any int values. gl.texture_max_lod glfloat texture maximum level-of-detail value any float values. gl.texture_min_lod glfloat texture minimum level-of-detail value any float values. gl.texture_wrap_r glenum wrapping function for texture coordinate r gl.repeat (default value), gl.clamp_to_edge, gl.mirrored_repeat. return value returns the requested texture information (as specified with pname). if an error occurs, null is returned. examples gl.gettexparamete...
WebGLRenderingContext.isContextLost() - Web APIs
lost() method returns a boolean indicating whether or not the webgl context has been lost and must be re-established before rendering can resume. syntax let islost = gl.iscontextlost(); return value a boolean which is true if the context is lost, or false if not. usage notes there are several reasons why a webgl context may be lost, making it necessary to re-establish the context before resuming rendering. 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. the user's computer has multiple graphics processors (such as a laptop with both mobile and desktop class gpus, the former used primarily when on battery po...
...ntire browser. the user updates their graphics driver on an operating system that allows graphics drivers to be updated without restarting the system. examples for example, when checking for program linking success, you could also check if the context is not lost: gl.linkprogram(program); if (!gl.getprogramparameter(program, gl.link_status) && !gl.iscontextlost()) { var info = gl.getprograminfolog(program); console.log('error linking program:\n' + info); } specifications specification status comment webgl 1.0the definition of 'webglrenderingcontext.iscontextlost' in that specification. recommendation initial definition. ...
Hello vertex attributes - Web APIs
hello world program in glsl how to send input to a shader program by saving data in gpu memory. <p>first encounter with attributes and sending data to gpu. ...
..." + "error log: " + linkerrlog; return; } initializeattributes(); gl.useprogram(program); gl.drawarrays(gl.points, 0, 1); document.queryselector("canvas").addeventlistener("click", function (evt) { var clickxrelativtocanvas = evt.page...
WebGL by example - Web APIs
examples by topic the examples are sorted in order of increasing difficulty. but rather than just presenting them in a single long list, they are additionally divided into topics. ...
...rplate 1 the example describes repeated pieces of code that will be hidden from now on, as well as defining a javascript utility function to make webgl initialization easier. scissor animation some animation fun with scissoring and clearing operations. raining rectangles a simple game that demonstrates clearing with solid colors, scissoring, animation, and user interaction. shader programming basics hello glsl a very basic shader program that draws a solid color square. hello vertex attributes combining shader programming and user interaction through vertex attributes. textures from code a simple demonstration of procedural texturing with fragment shaders. miscellaneous advanced examples video textures this example demonstrates how to use video files as textures. ...
Animating objects with WebGL - Web APIs
the value of squarerotation over time. we can do that by creating a new variable to track the time at which we last animated (let's call it then), then adding the following code to the end of the main function var then = 0; // draw the scene repeatedly function render(now) { now *= 0.001; // convert to seconds const deltatime = now - then; then = now; drawscene(gl, programinfo, buffers, deltatime); requestanimationframe(render); } requestanimationframe(render); this code uses requestanimationframe to ask the browser to call the function "render" on each frame. requestanimationframe passes us the time in milliseconds since the page loaded. we convert that to seconds and then subtract from it the last time to compute deltatime which is the number of second s...
...iseconds since the page loaded. we convert that to seconds and then subtract from it the last time to compute deltatime which is the number of second since the last frame was rendered. at the end of drawscene we add the code to update squarerotation. squarerotation += deltatime; this code uses the amount of time that's passed since the last time we updated the value of squarerotation to determine how far to rotate the square. view the complete code | open this demo on a new page « previousnext » ...
Animating textures in WebGL - Web APIs
lformat, width, height, border, srcformat, srctype, pixel); // turn off mips and set wrapping to clamp to edge so it // will work regardless of the dimensions of the video. ...
...re() each time just before we call the drawscene() function. ...
A simple RTCDataChannel sample - Web APIs
in this example, we will open an rtcdatachannel connection linking two elements on the same page. while that's obviously a contrived scenario, it's useful for demonstrating the flow of connecting two peers. ...
...e the "local" end of the connection. this is the peer that will send out the connection request. the next step is to create the rtcdatachannel by calling rtcpeerconnection.createdatachannel() and set up event listeners to monitor the channel so that we know when it's opened and closed (that is, when the channel is connected or disconnected within that peer connection). it's important to keep in mind that each end of the channel has its own rtcdatachannel object. set up the remote peer remoteconnection = new rtcpeerconnection(); remoteconnection.ondatachannel = receivechannelcallback; the remote end is set up similarly, except that we don't need to explicitly create an rtcdatachannel ourselves, since we're going to be connected through the channel established above. instead, we set up a d...
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. but there's a lot more you can do with webrtc. in this guide, we'll examine how to add a data channel to a peer connection, which can then be used to securely exchange arbitrary data; that is, any kind of data we wish, in any format we choose. since all webrtc components are required to use encryption, any data transmitted on an rtcdatachannel is automatically secured using datagram transport layer security (dtls). see security below for more information. 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...
...els. this proposal is still in ietf draft form, but once implemented, it will make it possible to send messages with essentially no size limitations, since the sctp layer will automatically interleave the underlying sub-messages to ensure that every channel's data has the opportunity to get through. firefox support for ndata is in the process of being implemented; see bug 1381145 to track it becoming available for general use. the chrome team is tracking their implementation of ndata support in chrome bug 5696. much of the information in this section is based in part on the blog post demystifyijng webrtc's data channel message size limitations, written by lennart grahl. he goes into a bit more detail there, but as browsers have been updated since then some of it may be out-of-date. in addi...
Improving compatibility using WebRTC adapter.js - Web APIs
e webrtc adapter to work around compatibility issues in different browsers' webrtc implementations. the adapter is a javascript shim which lets your code to be written to the specification so that it will "just work" in all browsers with webrtc support. there's no need to conditionally use prefixed apis or implement other workarounds. note: since there is ongoing fluidity in functionality and naming of api terms in webrtc and supporting browsers, use of this adapter is generally recommended. the adapter is provided under a bsd-style license. what adapter.js does for each version of each browser that supports webrtc, adapter.js implements the needed polyfills, establishes the non-prefixed names of apis, and applies any other changes needed to make the browser run code written to the webr...
... to include adapter.js on any page that uses webrtc apis: download a copy of the latest version of adapter.js from github. place it in your site's directory structure (such as in your scripts directory). 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. keep in mind that even a good shim like this one doesn't mean you don't need to test your code on different browsers (and ideally different versions of each browser). ...
WebXR application life cycle - Web APIs
bxr api is available; if navigator.xr is undefined, you can assume the user's browser and/or device doesn't support webxr. if it's not supported, disable any user interface used to activate xr features and abort any attempts to enter xr mode. call navigator.xr.issessionsupported(), specifying the webxr experience mode you want to provide: inline, immersive-vr, or immersive-ar, in order to determine whether or not the type of session you wish to provide is available. if the session type you want to use is available, provide the appropriate interface to the user to allow them to activate it. when the user requests the activation of webxr functionality by engaging with the user interface enabled above, request an xrsession using the desired mode. this is done by calling navigator.xr.
... ...
Targeting and hit detection - Web APIs
ever 3d graphics engine you're using offers hit testing, especially if it's designed specifically for game development. simplified representative objects one common solution is to overlay simplified, invisible objects atop the objects in your scene. these objects then serve a s. for instance, if you have a more-or-less rectangular object, use a rectangle as a surrogate for the object when performing hit testing. likewise, if an object is essentially round, use the radius of the minimum enclosing circle to establish a colision test object. real-world hit testing the acronym "lidar" has multiple definitions depending on specifics of how it's implemented, but the end result is the same. most commonly, it refers to "laser imaging, detection, and ranging" or "light detection and ranging"). te...
...sting for collisions with the real world is a different problem, which may involve not only interpreting the imagery from the device's camera (if available) but also potentially multiple additional sensors. some devices include infrared sensors to help range objects, and others provide powerful lidar systems, which use lasers (usually infrared lasers, which can't be seen by the human eye) to determine range to objects in the world. the details of how to work with an individual platform's ranging system is beyond the scope of this article. however, there's hope: a proposal has been floated for a webxr hit test module that would layer atop webxr to provide an api for performing hit testing and collision detection. ...
Web Animations API Concepts - Web APIs
in earnest among mozilla firefox and google chrome developers to create the one animation spec to rule them all: the web animations api. now we’ve got the waapi for future animation specifications to piggyback on, allowing them to to remain consistent and play well together. it also provides a point of reference all browsers can adhere to with the currently available specs. the two models: timing and animation the web animations api runs on top of two models, one that handles time—timing—and one that handles visual change over time—animation. the timing model keeps track of how far along a set timeline we've come. the animation model determines what the animated object should look like at any given time. timing the timing model is the backbone of working with the waapi. each doc...
...ecifically keyframe effects (we’ll get to those in a moment). like a dvd player, we can use the animation object’s methods to play, pause, seek, and control the animation’s playback direction and speed. animation effect if animation objects are dvd players, we can think of animation effects, or keyframe effects, as dvds. keyframe effects are a bundle of information including at the bare minimum a set of keys and the duration they need to be animated over. the animation object takes this information and, using the timeline object, assembles a playable animation we can view and reference. we currently have only one animation effect type available: keyframeeffect. potentially we could have all kinds of animation effects in the future—e.g. effects for grouping and sequencing, not unl...
Web Animations API - Web APIs
the web animations api allows for synchronizing and timing changes to the presentation of a web page, i.e. animation of dom elements. it does so by combining two models: the timing model and the animation model. concepts and usage the web animations api provides a common language for browsers and developers to describe animations on dom elements. to get more information on the concepts behind the api and how to use it, read using the web animations api. web animations interfaces animation provides playback controls and a timeline for an animation node or source. can take an object created with the keyframeeffect() constructor. keyframeeffect describes sets of animatable properties and values, called keyframes and their timing options. these can then be played using the animation() c...
...ntimeline represents the timeline of animation. this interface exists to define timeline features (inherited by documenttimeline and future timeline objects) and is not itself accessed by developers. animationevent actually part of css animations. documenttimeline represents animation timelines, including the default document timeline (accessed using the document.timeline property). effecttiming element.animate(), keyframeeffectreadonly.keyframeeffectreadonly(), and keyframeeffect.keyframeeffect() all accept an optional dictionary object of timing properties. extensions to other interfaces the web animations api adds some new features to document and element. extensions to the document interface document.timeline the documenttimeline object representing the default document tim...
Controlling multiple parameters with ConstantSourceNode - Web APIs
xed volume. html the html content for this example is primarily a button to toggle the oscillator tones on and off and an <input> element of type range to control the volume of two of the three oscillators. ...
... nodes will reach the output, whether that output be speakers, headphones, a recording stream, or any other destination type. after setting the window's load event handler to be the setup() function, the stage is set. let's see how the action plays out. toggling the oscillators on and off because oscillatornode doesn't support the notion of being in a paused state, we have to simulate it by terminating the oscillators and starting them again when the play button is clicked again to toggle them back on. let's look at the code. function toggleplay(event) { if (playing) { playbutton.innerhtml = "▶️"; stoposcillators(); } else { playbutton.innerhtml = "⏸"; startoscillators(); } } if the playing variable indicates we're already playing the oscillators, we change th...
Example and tutorial: Simple synth keyboard - Web APIs
musical keyboard itself. we draw this in a pair of nested <div> elements so that we can make the keyboard horizontally scrollable if all the keys don't fit on the screen, without having them wrap around. the keyboard first, we create space to build the keyboard into. we will be programmatically constructing the keyboard, because doing so gives us the flexibility to configure each key as we determine the appropriate data for the corresponding note. in our case, we get each key's frequency from a table, but it could be calculated algorithmically as well. <div class="container"> <div class="keyboard"></div> </div> the <div> named "container" is the scrollable box that lets the keyboard be scrolled horiontally if it's too wide for the available space. the keys themselves will be inserted i...
...ed as needed. then we establish a box that will be presented on the left side of the bar and place a label and an <input> element of type "range". the range element will typically be presented as a slider control; we configure it to allow any value between 0.0 and 1.0, stepping by 0.01 each position. ...
Using IIR filters - Web APIs
te your own if none of the alaready available settings is right for what you want. as well as this, if your audio graph needed a highpass and a bandpass filter within it, you could just use one iir filter node in place of the two biquad filter nodes you would otherwise need for this. with the iirfilter node it's up to you to set what feedforward and feedback values the filter needs — this determines the characteristics of the filter. the downside is that this involves some complex maths. if you are looking to learn more there's some information about the maths behind iir filters here. this enters the realms of signal processing theory — don't worry if you look at it and feel like it's not for you. if you want to play with the iir filter node and need some values to help along the way, ...
...u want to play with the iir filter node and need some values to help along the way, there's a table of already calculated values here; on pages 4 & 5 of the linked pdf the an values refer to the feedforward values and the bn values refer to the feedback. musicdsp.org is also a great resource if you want to read more about different filters and how they are implemented digitally. with that all in mind, let's take a look at the code to create an iir filter with the web audio api. setting our iirfilter co-efficients when creating an iir filter, we pass in the feedforward and feedback coefficients as options (coefficients is how we describe the values). both of these parameters are arrays, neither of which can be larger than 20 items. when setting our coefficients, the feedforward values can'...
Using the Web Speech API - Web APIs
ions for use, and a form with some simple controls. the <select> element is initially empty, but is populated with <option>s via javascript (see later on.) <h1>speech synthesiser</h1> <p>enter some text in the input below and press return to hear it. ...
...er some text in the input below and press return to hear it. change voices using the dropdown menu.</p> <form> <input type="text" class="txt"> <div> <label for="rate">rate</label><input type="range" min="0.5" max="2" value="1" step="0.1" id="rate"> <div class="rate-value">1</div> <div class="clearfix"></div> </div> <div> <label for="pitch">pitch</label><input type="range" min="0" max="2" value="1" step="0.1" id="pitch"> <div class="pitch-value">1</div> <div class="clearfix"></div> </div> <select> </select> </form> javascript let's investigate the javascript that powers this app. setting variables first of all, we capture references to all the dom elements involved in the ui, but more interestingly, we capture a reference to window.speechsynthesis. t...
WheelEvent - Web APIs
g direction. instead, detect value changes to scrollleft and scrolltop of the target in the scroll event. ...
...rection. instead, detect value changes to scrollleft and scrolltop of the target in the scroll event. ...
Window.devicePixelRatio - Web APIs
ay, while a value of 2 is expected for hidpi/retina displays. other values may be returned as well in the case of unusually low resolution displays or, more often, when a screen has a higher pixel depth than simply double the standard resolution of 96 or 76 dpi. examples correcting resolution in a <canvas> a <canvas> can appear too blurry on retina screens. use window.devicepixelratio to determine how much extra pixel density should be added to allow for a sharper image. html <canvas id="canvas"></canvas> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); // set display size (css pixels). var size = 200; canvas.style.width = size + "px"; canvas.style.height = size + "px"; // set actual size in memory (scaled to account for extra pixel dens...
...er which the media query is created using matchmedia() and addeventlistener() is called to set up updatepixelratio() as a handler for the change event. html the html creates the boxes containing the instructions and the pixel-ratio box that will display the current pixel ratio information. <div class="container"> <div class="inner-container"> <p>this example demonstrates the effect of zooming the page in and out (or moving it to a screen with a different scaling factor) on the value of the property <code>window.devicepixelratio</code>. try it and watch what happens!</p> </div> <div class="pixel-ratio"></div> </div> css body { font: 22px arial, sans-serif; } .container { top: 2em; width: 22em; height: 14em; border: 2px solid #22d; margin: 0 ...
Window.innerHeight - Web APIs
rt. the width can be obtained using the innerwidth property. syntax let intviewportheight = window.innerheight; value an integer value indicating the window's layout viewport height in pixels. the property is read only and has no default value. to change the width of the window, call one of its resize methods, such as resizeto() or resizeby(). ...
...change the width of the window, call one of its resize methods, such as resizeto() or resizeby(). usage notes to obtain the height of the window minus its horizontal scroll bar and any borders, use the root <html> element's clientheight() property instead. both innerheight and innerwidth are available on any window or any object that behaves like a window, such as a tab or frame. ...
window.postMessage() - Web APIs
ost sharedarraybuffer } else { // do something else } see also planned changes to shared memory which is starting to roll out to browsers (firefox 79, for example). example /* * in window a's scripts, with a being on <http://example.com:8080>: */ var popup = window.open(/* popup details */); // when the popup has fully loaded, if not blocked by a popup blocker: // this does nothing, assuming the window hasn't changed its location. popup.postmessage("the user is 'bob' and the password is 'secret'", "https://secure.example.net"); // this will successfully queue a message to be sent to the popup, assuming // the window hasn't changed its location. popup.postmessage("hello there!", "http://example.com"); function receivemessage(event) { // do we trust the sender of...
... event.source.postmessage("hi there yourself! the secret response " + "is: rheeeeet!", event.origin); } window.a...
WindowOrWorkerGlobalScope.clearTimeout() - Web APIs
and setinterval() are shared, which means you can technically use cleartimeout() and clearinterval() interchangeably. however, for clarity, you should avoid doing so. example run the script below in the context of a web page and click on the page once. you'll see a message popping up in a second. if you click the page multiple times in one second, the alert only appears once. ...
...nce. you'll see a message popping up in a second. if you click the page multiple times in one second, the alert only appears once. var alarm = { remind: function(amessage) { alert(amessage); this.timeoutid = undefined; }, setup: function() { if (typeof this.timeoutid === 'number') { this.cancel(); } this.timeoutid = window.settimeout(function(msg) { this.remind(msg); }.bind(this), 1000, 'wake up!'); }, cancel: function() { window.cleartimeout(this.timeoutid); } }; window.onclick = function() { alarm.setup(); }; notes passing an invalid id to cleartimeout() silently does nothing; no exception is thrown. specifications specification status comment html living standardthe definition of 'windoworworkerglobals...
WorkerGlobalScope.dump() - Web APIs
the dump() method of the workerglobalscope interface allows you to write a message to stdout — i.e. in your terminal, in firefox only. this is the same as firefox's window.dump, but for workers. syntax dump('my message\n'); parameters a domstring containing the message you want to send. returns void. example to write an output from your worker to your computer's terminal, you first have to run an instance of firefox started from your command line/terminal. 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. next, run a worker containing the following line: dump('te...
... specifications this method does not appear in any specification. ...
XMLDocument - Web APIs
or properties to it: nevertheless, several algorithms behave differently with the two types of documents. ...
...properties to it: nevertheless, several algorithms behave differently with the two types of documents. ...
XMLHttpRequest.getAllResponseHeaders() - Web APIs
the code shows how to obtain the raw header...
...ecurity: max-age=63072000\r\n vary: cookie, accept-encoding\r\n content-length: 6502\r\n x-xss-protection: 1; mode=block\r\n each line is terminated by both carriage return and line feed characters (\r\n). these are essentially delimiters separating each of the headers. note: in modern browsers, the header names are returned in all lower case, as per the latest spec. example this example examines the headers in the request's readystatechange event handler, xmlhttprequest.onreadystatechange. the code shows how to obtain the raw header string, as well as how to convert it into an array of individual headers and then how to take that array and create a mapping of header names to their values. var request = new xmlhttprequest(); request.open("get", "foo.txt", true); request.send(); reques...
XMLHttpRequestEventTarget - Web APIs
describes the event handlers you can implement in an object that will handle events for an xmlhttprequest. ...
...ribes the event handlers you can implement in an object that will handle events for an xmlhttprequest. ...
XMLHttpRequestResponseType - Web APIs
cument the response is an html document or xml xmldocument, as appropriate based on the mime type of the received data. see html in xmlhttprequest to learn more about using xhr to fetch html content. json the response is a javascript object created by parsing the contents of received data as json. text the response is a text in a domstring object. ms-stream the response is part of a streaming download; this response type is only allowed for download requests, and is only supported by internet explorer. deprecated values moz-chunked-arraybuffer a firefox-only value which instructs xmlhttprequest to deliver arraybuffer objects containing chunks of the incoming data. accessing response during a progress event returns the data received so far. outside the progress event handler...
...ing chunks of the incoming data. accessing response during a progress event returns the data received so far. outside the progress event handler, the value of response is always null. 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. specifications specification status comment xmlhttprequest unknown live standard, latest version ...
XRHandedness - Web APIs
e value of the the xrinputsource property handedness. values none the input controller is not associated with one of the user's hands. left the input controller is being held in, worn on, or is attached to the user's left hand. right the input controller is being held in, worn on, or is attached to the user's right hand. examples one important usage scentario for handedness is to determine which hand a controller is in so you can draw a representation of that hand (or the device that hand is controlling) in virtual space. function updateinputsources(session, frame, refspace) { for (let source of session.inputsources) { if (source.gripspace) { let grippose = frame.getpose(source.gripspace, refspace); if (grippose) { myrenderhandobject(grippose, inputsour...
...quired and any performance constraints), scans the list of input sources looking for any which have a gripspace which isn't null. if a gripspace is present, that means the input source is a hand-held device of some sort, so it should be rendered visibly if possible. if gripspace is non-null, the function proceeds to get the pose for the gripspace transformed into the current reference space. assuming that's then valid, a function called myrenderhandobject() is called with the grip's pose and the value of handedness. with these values in hand (no pun intended), myrenderhandobject() can draw the appropriate model positioned and formed for the correct hand. specifications specification status comment webxr device apithe definition of 'xrhandedness' in that specificatio...
XRInputSource.handedness - Web APIs
r's right hand. usage notes if the input source is not a device associated with a user's hand (whether by being held, attached, or worn), the value of handedness is none. this may indicate, for example, an input source which isn't hand-held, such as controls built into a headset or an input device attached to the head or body. examples one important usage scentario for handedness is to determine which hand a controller is in so you can draw a representation of that hand (or the device that hand is controlling) in virtual space. function updateinputsources(session, frame, refspace) { for (let source of session.inputsources) { if (source.gripspace) { let grippose = frame.getpose(source.gripspace, refspace); if (grippose) { myrenderhandobject(grippose, inputsour...
...quired and any performance constraints), scans the list of input sources looking for any which have a gripspace which isn't null. if a gripspace is present, that means the input source is a hand-held device of some sort, so it should be rendered visibly if possible. if gripspace is non-null, the function proceeds to get the pose for the gripspace transformed into the current reference space. assuming that's then valid, a function called myrenderhandobject() is called with the grip's pose and the value of handedness. with these values in hand (no pun intended), myrenderhandobject() can draw the appropriate model positioned and formed for the correct hand. specifications specification status comment webxr device apithe definition of 'xrinputsource.handedness' in that ...
XRPermissionDescriptor.optionalFeatures - Web APIs
d for each reference space type constant.. reference space descriptors the types of reference space are listed in the table below, with brief information about their use cases and which interface is used to implement them. xrreferencespacetype description interface bounded-floor similar to the local type, except the user is not expected to move outside a predetermined boundary, given by the boundsgeometry in the returned object. xrboundedreferencespace local a tracking space whose native origin is located near the viewer's position at the time the session was created. the exact position depends on the underlying platform and implementation. the user isn't expected to move much if at all beyond their starting position, and tracking is opti...
... may drift as needed to accommodate that need. xrreferencespace viewer a tracking space whose native origin tracks the viewer's position and orientation. this is used for environments in which the user can physically move around, and is supported by all instances of xrsession, both immersive and inline, though it's most useful for inline sessions. it's particularly useful when determining the distance between the viewer and an input, or when working with offset spaces. otherwise, typically, one of the other reference space types will be used more often. xrreferencespace usage notes examples let xrpermissiondesc = { name: "xr", mode: "immersive-vr", optionalfeatures: [ "bounded-floor" ] }; if (navigator.permissions) { navigator.permissions.query(xrpermissio...
XRPermissionDescriptor.requiredFeatures - Web APIs
s of webxr may add more recognized features. the permitted values are: the types of reference space are listed in the table below, with brief information about their use cases and which interface is used to implement them. xrreferencespacetype description interface bounded-floor similar to the local type, except the user is not expected to move outside a predetermined boundary, given by the boundsgeometry in the returned object. xrboundedreferencespace local a tracking space whose native origin is located near the viewer's position at the time the session was created. the exact position depends on the underlying platform and implementation. the user isn't expected to move much if at all beyond their starting position, and tracking is opti...
... may drift as needed to accommodate that need. xrreferencespace viewer a tracking space whose native origin tracks the viewer's position and orientation. this is used for environments in which the user can physically move around, and is supported by all instances of xrsession, both immersive and inline, though it's most useful for inline sessions. it's particularly useful when determining the distance between the viewer and an input, or when working with offset spaces. otherwise, typically, one of the other reference space types will be used more often. xrreferencespace usage notes examples in this example, permissions are checked to ensure that the user has granted permission for the site or app to use immersive augmented reality mode with the local-floor referenc...
XRPermissionStatus.granted - Web APIs
ll of these strings come from the xrreferencespacetype enumerated type. the types of reference space are listed in the table below, with brief information about their use cases and which interface is used to implement them. xrreferencespacetype description interface bounded-floor similar to the local type, except the user is not expected to move outside a predetermined boundary, given by the boundsgeometry in the returned object. xrboundedreferencespace local a tracking space whose native origin is located near the viewer's position at the time the session was created. the exact position depends on the underlying platform and implementation. the user isn't expected to move much if at all beyond their starting position, and tracking is opti...
... may drift as needed to accommodate that need. xrreferencespace viewer a tracking space whose native origin tracks the viewer's position and orientation. this is used for environments in which the user can physically move around, and is supported by all instances of xrsession, both immersive and inline, though it's most useful for inline sessions. it's particularly useful when determining the distance between the viewer and an input, or when working with offset spaces. otherwise, typically, one of the other reference space types will be used more often. xrreferencespace usage notes examples specifications specification status comment webxr device apithe definition of 'xrpermissionstatus.granted' in that specification. working draft ...
XRPose.emulatedPosition - Web APIs
o the sides. any such data is taken from other sources, such as keyboard or mouse inputs or game controllers. as such, the position is considered to be emulated, so the emulatedposition property is true. contrariwise, xr devices which can also track movement forward and backward as well as laterally—six degree of freedom (6dof) devices—don't require any information from other sources to determine the user's position, so the value of emulatedposition is false. the same notion applies not just to the user's head, but to any object. a hand controller that can directly report its position would have a value of false for this property as well. if its position is computed as an offset from another object (such as by basing it off the model representing the user's body), then this value is tru...
...its position is computed as an offset from another object (such as by basing it off the model representing the user's body), then this value is true. this information is important because devices whose position is emulated are prone to their offset drifting relative to the real world space over time. this is because emulating a position based on accelerometer inputs and models tends to introduce minor errors which accumulate over time. specifications specification status comment webxr device apithe definition of 'xrpose.emulatedposition' in that specification. working draft initial definition. ...
XRReferenceSpace - Web APIs
d for each reference space type constant.. reference space descriptors the types of reference space are listed in the table below, with brief information about their use cases and which interface is used to implement them. xrreferencespacetype description interface bounded-floor similar to the local type, except the user is not expected to move outside a predetermined boundary, given by the boundsgeometry in the returned object. xrboundedreferencespace local a tracking space whose native origin is located near the viewer's position at the time the session was created. the exact position depends on the underlying platform and implementation. the user isn't expected to move much if at all beyond their starting position, and tracking is opti...
... may drift as needed to accommodate that need. xrreferencespace viewer a tracking space whose native origin tracks the viewer's position and orientation. this is used for environments in which the user can physically move around, and is supported by all instances of xrsession, both immersive and inline, though it's most useful for inline sessions. it's particularly useful when determining the distance between the viewer and an input, or when working with offset spaces. otherwise, typically, one of the other reference space types will be used more often. xrreferencespace usage notes creating an xrreferencespace there are two situations in which you need to obtain an xrreferencespace. the first is when you set up your scene and need to obtain a reference space to rep...
XRReferenceSpaceType - Web APIs
d for each reference space type constant.. reference space descriptors the types of reference space are listed in the table below, with brief information about their use cases and which interface is used to implement them. xrreferencespacetype description interface bounded-floor similar to the local type, except the user is not expected to move outside a predetermined boundary, given by the boundsgeometry in the returned object. xrboundedreferencespace local a tracking space whose native origin is located near the viewer's position at the time the session was created. the exact position depends on the underlying platform and implementation. the user isn't expected to move much if at all beyond their starting position, and tracking is opti...
... may drift as needed to accommodate that need. xrreferencespace viewer a tracking space whose native origin tracks the viewer's position and orientation. this is used for environments in which the user can physically move around, and is supported by all instances of xrsession, both immersive and inline, though it's most useful for inline sessions. it's particularly useful when determining the distance between the viewer and an input, or when working with offset spaces. otherwise, typically, one of the other reference space types will be used more often. xrreferencespace specifications specification status comment webxr device apithe definition of 'xrreferencespacetype' in that specification. working draft initial definition. ...
XRRigidTransform() - Web APIs
xrrigidtransform() constructor creates and returns a new xrrigidtransform object, representing the position and orientation of a point or object. among other things, xrrigidtransform is used when providing a transform to translate between coordinate systems across spaces. ...
...the default value for orientation is {x: 0, y: 0, z: 0, w: 1}. the specified orientation gets normalized if it's not already. ...
XRRigidTransform.inverse - Web APIs
the read-only inverse property of the xrrigidtransform interface returns another xrrigidtransform object which is the inverse of its owning transform. that is, you can always get the inverse of any xrrigidtransform using its inverse property, instead of having to explicitly generate it. syntax let transforminverse = xrrigidtransform.inverse; value an xrrigidtransform which contains the inverse of the xrrigidtransform on which it's accessed. applying the inverse of a transform to any object previously transformed by the parent xrrigidtransform always undoes the transformation, resulting in the object returning to its previous pose. in other words, its position and orientation both return to their prior configurations. examples in this example, the model view matrix for an object is com...
... object is computed by taking the view matrix and multiplying it by the object's pose matrix. let modelviewmatrix = mat4.create(); for (let view of pose.view) { let viewport = gllayer.getviewport(view); gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); /* ... */ mat4.multiply(modelviewmatrix, view.transform.inverse.matrix, objectmatrix); gl.uniformmatrix4fv(programinfo.uniformlocations.modelviewmatrix, false, modelviewmatrix); /* ... */ } this outline of a renderer's core code shows how the pose's view gets represented by taking its transform's inverse's matrix as the model view matrix used to transform objects based on the viewer's position and orientation. the inverse's matrix is multiplied by the object's matrix to get the model ...
XRSession.onsqueeze - Web APIs
controller inputs, see inputs and input sources. syntax xrsession.onsqueeze = squeezehandlerfunction; value a function to be invoked whenever the xrsession receives a squeeze event. examples handling squeeze events for a specific hand this snippet of code adds a simple handler for the squeeze event, which responds only to events on the user's off-hand (that is, the hand that isn't their dominant hand). this is determined by comparing the input source's handedness against the value of a handedness property on a user object we've established previously. xrsession.onsqueeze = event => { if (event.inputsource.handedness != user.handedness) { handleoffhandsqueeze(event.inputsource, event.frame); } }; finishing an ongoing squeeze action this example exapnds somewhat on the previ...
...leoffhandsqueeze(event.inputsource, event.frame); } }; finishing an ongoing squeeze action this example exapnds somewhat on the previous example by demonstrating a way to implement the ability for the user to drop an object that was previously picked up by the user.. this is just a snippet of code, but should establish the general idea. after checking that the event occurred on the user's dominant hand, the pose's target ray is obtained. 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. this also clears the value of heldobject so we know that there's no longer an object in hand. xrsession.onsqueeze = event => {...
XRSession.requestReferenceSpace() - Web APIs
d for each reference space type constant.. reference space descriptors the types of reference space are listed in the table below, with brief information about their use cases and which interface is used to implement them. xrreferencespacetype description interface bounded-floor similar to the local type, except the user is not expected to move outside a predetermined boundary, given by the boundsgeometry in the returned object. xrboundedreferencespace local a tracking space whose native origin is located near the viewer's position at the time the session was created. the exact position depends on the underlying platform and implementation. the user isn't expected to move much if at all beyond their starting position, and tracking is opti...
... may drift as needed to accommodate that need. xrreferencespace viewer a tracking space whose native origin tracks the viewer's position and orientation. this is used for environments in which the user can physically move around, and is supported by all instances of xrsession, both immersive and inline, though it's most useful for inline sessions. it's particularly useful when determining the distance between the viewer and an input, or when working with offset spaces. otherwise, typically, one of the other reference space types will be used more often. xrreferencespace return value a promise that resolves with an xrreferencespace object. exceptions rather than throwing true exceptions, requestreferencespace() rejects the returned promise with a domexception whose...
XRSession: selectend event - Web APIs
the webxr event selectend is sent to an xrsession when one of its input sources ends its primary action or when an input source that's in the process of handling an ongoing primary action is disconnected without successfully completing the action. 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. bubbles yes cancelable no interface xrinputsourceevent event handler property onselectend for details on how the selectstart, select, and selectend events work, and how you should react to them, see primary actions in inputs and input sources. examples the followi...
...ed successfully, the code then uses the value of event property type to route control to an appropriate function to handle the event which arrived: for selectstart events, a mybegintracking() function is called with the target ray pose's matrix. 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. mybegintracking() returns an object representing the object the user has begun to drag. upon receiving a select event, the mydropobject() function is called with the target object and the current target ray pose transform as inputs. this places the object into its new position in the world and triggers any effects that may arise from doing so (like scheduling an anima...
XRSession: selectstart event - Web APIs
the webxr event selectstart is sent to an xrsession when the user begins a primary action on one of its input sources. 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. bubbles yes cancelable no interface xrinputsourceevent event handler property onselectstart for details on how the selectstart, select, and selectend events work, and how you should react to them, see primary actions in inputs and input sources. examples the following example uses addeventlistener() to establish handlers for the selection events: selectstart, selectend, and select. this sni...
...ed successfully, the code then uses the value of event property type to route control to an appropriate function to handle the event which arrived: for selectstart events, a mybegintracking() function is called with the target ray pose's matrix. 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. mybegintracking() returns an object representing the object the user has begun to drag. upon receiving a select event, the mydropobject() function is called with the target object and the current target ray pose transform as inputs. this places the object into its new position in the world and triggers any effects that may arise from doing so (like scheduling an anima...
XRSession: squeezeend event - Web APIs
the webxr event squeezeend is sent to an xrsession when one of its input sources ends its primary action or when an input source that's in the process of handling an ongoing primary action is disconnected without successfully completing the action. 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. bubbles yes cancelable no interface xrinputsourceevent event handler property onsqueezeend for details on how the squeezestart, squeeze, and squeezeend events work, and how you should react to them, see primary squeeze actions in inputs and input sources. ...
...d successfully, the code then uses the value of event property type to route control to an appropriate function to handle the event which arrived: for squeezestart events, a mybegintracking() function is called with the target ray pose's matrix. 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. mybegintracking() returns an object representing the object the user has begun to drag. upon receiving a squeeze event, the mydropobject() function is called with the target object and the current target ray pose transform as inputs. this places the object into its new position in the world and triggers any effects that may arise from doing so (like scheduling an anim...
XRSessionEvent() - Web APIs
nts announcing state changes in an xrsession representing an augmented or virtual reality session. syntax newxrsessionevent = new xrsessionevent(type, eventinitdict); parameters type a domstring indicating which of the events represented by objects of type xrsessionevent this particular object represents. see event types for a list of the permitted values. eventinitdict an object conforming to the xrsessioneventinit dictionary which contains values to be applied to the newly-created event object. permitted values are: session the xrsession to which the event is to be delivered. return value a newly-created xrsessionevent object representing an object of the specfied type and configured as described by the eventinitdict parameter. event types the following events are re...
...n to which the event is to be delivered. return value a newly-created xrsessionevent object representing an object of the specfied type and configured as described by the eventinitdict parameter. event types the following events are represented using the xrsessionevent interface, and are permitted values for its type property. end fired at the session when it has ended, after being terminated by the application or the user agent. visibilitychange fired at the session whenever its visibility state changes. examples this example creates a listiener that watches for the visibility state of the session to change. it reacts by calling a function mysessionvisible() with a boolean indicating whether or not the session is visible; this function might, for instance, spin up or reconfi...
XRWebGLLayerInit.antialias - Web APIs
rendering layer. if false, anti-aliasing is not desired. usage notes the state of anti-aliasing for the context after being created can be read from the xrwebgllayer property antialias. 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. let options = { antialias: getpreferencevalue("antialiasing") }; let gllayer = new xrwebgllayer(xrsession, gl, options); if (gllayer) { xrsession.updaterenderstate({ baselayer: gllayer }); } offering the user features such as the ability to enable or disable things like anti-aliasing can ...
...port; this is passed into the constructor. let options = { antialias: getpreferencevalue("antialiasing") }; let gllayer = new xrwebgllayer(xrsession, gl, options); if (gllayer) { xrsession.updaterenderstate({ baselayer: gllayer }); } offering the user features such as the ability to enable or disable things like anti-aliasing can provide them with optiions to try when your app isn't performing as well as they'd like. disabling anti-aliasing may improve performance to some extent. specifications specification status comment webxr device apithe definition of 'xrwebgllayerinit.antialias' in that specification. working draft initial definition. ...
ARIA: timer role - Accessibility
eraction. the timer role does not have a related html widget and xxx. the author of the timer must take full responsibility for not letting users get stuck in a focus limbo or trap focus inside something the user cannot exit of. all aspects of interaction, including returning to the regular web content on other parts of the page, must be handled. use wisely, and cautiously! examples some prominent web timers include clocks, stop watches and countdowns, such as ticketing websites, e-commerce sites, and event countdowns (see https://countingdownto.com/). as an illustration of aria-atomic, consider a site with a simple clock, showing hours and minutes. the clock is updated each minute, with the new remaining time simply overwriting the current content. <div id="clock" role="timer" aria-l...
...t that changed compared to the previous content will be announced. for instance, when the clock changes from "17:33" to "17:34", assistive technologies will only announce "4", which won't be very useful to users. one way around this would be to first clear the contents of the live region, and then inject the new content. however, this can sometimes be unreliable, as it's dependent on the exact timing of these two updates. aria-atomic="true" ensures that each time the live region is updated, the entirety of the content is announced in full (e.g. "time: 17:34"). <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 int...
ARIA: tab role - Accessibility
tton role="tab" aria-selected="true" aria-controls="tabpanel-id" id="tab-id">tab label</button> description an element with the tab role controls the visibility of an associated element with the tabpanel role. the common user experience pattern is a group of visual tabs above, or to the side of, a content area, and selecting a different tab changes the content and makes the selected tab more prominent than the other tabs. elements with the role tab must either be a child of an element with the tablist role, or have their id part of the aria-owns property of a tablist. this combination identifies to assistive technology that the element is part of a group of related elements. some assistive technology will provide a count of the number of tab role elements inside a tablist, and inform users...
...lement to -1, making it no longer tabbable. then, if the right arrow is being pressed, we increase our tab focus counter by one. if the counter is greater than the number of tab elements we have, we circle back to the first tab by setting that counter to 0. if the left arrow is being pressed, we decrease our tab focus counter by one, and if it is then less than 0, we set it number of tab elements minus one (to get to the last element). finally, we set focus to the tab element whose index is equal to the tab focus counter, and set its tabindex to 0 to make it tabbable. to handle changing the active tab and tabpanel, we have a function that takes in the event, gets the element that triggered the event, the triggering element's parent element, and its grandparent element. we then find all tabs ...
ARIA: checkbox role - Accessibility
nstead of re-purposing an element and adding aria. instead use the native html checkbox of <input type="checkbox">, which natively provides all the functionality required: <input type="checkbox" id="chk1-label"> <label for="chk1-label">remember my preferences</label> description the native html checkbox form control can only have two checked states ("checked" or "not checked"), with an indeterminate state settable via javascript. similarly, an element with role="checkbox" can expose three states through the aria-checked attribute: true, false, or mixed. since a checkbox is an interactive control, it must be focusable and keyboard accessible. if the role is applied to a non-focusable element, use the tabindex attribute to change this. the expected keyboard shortcut for activating a check...
... value of the aria-checked attribute dynamically when the checkbox is activated. associated wai-aria roles, states, and properties aria-checked the value of aria-checked defines the state of a checkbox. this attribute has one of three possible values: true the checkbox is checked false the checkbox is not checked mixed the checkbox is partially checked, or indeterminate tabindex="0" used to make it focusable so the assistive technology user can tab to it and start reading right away. keyboard interactions key function space activates the checkbox required javascript required event handlers onclick handle mouse clicks that will change the state of the checkbox by changing the value of the aria-checked attribute and th...
ARIA: dialog role - Accessibility
with the dialog using the aria-describedby attribute. this approach is shown in the code snippet below: <div role="dialog" aria-labelledby="dialog1title" aria-describedby="dialog1desc"> <h2 id="dialog1title">your personal details were successfully updated</h2> <p id="dialog1desc">you can change your details at any time in the user account section.</p> <button>close</button> </div> keep in mind that a dialog's title and description text do not have to be focusable in order to be perceived by screen readers operating in a non-virtual mode. the combination of the aria dialog role and labeling techniques should make the screen reader announce the dialog's information when focus is moved into it. required javascript features focus management a dialog has particular requirements for how...
...ing their screen reader's virtual cursor. it is important for developers to ensure that content outside of the modal dialog is inaccessible to all users while the modal dialog is active. specifications specification status accessible rich internet applications (wai-aria) 1.1the definition of 'alert' in that specification. recommendation screen reader support coming soon ...
Basic form hints - Accessibility
wai-aria, the accessible rich internet applications specification from the w3c's web accessibility initiative, provides the aria-labe...
...wai-aria, the accessible rich internet applications specification from the w3c's web accessibility initiative, provides the aria-labelledby attribute for these cases. the exampl...
Accessibility and Spacial Patterns - Accessibility
spatial localization nasa conducted research on the perception of color, and found that luminance contrast mattered greatly as to how they were perceived. the two images below are from nasa research, specifically, from the article, "designing with blue" "spatial localization. symbols which have the same luminance as their background are perceptually less securely located in space and time than are symbols with higher luminance contrast. they tend to "float" visually or be "captured" by adjacent symbols with high luminance-contrast. the phenomenon seems to be especially problematic for symbol/background combinations that differ only in the blue channel." distance between stripes photosensitive seizures may be caused by static images as well as animation. the mechanism for this i...
... and its version. for example, borders on svg can extend both inward and outward from its dimensions, or for newer versions of svg, entirely outward from it, thus reducing the space around the svg to enable perception. ...
Accessibility Information for Web Authors - Accessibility
guidelines and regulations section 508 guidelines for web authors these guidelines must be followed by u.s. websites. other organizations such as schools are starting to follow these guidelines as well. web content accessibility guidelines (wcag) 1.0 another important set of guidelines from the w3c web accessibility initiative (wai). the european union is looking to base their upcoming accessibility regulations on these guidelines. these guidelines are discussed on the wai interest group discussion list. how-to's key-navigable custom dhtml widgets in mozilla & ie this document discusses how to use tabindex, element.focus() and onkeypress to make custom dhtml widgets such as menus or tree views keyboard accessible. accessible web page authoring ibm has put togeth...
...validator may also be downloaded from firefox add-ons: html validator. color contrast analyzer by juicy studio "contrast is the perceived difference between two adjacent colors. (...) contrast is extremely important in web design." wheel of color: pump up the contrast, robert hess, msdn "for this year's list of worst design mistakes, (...) i asked readers of my newsletter to nominate the usability problems they found the most irritating. (...) about one-third complained about low contrast between text and background." top ten web design mistakes of 2005: 1. legibility problems how can a web author establish easily and quickly if the background color and foreground (text) color in use in his webpages have sufficient color contrast difference and sufficient color br...
Text labels and names - Accessibility
ria-label aria-labelledby wai-aria: dialog role dialog authoring practices documents must have a title it is important on each html document to include a <title> that describes the page's purpose. a common navigation technique for users of assistive technology is to infer what content a page contains by reading its title. 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. examples the title for the reference article about the <title> element is as follows: <title>&lt;title&gt;: the document title element - html: hypertext markup language</title> another example might look like so: <title>fill in your details to register — mygov services</title> to help the user, you can update t...
...ctice to label a toolbar, even if there is only one per page. see also w3c aria toolbar example related wcag success criteria 1.1.1 non-text content (a) all non-text content that is presented to the user has a text alternative that serves the equivalent purpose, except for the situations listed in the above link. 2.4.4 link purpose (in context) (a) the purpose of each link can be determined from the link text alone or from the link text together with its programmatically determined link context, except where the purpose of the link would be ambiguous to users in general. 2.4.9 link purpose (link only) (aaa) a mechanism is available to allow the purpose of each link to be identified from link text alone, except where the purpose of the link would be ambiguous to users in general.
::placeholder - CSS: Cascading Style Sheets
important to ensure that the contrast ratio between the color of the placeholder text and the background of the input is high enough that people experiencing low vision conditions will be able to read it while also making sure there is enough of a difference between the placeholder text and input text color that users do not mistake the placeholder for inputed data. color contrast ratio is determined by comparing the luminosity of the placeholder text and the input background color values. in order to meet current web content accessibility guidelines (wcag), a ratio of 4.5:1 is required for text content and 3:1 for larger text such as headings. large text is defined as 18.66px and bold or larger, or 24px or larger. webaim: color contrast checker mdn understanding wcag, guideline 1.4 exp...
...-hint">example: jane@sample.com</span> <input id="user-email" aria-describedby="user-email-hint" name="email" type="email"> placeholders in form fields are harmful — nielsen norman group windows high contrast mode placeholder text will appear with the same styling as user-entered text content when rendered in windows high contrast mode. this will make it difficult for some people to determine which content has been entered, and which content is placeholder text. greg whitworth — how to use -ms-high-contrast labels placeholders are not a replacement for the <label> element. 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. mdn ba...
:in-range - CSS: Cascading Style Sheets
Web › CSS › :in-range
/* selects any <input>, but only when it has a range specified, and its value is inside that range */ input:in-range { background-color: rgba(0, 255, 0, 0.25); } this pseudo-class is useful for giving the user a visual indication that a field's current value is within the permitted limits. note: this pseudo-class only applies to elements that have (and can take) a range limitation. ...
...e permitted limits. note: this pseudo-class only applies to elements that have (and can take) a range limitation. in the absence of such a limitation, the element can neither be "in-range" nor "out-of-range." syntax :in-range examples html <form action="" id="form1"> <ul>values between 1 and 10 are valid. ...
:out-of-range - CSS: Cascading Style Sheets
/* selects any <input>, but only when it has a range specified, and its value is outside that range */ input:out-of-range { background-color: rgba(255, 0, 0, 0.25); } this pseudo-class is useful for giving the user a visual indication that a field's current value is outside the permitted limits. note: this pseudo-class only applies to elements that have (and can take) a range limitation. ...
...imits. note: this pseudo-class only applies to elements that have (and can take) a range limitation. ...
@counter-style - CSS: Cascading Style Sheets
@counter-style thumbs { system: cyclic; symbols: "\1f44d"; suffix: " "; } ul { list-style: thumbs; } the initial version of css defined a set of useful counter styles. however, although more styles were added to this set of predefined styles over the years, this system proved too restrictive to fulfill the needs of worldwide typography. the @counter-style at-rule addresses this shortcoming in an open-ended manner, by allowing authors to define their own counter styles when the pre-defined styles aren't fitting their needs. syntax descriptors each @counter-style is identified by a name and has a set of descriptors. system specifies the algorithm to be used for converting the integer value of a counter to a string representation. negative lets the author specify symbols ...
...scriptor, a symbol that is appended to the marker representation. suffixes come after the marker representation. range defines the range of values over which the counter style is applicable. if a counter style is used to represent a counter value outside of its ranges, the counter style will drop back to its fallback style. pad is used when you need the marker representations to be of a minimum length. for example if you want the counters to start at 01 and go through 02, 03, 04 etc, then the pad descriptor is to be used. for representations larger than the specified pad value, the marker is constructed as normal. fallback specifies a system to fall back into if either the specified system is unable to construct the representation of a counter value or if the counter value outs...
-ms-high-contrast - CSS: Cascading Style Sheets
ation is being displayed in high contrast mode, and with what color variation. high contrast mode is a specialized display mode that prioritizes making content as legible as possible by dynamically replacing foreground and background colors with a user-specified theme. for web content, theme colors are mapped to content types. this media feature applies to bitmap media types. it does not accept min/max prefixes. syntax the -ms-high-contrast media feature is specified as one of the following values. values none ... no longer supported as of microsoft edge 18. active indicates that the subsequent styling rules will be applied when the system is placed in high contrast mode with any color variation. black-on-white indicates that the subsequent styling rules will be applied ...
...lor variation, and a white-on-black color variation, respectively. @media screen and (-ms-high-contrast: active) { /* all high contrast styling rules */ } @media screen and (-ms-high-contrast: black-on-white) { div { background-image: url('image-bw.png'); } } @media screen and (-ms-high-contrast: white-on-black) { div { background-image: url('image-wb.png'); } } accessibility concerns theming high contrast mode's theme colors come from a limited subset of deprecated css2 system colors. the available color keywords are: windowtext: controls the color of text content. highlighttext: controls the color of selected text. highlight: controls the background color of selected text. buttonface: controls the color of a <button> element's text. window: controls the color of the backgro...
device-height - CSS: Cascading Style Sheets
examples this html applies a special stylesheet for devices that are shorter than 800 pixels. ...
... examples this html applies a special stylesheet for devices that are shorter than 800 pixels. ...
device-width - CSS: Cascading Style Sheets
examples this html applies a special stylesheet for devices that are narrower than 800 pixels. ...
... examples this html applies a special stylesheet for devices that are narrower than 800 pixels. ...
height - CSS: Cascading Style Sheets
Web › CSS › @media › height
the height css media feature can be used to apply styles based on the height of the viewport (or the page box, for paged media). syntax the height feature is specified as a <length> value representing the viewport height. it is a range feature, meaning that you can also use the prefixed min-height and max-height variants to query minimum and maximum values, respectively. ...
...ght feature is specified as a <length> value representing the viewport height. it is a range feature, meaning that you can also use the prefixed min-height and max-height variants to query minimum and maximum values, respectively. examples html <div>watch this element as you resize your viewport's height.</div> css /* exact height */ @media (height: 360px) { div { color: red; } } /* minimum height */ @media (min-height: 25rem) { div { background: yellow; } } /* maximum height */ @media (max-height: 40rem) { div { border: 2px solid blue; } } result specifications specification status comment media queries level 4the definition of 'height' in that specification. candidate recommendation the value can now be negative, in whic...
resolution - CSS: Cascading Style Sheets
Web › CSS › @media › resolution
the resolution css media feature can be used to test the pixel density of the output device. syntax the resolution feature is specified as a <resolution> value representing the pixel density of the output device. it is a range feature, meaning that you can also use the prefixed min-resolution and max-resolution variants to query minimum and maximum values, respectively. ...
...as a <resolution> value representing the pixel density of the output device. it is a range feature, meaning that you can also use the prefixed min-resolution and max-resolution variants to query minimum and maximum values, respectively. examples html <p>this is a test of your device's pixel density.</p> css /* exact resolution */ @media (resolution: 150dpi) { p { color: red; } } /* minimum resolution */ @media (min-resolution: 72dpi) { p { text-decoration: underline; } } /* maximum resolution */ @media (max-resolution: 300dpi) { p { background: yellow; } } result specifications specification status comment media queriesthe definition of 'resolution' in that specification. recommendation initial definition. ...
width - CSS: Cascading Style Sheets
Web › CSS › @media › width
the width css media feature can be used to test the width of the viewport (or the page box, for paged media). syntax the width feature is specified as a <length> value representing the viewport width. it is a range feature, meaning that you can also use the prefixed min-width and max-width variants to query minimum and maximum values, respectively. ...
...the width feature is specified as a <length> value representing the viewport width. it is a range feature, meaning that you can also use the prefixed min-width and max-width variants to query minimum and maximum values, respectively. examples html <div>watch this element as you resize your viewport's width.</div> css /* exact width */ @media (width: 360px) { div { color: red; } } /* minimum width */ @media (min-width: 35rem) { div { background: yellow; } } /* maximum width */ @media (max-width: 50rem) { div { border: 2px solid blue; } } result specifications specification status comment media queries level 4the definition of 'width' in that specification. candidate recommendation the value can now be negative, in which cas...
zoom - CSS: Cascading Style Sheets
Web › CSS › @viewport › zoom
<number> a non-negative number used as the zoom factor. ...
... <number> a non-negative number used as the zoom factor. <percentage> a non-negative percentage value used as the zoom factor. ...
CSS Basic Box Model - CSS: Cascading Style Sheets
css basic box model is a module of css that defines the rectangular boxes—including their padding and margin—that are generated for elements and laid out according to the visual formatting model. ...
...ox model is a module of css that defines the rectangular boxes—including their padding and margin—that are generated for elements and laid out according to the visual formatting model. reference properties properties controlling the flow of content in a box overflow overflow-x overflow-y properties controlling the size of a box height width max-height max-width min-height min-width properties controlling the margins of a box margin margin-bottom margin-left margin-right margin-top margin-trim properties controlling the paddings of a box padding padding-bottom padding-left padding-right padding-top other properties visibility guides introduction to the css box model explains one of the fundamental concept of css: the box model. th...
Basic Concepts of Multicol - CSS: Cascading Style Sheets
multiple-column layout, usually referred to as multicol, is a specification for laying out content into a set of column boxes much like columns in a newspaper. this guide explains how the specification works with some common use case examples. key concepts and terminology multicol is unlike any of the other layout methods we have in css in that it fragments the content, including all descendent elements, into columns. this happens in the same way that content is fragmented into pages when we work with css paged media, for example by creating a print stylesheet. the properties defined by the specification are: column-width column-count columns column-rule-color column-rule-style column-rule-width column-rule column-span column-fill column-gap by adding column-count or column-...
...lements do not collapse with any margin on the container. the column-width property the column-width property is used to set the optimal width for every column box. if you declare a column-width, the browser will work out how many columns of that width will fit into the multicol container and distribute any extra space equally between the columns. therefore, the column width should be seen as a minimum width, as column boxes are likely to be wider due to the additional space. the column box will only shrink to be smaller than the declared column width in the case of a single column with less available width than the value of column-width. in the below example we use the column-width property with a value of 200px. we get as many 200 pixel columns as will fit the container, with the extra ...
Backwards Compatibility of Flexbox - CSS: Cascading Style Sheets
at a flex container is created. if you find something referring to display: box or display: flexbox this is outdated information. status in browsers browser support for flexbox is excellent, and the majority of browsers do not need a prefix at this point. safari was the last of the major browsers to remove prefixes, with the release of safari 9 in 2015. the two browsers you should still keep in mind for cross-browser compatibility are: internet explorer 10, which implemented the display: flexbox version of the specification with the -ms- prefix. uc browser, which still supports the 2009 display: box version only with the -webkit- prefix. note also that internet explorer 11 supports the modern display: flex specification however it has a number of bugs in the implementation. common is...
... flexbugs site is a helpful resource. you will see that many of the listed bugs apply to old browser versions and are fixed in current browsers. each of the bugs has a workaround listed — which can save you many hours of puzzling. if you want to include very old browsers with flexbox support then you can include the vendor prefixes in your css in addition to the unprefixed version. this is becoming less and less of a requirement today as support is widespread. .wrapper { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; } autoprefixer online is a useful way to see which prefixes are recommended, depending on how many versions you wish to go back with browser support. you can also check can i use for information about when prefixes were removed in ...
Introduction to formatting contexts - CSS: Cascading Style Sheets
a bfc contains everything inside it, float and clear only apply to items inside the same formatting context, and margins only collapse between elements in the same formatting context. bfc creation examples let's have a look at a couple of these in order to see the effect creating a new bfc. in the example below, we have a floated element inside a <div> with a bo...
...lements, the float has been taken out of flow so the background and border of the div only contain the content and not the float. creating a new bfc would contain the float. a typical way to do this in the past has been to set overflow: auto or set other values than the initial value of overflow: visible. setting overflow: auto created a new bfc containing the float. our <div> now becomes a mini-layout inside our layout. any child element will be contained inside it. 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. there are some occasions in which you will find you get unwanted scrollbars or clipped shadows when you use this property purely to create a bfc. in addition, it ...
Subgrid - CSS: Cascading Style Sheets
f the parent, the nested grid will have three column tracks of the same size as the parent grid. gaps are inherited but can also be overridden with a different gap value. line names can be passed from the parent into the subgrid, and the subgrid can also declare its own line names. subgrid for columns in the example below i have a grid layout with nine 1fr column tracks and four rows that are a minimum of 100px tall. i place .item from column line 2 to 7, and row 2 to 4. i then make this grid item into a grid, giving it column tracks that are a subgrid and defining rows as normal. as the item spans five column tracks, this means that the subgrid has five column tracks. i can then place .subitem on this grid. the rows in this example are not a subgrid and so behave as a nested grid does no...
...ample below using the parent lines, and one using the subgrid lines. using subgrids other than needing to take care of items that do not fit in your subgrid, a subgrid acts very similarly to any nested grid; the only difference is that the track sizing of the subgrid is set on the parent grid. as with any nested grid however, the size of content in the subgrid can change the track sizing, assuming a track sizing method is used that allows content to affect the size. in such a case, auto-sized row tracks for example will grow to fit content in the main grid and content in the subgrid. as the subgrid value acts in much the same way as a regular nested grid, it is easy to switch between the two. for example, if you realise that you need an implicit grid for rows, all you would need to do is...
Consistent list indentation - CSS: Cascading Style Sheets
n't have the same effect in another. for example, if you declare that lists have no left margin, they move over in internet explorer, but sit stubbornly in place in gecko-based browsers.this article will help you understand the problems that can occur and how to avoid them. in order to understand why this is the case, and more importantly how to avoid the problem altogether, it's necessary to examine the details of list construction. making a list first, we consider a single, pure list item. this list item has no marker (otherwise known as a "bullet") and is not yet part of a list itself. it hangs alone in the void, simple and unadorned, as shown in figure 1. that dotted red border represents outer edges of the content-area of the list item. remember that, at this point, the list item h...
... not the important part here. what's key is that the markers are placed outside the "principal box" of the <li> elements, not the <ul>. they're sort of like appendages to the list items, hanging outside the content-area of the <li> but still attached to the <li>. this is why, in every browser except internet explorer for windows, markers are placed outside any border set for an <li> element, assuming the value of list-style-position is outside. if it's changed to inside, then the markers are brought inside the <li>'s content, as though they're an inline box placed at the very beginning of the <li>. indenting it twice so how will all this appear in a document? at the moment, we have a situation analogous to these styles: ul, li {margin-left: 0; padding-left: 0;} if we dropped this list in...
CSS Logical Properties and Values - CSS: Cascading Style Sheets
standard english text, it is the vertical dimension. inline dimension the dimension parallel to the flow of text within a line, i.e., the horizontal dimension in horizontal writing modes, and the vertical dimension in vertical writing modes. for standard english text, it is the horizontal dimension. ...
... text, it is the vertical dimension. inline dimension the dimension parallel to the flow of text within a line, i.e., the horizontal dimension in horizontal writing modes, and the vertical dimension in vertical writing modes. for standard english text, it is the horizontal dimension. ...
Introducing the CSS Cascade - CSS: Cascading Style Sheets
Web › CSS › Cascade
nt, or @supports — participate in the cascade, declarations contained in @keyframes don't. as with @font-face, only the at-rule as a whole is selected via the cascade algorithm. finally, note that @import and @charset obey specific algorithms and aren't affected by the cascade algorithm. origin of css declarations the css cascade algorithm's job is to select css declarations in order to determine the correct values for css properties. css declarations originate from different origins: the user-agent stylesheets, the author stylesheets, and the user stylesheets. though style sheets come from these different origins, they overlap in scope; to make this work, the cascade algorithm defines how they interact. user-agent stylesheets the browser has a basic style sheet that gives a default s...
...ge or site. 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. cascading order the cascading algorithm determines how to find the value to apply for each property for each document element. it first filters all the rules from the different sources to keep only the rules that apply to a given element. that means rules whose selector matches the given element and which are part of an appropriate media at-rule. then it sorts these rules according to their importance, that is, whether or not they are follo...
Layout and the containing block - CSS: Cascading Style Sheets
the size and position of an element are often impacted by its containing block. most often, the containing block is the content area of an element's nearest block-level ancestor, but this is not always the case. in this article, we examine the factors that determine an element's containing block. when a user agent (such as your browser) lays out a document, it generates a box for every element. ...
...nt's containing block. when a user agent (such as your browser) lays out a document, it generates a box for every element. each box is divided into four areas: content area padding area border area margin area many developers believe that the containing block of an element is always the content area of its parent, but that isn't necessarily true. let's investigate the factors that determine what an element's containing block is. effects of the containing block before learning what determines the containing block of an element, it's useful to know why it matters in the first place. the size and position of an element are often impacted by its containing block. percentage values that are applied to the width, height, padding, margin, and offset properties of an absolutely position...
Pseudo-classes - CSS: Cascading Style Sheets
you can chain together as many pseudo-classes as you want in a selector. ...
...:required, :optional, :read-only and :read-write, but without the associated semantic meaning. selectors level 3 recommendation defined :target, :root, :nth-child(), :nth-last-of-child(), :nth-of-type(), :nth-last-of-type(), :last-child, :first-of-type, :last-of-type, :only-child, :only-of-type, :empty and :not(). defined the syntax of :enabled, :disabled, :checked, and :indeterminate, but without the associated semantic meaning. no significant change for pseudo-classes defined in css level 2 (revision 1). css level 2 (revision 1) recommendation defined :lang(), :first-child, :hover, and :focus. no significant change for pseudo-classes defined in css level 1. css level 1 recommendation defined :link, :visited and :active, but without th...
animation-direction - CSS: Cascading Style Sheets
l the animation plays forwards each cycle. in other words, each time the animation cycles, the animation will reset to the beginning state and start over again. this is the default value. reverse the animation plays backwards each cycle. in other words, each time the animation cycles, the animation will reset to the end state and start over again. ...
...each time the animation cycles, the animation will reset to the beginning state and start over again. this is the default value. reverse the animation plays backwards each cycle. in other words, each time the animation cycles, the animation will reset to the end state and start over again. animation steps are performed backwards, and timing functions are also reversed. for example, an ease-in timing function becomes ease-out. alternate the animation reverses direction each cycle, with the first iteration being played forwards. the count to determine if a cycle is even or odd starts at one. alternate-reverse the animation reverses direction each cycle, with the first iteration being played backwards. the count to determine if a cycle is even or odd starts at one. note: when you specif...
border-bottom-left-radius - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. the rounding can be a circle or an ellipse, or if one of the value is 0 no rounding is done and the corner is square. ...
...with two values: the first value is a <length> or a <percentage> denoting the horizontal semi-major axis of the ellipse to use for the border in that corner. the second value is a <length> or a <percentage> denoting the vertical semi-major axis of the ellipse to use for the border in that corner. values <length-percentage> denotes the size of the circle radius or the semi-major and semi-minor axes of the ellipse. as absolute length it can be expressed in any unit allowed by the css <length> data type. percentages for the horizontal axis refer to the width of the box, percentages for the vertical axis refer to the height of the box. negative values are invalid. formal definition initial value0applies toall elements; but user agents are not required to apply to table and inline-tab...
border-bottom-right-radius - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. the rounding can be a circle or an ellipse, or if one of the value is 0 no rounding is done and the corner is square. ...
...with two values: the first value is a <length> or a <percentage> denoting the horizontal semi-major axis of the ellipse to use for the border in that corner. the second value is a <length> or a <percentage> denoting the vertical semi-major axis of the ellipse to use for the border in that corner. values <length-percentage> denotes the size of the circle radius or the semi-major and semi-minor axes of the ellipse. as absolute length it can be expressed in any unit allowed by the css <length> data type. percentages for the horizontal axis refer to the width of the box, percentages for the vertical axis refer to the height of the box. negative values are invalid. formal definition initial value0applies toall elements; but user agents are not required to apply to table and inline-tab...
border-top-left-radius - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. the rounding can be a circle or an ellipse, or if one of the value is 0,no rounding is done and the corner is square. ...
...with two values: the first value is a <length> or a <percentage> denoting the horizontal semi-major axis of the ellipse to use for the border in that corner. the second value is a <length> or a <percentage> denoting the vertical semi-major axis of the ellipse to use for the border in that corner. values <length-percentage> denotes the size of the circle radius or the semi-major and semi-minor axes of the ellipse. as absolute length it can be expressed in any unit allowed by the css <length> data type. percentages for the horizontal axis refer to the width of the box, percentages for the vertical axis refer to the height of the box. negative values are invalid. formal definition initial value0applies toall elements; but user agents are not required to apply to table and inline-tab...
border-top-right-radius - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. the rounding can be a circle or an ellipse, or if one of the value is 0 no rounding is done and the corner is square. ...
...with two values: the first value is a <length> or a <percentage> denoting the horizontal semi-major axis of the ellipse to use for the border in that corner. the second value is a <length> or a <percentage> denoting the vertical semi-major axis of the ellipse to use for the border in that corner. values <length-percentage> denotes the size of the circle radius or the semi-major and semi-minor axes of the ellipse. as absolute length it can be expressed in any unit allowed by the css <length> data type. percentages for the horizontal axis refer to the width of the box, percentages for the vertical axis refer to the height of the box. negative values are invalid. formal definition initial value0applies toall elements; but user agents are not required to apply to table and inline-tab...
<color> - CSS: Cascading Style Sheets
mediumaquamarine #66cdaa mediumblue #0000cd mediumorchid #ba55d3 mediumpurple #9370db mediumseagreen #3cb371 mediumslateblue #7b68ee mediumspringgreen #00fa9a mediumturquoise #48d1cc mediumvioletred #c71585 midnightblue #191970 mintcream #f5fffa mistyrose #ffe4e1 moccasin #ffe4b5 navajowhite #ffdead oldlace #fdf5e6 olivedrab #6b8e23 orangered #ff4500 orchid #da70d6 palegoldenrod #eee8aa palegreen #98fb98 paleturquoise #afeeee palevioletred #db7093 ...
... background color. interpolation in animations and gradients, <color> values are interpolated on each of their red, green, and blue components. each component is interpolated as a real, floating-point number. note that interpolation of colors happens in the alpha-premultiplied srgba color space to prevent unexpected gray colors from appearing. in animations, the interpolation's speed is determined by the timing function. accessibility considerations some people have difficulty distinguishing colors. the wcag 2.0 recommendation strongly advises against using color as the only means of conveying a specific message, action, or result. see color and color contrast for more information. examples color value tester in this example we provide a <div> and a text input. entering a valid colo...
cursor - CSS: Cascading Style Sheets
Web › CSS › cursor
e end of the fallback list. see using url values for the cursor property for more details. <x> <y> optional x- and y-coordinates. two unitless nonnegative numbers less than 32. keyword values move your mouse over values to see their live appearance in your browser: category css value example description general auto the ua will determine the cursor to display based on the current context. e.g., equivalent to text when hovering text. default the platform-dependent default cursor. typically an arrow. none no cursor is rendered. links & status context-menu a context menu is available. help help information is available. pointer ...
...ple, n-resize and s-resize are the same as ns-resize. e-resize s-resize w-resize ne-resize nw-resize se-resize sw-resize ew-resize bidirectional resize cursor. ns-resize nesw-resize nwse-resize zooming zoom-in something can be zoomed (magnified) in or out. zoom-out usage notes although the specification does not define any size limitations for cursor, individual user agents may choose to do so. cursor changes using images which are outside the size range supported by the browser will generally just be ignored. check the browser compatibil...
<easing-function> - CSS: Cascading Style Sheets
tom: 20px; } javascript const selectelem = document.queryselector('select'); const startbtn = document.queryselector('button'); const divelem = document.queryselector('div > div'); startbtn.addeventlistener('click', () => { if(startbtn.textcontent === 'start animation') { divelem.style.animationname = 'move-right'; startbtn.textcontent = 'stop animation'; divelem.style.animationtimingfunction = selectelem.value; } else { divelem.style.animationname = 'unset'; startbtn.textcontent = 'start animation'; } }); selectelem.addeventlistener('change', () => { divelem.style.animationtimingfunction = selectelem.value; }); result cubic-bezier() function examples these cubic bézier curves are valid for use in css: /* the canonical bézier curve with four <number> in...
... these easing function are invalid: /* the first parameter must be an <integer> and cannot be a real value, even if it is equal to one. */ steps(2.0, jump-end) /* the amount of steps must be non-negative. */ steps(-3, start) /* there must be at least one step.*/ steps(0, jump-none) specifications specification status comment css animationsthe definition of '<timing-function>' in that specification. working draft defines <single-timing-function> as a synonym for <single-transition-timing-function> of the css transitions module. css timing functions level 1the definition of '<easing-function>' in that specification. working draft initial definition. ...
<filter-function> - CSS: Cascading Style Sheets
nt.queryselector('input'); const output = document.queryselector('output'); const curvalue = document.queryselector('p code'); selectelem.addeventlistener('change', () => { setslider(selectelem.value); setdiv(selectelem.value); }); slider.addeventlistener('input', () => { setdiv(selectelem.value); }); function setslider(filter) { if(filter === 'blur') { slider.value = 0; slider.min = 0; slider.max = 30; slider.step = 1; slider.setattribute('data-unit', 'px'); } else if(filter === 'brightness' || filter === 'contrast' || filter === 'saturate') { slider.value = 1; slider.min = 0; slider.max = 4; slider.step = 0.05; slider.setattribute('data-unit', ''); } else if(filter === 'drop-shadow') { slider.value = 0; slider.min = -20; sli...
...ast' || filter === 'saturate') { slider.value = 1; slider.min = 0; slider.max = 4; slider.step = 0.05; slider.setattribute('data-unit', ''); } else if(filter === 'drop-shadow') { slider.value = 0; slider.min = -20; slider.max = 40; slider.step = 1; slider.setattribute('data-unit', 'px'); } else if(filter === 'opacity') { slider.value = 1; slider.min = 0; slider.max = 1; slider.step = 0.01; slider.setattribute('data-unit', ''); } else if(filter === 'grayscale' || filter === 'invert' || filter === 'sepia') { slider.value = 0; slider.min = 0; slider.max = 1; slider.step = 0.01; slider.setattribute('data-unit', ''); } else if(filter === 'hue-rotate') { slider.value = 0; slider.min = 0; slider.max =...
flex-basis - CSS: Cascading Style Sheets
tps://github.com/mdn/interactive-examples and send us a pull request. note: in case both flex-basis (other than auto) and width (or height in case of flex-direction: column) are set for an element, flex-basis has priority. syntax /* specify <'width'> */ flex-basis: 10em; flex-basis: 3px; flex-basis: auto; /* intrinsic sizing keywords */ flex-basis: fill; flex-basis: max-content; flex-basis: min-content; flex-basis: fit-content; /* automatically size based on the flex item’s content */ flex-basis: content; /* global values */ flex-basis: inherit; flex-basis: initial; flex-basis: unset; the flex-basis property is specified as either the keyword content or a <'width'>. values <'width'> an absolute <length>, a <percentage> of the parent flex container's main size property, or the...
...olor: white; font-size: 14px; text-align: center; position: relative; } .flex:after { position: absolute; z-index: 1; left: 0; top: 100%; margin-top: 10px; width: 100%; color: #333; font-size: 12px; } .flex1 { flex-basis: auto; } .flex1:after { content: 'auto'; } .flex2 { flex-basis: max-content; } .flex2:after { content: 'max-content'; } .flex3 { flex-basis: min-content; } .flex3:after { content: 'min-content'; } .flex4 { flex-basis: fit-content; } .flex4:after { content: 'fit-content'; } .flex5 { flex-basis: content; } .flex5:after { content: 'content'; } .flex6 { flex-basis: fill; } .flex6:after { content: 'fill'; } results specifications specification status comment css flexible box layout module...
font-size-adjust - CSS: Cascading Style Sheets
h defines the size of upper-case letters). /* use the specified font size */ font-size-adjust: none; /* use a font size that makes lowercase letters half the specified font size */ font-size-adjust: 0.5; /* global values */ font-size-adjust: inherit; font-size-adjust: initial; font-size-adjust: unset; the property is useful since the legibility of fonts, especially at small sizes, is determined more by the size of lowercase letters than by the size of capital letters. legibility can become an issue when the first-choice font-family is unavailable and its replacement has a significantly different aspect ratio (the ratio of the size of lowercase letters to the size of the font). to use this property in a way that is compatible with browsers that do not support font-size-adjust, it is s...
...; ... is really specifying that the lowercase letters of the font should be 7px high (0.5 × 14px). this will still produce reasonable results in browsers that do not support font-size-adjust, where a 14px font will be used. syntax values none choose the size of the font based only on the font-size property. <number> choose the size of the font so that its lowercase letters (as determined by the x-height of the font) are the specified number times the font-size. the number specified should generally be the aspect ratio (ratio of x-height to font size) of the first choice font-family. this means that the first-choice font, when available, will appear the same size in browsers, whether or not they support font-size-adjust. 0 yields text of zero height (hidden text). formal ...
gap (grid-gap) - CSS: Cascading Style Sheets
Web › CSS › gap
ithub.com/mdn/interactive-examples and send us a pull request. css grid layout initially defined the grid-gap property. this prefixed property is being replaced by gap. however, in order to support browsers that implemented grid-gap and not gap for grid, you will need to use the prefixed property as in the interactive example above. ...
...d property is being replaced by gap. however, in order to support browsers that implemented grid-gap and not gap for grid, you will need to use the prefixed property as in the interactive example above. syntax /* one <length> value */ gap: 20px; gap: 1em; gap: 3vmin; gap: 0.5cm; /* one <percentage> value */ gap: 16%; gap: 100%; /* two <length> values */ gap: 20px 10px; gap: 1em 0.5em; gap: 3vmin 2vmax; gap: 0.5cm 2mm; /* one or two <percentage> values */ gap: 16% 100%; gap: 21px 82%; /* calc() values */ gap: calc(10% + 20px); gap: calc(20px + 10%) calc(10% - 5px); /* global values */ gap: inherit; gap: initial; gap: unset; this property is specified as a value for <'row-gap'> followed optionally by a value for <'column-gap'>. if <'column-gap'> is omitted, it’s set to the same valu...
image-rendering - CSS: Cascading Style Sheets
the image-rendering css property sets an image scaling algorithm. the property applies to an element itself, to any images set in its other properties, and to its descendants. the user agent will scale an image when the page author specifies dimensions other than its natural size. scaling may also occur due to user interaction (zooming). 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. this property has no effect on non-scaled images. syntax /* keyword values */ image-rendering: auto; image-rendering: crisp-edges; image-rendering: pixelated; /* global values */ image-rendering: inherit; image-rendering: initial; image-renderi...
...g algorithms such as 2×sai and hqx-family algorithms. this value is intended for pixel-art images, such as in browser games. pixelated when scaling the image up, the nearest-neighbor algorithm must be used, so that the image appears to be composed of large pixels. when scaling down, this is the same as auto. note: the values optimizequality and optimizespeed present in an early draft (and coming from its svg counterpart image-rendering) are defined as synonyms for the smooth and pixelated values respectively. formal definition initial valueautoapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax auto | crisp-edges | pixelated examples setting image scaling algorithms in practical use, the pixelated and crisp-edges rules can be combined ...
<integer> - CSS: Cascading Style Sheets
Web › CSS › integer
e <integer> data type consists of one or several decimal digits, 0 through 9 inclusive, optionally preceded by a single + or - sign. there is no unit associated with integers. note: there is no official range of valid <integer> values. opera 12.1 supports values up to 215-1, ie up to 220-1, and other browsers even higher. during the css3 values cycle there was a lot of discussion about setting a minimum range to support: the latest decision, in april 2012 during the lc phase, was [-227-1; 227-1], but other values like 224-1 and 230-1 were also proposed. however, the latest spec doesn't specify a range anymore. interpolation when animated, values of the <integer> data type are interpolated using discrete, whole steps. the calculation is done as if they were real, floating-point numbers; the...
...27-1], but other values like 224-1 and 230-1 were also proposed. however, the latest spec doesn't specify a range anymore. interpolation when animated, values of the <integer> data type are interpolated using discrete, whole steps. the calculation is done as if they were real, floating-point numbers; the discrete value is obtained using the floor function. the speed of the interpolation is determined by the timing function associated with the animation. examples valid integers 12 positive integer (without a leading + sign) +123 positive integer (with a leading + sign) -456 negative integer 0 zero +0 zero, with a leading + -0 zero, with a leading - invalid integers 12.0 this is a <number>, not an <integer>, though it represents ...
line-height - CSS: Cascading Style Sheets
on non-replaced inline elements, it specifies the height that is used to calculate line box height. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...produce unexpected results (see example below). <percentage> relative to the font size of the element itself. the computed value is this <percentage> multiplied by the element's computed font size. percentage values may produce unexpected results (see the second example below). -moz-block-height sets the line height to the content height of the current block. accessibility concerns use a minimum value of 1.5 for line-height for main paragraph content. this will help people experiencing low vision conditions, as well as people with cognitive concerns such as dyslexia. if the page is zoomed to increase the text size, using a unitless value ensures that the line height will scale proportionately. w3c understanding wcag 2.1 formal definition initial valuenormalapplies toall elements. ...
mask-border-mode - CSS: Cascading Style Sheets
the mask-border-mode css property specifies the blending mode used in a mask border. syntax /* keyword values */ mask-border-mode: luminance; mask-border-mode: alpha; /* global values */ mask-border-mode: inherit; mask-border-mode: initial; mask-border-mode: unset; values luminance the luminance values of the mask border image are used as the mask values. alpha the alpha values of the mask border image are used as the mask values. formal definition initial valuealphaapplies toall elements; in svg, it applies to container elements excluding the defs element and all graphics elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax luminance | alpha examples basic usage this property doesn't yet seem to have support anywhere. when browsers support it,...
...aluealphaapplies toall elements; in svg, it applies to container elements excluding the defs element and all graphics elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax luminance | alpha examples basic usage this property doesn't yet seem to have support anywhere. when browsers support it, it will specify the type of blending mode used for the mask border — luminance or alpha: mask-border-mode: luminance; mask-border-mode: alpha; specifications specification status comment css masking module level 1the definition of 'mask-border-mode' in that specification. candidate recommendation initial definition ...
mask-size - CSS: Cascading Style Sheets
Web › CSS › mask-size
dth and the second sets height. each value can be a <length>, a <percentage>, or auto. values <length> a <length> value scales the mask image to the specified length in the corresponding dimension. negative lengths are not allowed. <percentage> a <percentage> value scales the mask image in the corresponding dimension to the specified percentage of the mask positioning area, which is determined by the value of mask-origin. the mask positioning area is, by default, the area containing the content of the box and its padding; the area may also be changed to just the content or to the area containing borders, padding and content. negative percentages are not allowed. auto a keyword that scales the mask image in the corresponding directions in order to maintain its intrinsic proportion. ...
...or auto auto: if the image has both intrinsic dimensions, it is rendered at that size. if it has no intrinsic dimensions and no intrinsic proportion, it is rendered at the size of the mask positioning area. if it has no dimensions but has a proportion, it's rendered as if contain had been specified instead. if the image has one intrinsic dimension and a proportion, it's rendered at the size determined by that one dimension and the proportion. 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...
orphans - CSS: Cascading Style Sheets
Web › CSS › orphans
the orphans css property sets the minimum number of lines in a block container that must be shown at the bottom of a page, region, or column. /* <integer> values */ orphans: 2; orphans: 3; /* global values */ orphans: inherit; orphans: initial; orphans: unset; in typography, an orphan is the first line of a paragraph that appears alone at the bottom of a page. (the paragraph continues on a following page.) syntax values <integer> the minimum number of lines that can stay by themselves at the bottom of a fragment before a fragmentation break. the value must be positive. ...
...it is used to demonstrate how orphans work.</p> <p>this is the third paragraph. ...
perspective - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax /* keyword value */ perspective: none; /* <length> values */ perspective: 20px; perspective: 3.5em; /* global values */ perspective: inherit; perspective: initial; perspective: unset; values none indicates that no perspective transform is to be applied. <length> a <length> giving the distance from the user to the z=0 plane. ...
...perspective transform is to be applied. <length> a <length> giving the distance from the user to the z=0 plane. it is used to apply a perspective transform to the element and its content. if the value is 0 or a negative number, no perspective transform is applied. description each 3d element with z>0 becomes larger; each 3d-element with z<0 becomes smaller. the strength of the effect is determined by the value of this property. the parts of the 3d elements that are behind the user — i.e. their z-axis coordinates are greater than the value of the perspective css property — are not drawn. 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 n...
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. if omitted, the default value is center, meaing the gradient will be centered, . <angular-color-stop> a color-stop's <color> value, followed by one or two optional stop positions, (an <angle> along the gradient's circumference axis). the last color stop minus the first color-stop angle defines the size of the repeating gradient. <color-hint> th color-hint is an interpolation hint defining how the gradient progresses between adjacent color stops. the length defines at which point between two color stops the gradient color should reach the midpoint of the color transition. if omitted, the midpoint of the color transition is the midpoint between two ...
...60 degrees, but this is not in the specification. radial and conic gradient syntax provides for positioning the center of the gradient anywhere within, or even outside, the image. the values for the position are similar to the syntax for 2-value background-position. the gradient arc is part of the circumference of the gradient. 0 degress is north, or 12:00pm. the colors of the gradient are determined by the angled color stops, their starting points, ending points, and, in between, and optional angled color-stop points. the transitions between colors can be altered with color hints between adjacent colors' color stops. customizing gradients by adding more angled color-stop points on the gradient arc, you can create a highly customized transition between multiple colors. a color-stop's posi...
scroll-margin - CSS: Cascading Style Sheets
: 10px; scroll-margin: 1em .5em 1em 1em; /* global values */ scroll-margin: inherit; scroll-margin: initial; scroll-margin: unset; values <length> an outset from the corresponding edge of the scroll container. description you can see the effect of scroll-margin by scrolling to a point partway between two of the "pages" of the example's content. ...
...ffect of scroll-margin by scrolling to a point partway between two of the "pages" of the example's content. the value specified for scroll-margin determines how much of the page that's primarily outside the snapport should remain visible. thus, the scroll-margin values represent outsets defining the scroll snap area that is used for snapping this box to the snapport. the scroll snap area is determined by taking the transformed border box, finding its rectangular bounding box (axis-aligned in the scroll container’s coordinate space), then adding the specified outsets. formal definition initial value0applies toall elementsinheritednocomputed valueas specifiedanimation typeby computed value type formal syntax <length>{1,4} examples simple demonstration this example implements something...
shape-outside - CSS: Cascading Style Sheets
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. the float area determines the shape around which inline content (float elements) wrap. values none the float area is unaffected. inline content wraps around the element's margin box, like usual. <shape-box> the float area is computed according to the shape of a float element's edges (as defined by the css box model). this can be margin-box, border-box, padding-box, or content-box. the shape includes any curvature...
...area is computed according to the shape of a float element's edges (as defined by the css box model). this can be margin-box, border-box, padding-box, or content-box. the shape includes any curvature created by the border-radius property (behavior which is similar to background-clip). margin-box defines the shape enclosed by the outside margin edge. the corner radii of this shape are determined by the corresponding border-radius and margin values. if the border-radius / margin ratio is 1 or more, then the margin box corner radius is border-radius + margin. if the ratio is less than 1, then the margin box corner radius is border-radius + (margin * (1 + (ratio-1)^3)). border-box defines the shape enclosed by the outside border edge. the shape follows the normal border radius shap...
text-size-adjust - CSS: Cascading Style Sheets
s the text inflation algorithm used on some smartphones and tablets. other browsers will ignore this property. /* keyword values */ text-size-adjust: none; text-size-adjust: auto; /* <percentage> value */ text-size-adjust: 80%; /* global values */ text-size-adjust: inherit; text-size-adjust: initial; text-size-adjust: unset; because many websites have not been developed with small devices in mind, mobile browsers differ from desktop browsers in the way they render web pages. 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. to map the extra-wide layout back to the original device size, they either show only part of the whole render or scale the viewport down to fit. since text that has been s...
...mobile screen may be very small, many mobile browsers apply a text inflation algorithm to enlarge the text to make it more readable. when an element containing text uses 100% of the screen's width, the algorithm increases its text size, but without modifying the layout. the text-size-adjust property allows web authors to disable or modify this behavior, as web pages designed with small screens in mind do not need it. syntax the text-size-adjust property is specified as none, auto, or a <percentage>. values none disables the browser's inflation algorithm. auto enables the browser's inflation algorithm. this value is used to cancel a none value previously set with css. <percentage> enables the browser's inflation algorithm, specifying a percentage value with which to increase the fon...
widows - CSS: Cascading Style Sheets
Web › CSS › widows
the value must be positive. ...
...imum number of lines in a block container that must be shown at the top of a page, region, or column. /* <integer> values */ widows: 2; widows: 3; /* global values */ widows: inherit; widows: initial; widows: unset; in typography, a widow is the last line of a paragraph that appears alone at the top of a page. (the paragraph is continued from a prior page.) syntax values <integer> the minimum number of lines that can stay by themselves at the top of a new fragment after a fragmentation break. the value must be positive. formal definition initial value2applies toblock container elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax <integer> examples controlling column widows html <div> <p>this is the first paragraph containing some text.</p> ...
WAI ARIA Live Regions/API Support - Developer guides
aria-relevant on ancestor element container-busy "true" | "false" | "error" "false" the current changes are not yet complete. a state change event for the a11y api's busy state will be fired on the container object currently marked as busy, once it is no longer busy. this is especially important in...
...e "container-" prefix is so named because the attribute describes what the final computed property of similar name is for that node. this means that the at does not need to traverse up the parent chain to get this information. at this time, for properties where the container-[name] attribute has not been set, the at must have code to fall back on the default value as defined in the w3c spec. determining if event was from user input all events will now provide information about whether the event was caused by user input, or was something that the web page caused. this information is retrieved differently on each platform, because some platforms use asynchronous events. in iaccessible2, this is retrieved from the object attribute "event-from-input", which will be set to "true" or "false". if it...
Ajax - Developer guides
Web › Guide › AJAX
to anyone who has used xmlhttprequest, but this api provides a more powerful and flexible feature set. server-sent events traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server. with server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page. these incoming messages can be treated as events + data inside the web page. see also: using server-sent events. pure-ajax navigation example this article provides a working (minimalist) example of a pure-ajax website composed only of three pages. sending and receiving binary data the responsetype property of the xmlhttprequest object can be set to change the expected response type from the server. possibl...
... parse an xml document from a string, a file or via javascript and how to serialize xml documents to strings, javascript object trees (jxon) or files. xpath xpath stands for xml path language, it uses a non-xml syntax that provides a flexible way of addressing (pointing to) different parts of an xml document. as well as this, it can also be used to test addressed nodes within a document to determine whether they match a pattern or not. filereader api the filereader api 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 dr...
Guide to Web APIs - Developer guides
Web › Guide › API
e you'll find a complete list of all of the apis provided by the full web technology stack. ...
...ential management apiddomeencoding apiencrypted media extensionsffetch apifile system api frame timing apifullscreen apiggamepad api geolocation apihhtml drag and drop apihigh resolution timehistory apiiimage capture apiindexeddbintersection observer apillong tasks api mmedia capabilities api media capture and streamsmedia session apimedia source extensions mediastream recordingnnavigation timingnetwork information api ppage visibility apipayment request apiperformance apiperformance timeline apipermissions apipointer eventspointer lock apiproximity events push api rresize observer apiresource timing apisserver sent eventsservice workers apistoragestorage access apistreams ttouch eventsuurl apivvibration apivisual viewport wweb animationsweb audio apiweb authentication apiweb crypto...
Adding captions and subtitles to HTML5 video - Developer guides
ded a new button to control the subtitles menu that we will build. ...
... no image is used for the captions button, so it is simply styled as: .controls button[data-state="subtitles"] { height:85%; text-indent:0; font-size:16px; font-size:1rem; font-weight:bold; color:#666; background:#000; border-radius:2px; } there are also other css c...
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. this follow-up article looks at how to style this custom player, including making it responsive. the example in action you can find the code for the updated, styled example on github, and view it live. preliminary modifications from the original example this section summarises the modifications that were made to the original video player example to make the styling task easier, before the bulk of the work was started. html markup there are a few changes that were made to the html markup shown in the previous article. the custom video controls and <progress> element are now contained within <div> elements, rather than residing in...
... <div> elements, rather than residing inside unordered list items. ...
DOM onevent handlers - Developer guides
ers except onerror. event, source, lineno, colno, and error for the onerror event handler. note that the event parameter actually contains the error message as a string. when the event handler is invoked, the this keyword inside the handler is set to the dom element on which the handler is registered. for more details, see the this keyword documentation. ...
...m element on which the handler is registered. for more details, see the this keyword documentation. the return value from the handler determines if the event is canceled. the specific handling of the return value depends on the kind of event; for details, see "the event handler processing algorithm" in the html specification. when the event handler is invoked tbd (non-capturing listener) terminology the term event handler may refer to: any function or object that is registered to be notified of events or more specifically, to the mechanism of registering event listeners via on… attributes in html or properties in web apis, such as <button onclick="alert(this)"> or window.onload = function() { … }. when discussing the various methods of listening to events: event listener r...
Media events - Developer guides
media is playing and is restarted from the beginning, this event is sent. canplay sent when enough data is available that the media can be played, at least for a couple of frames. this corresponds to the have_future_data readystate. canplaythrough sent when the readystate changes to have_enough_data, indicating that the entire media can be played without interruption, assuming the download rate remains at least at the current level. it will also be fired when playback is toggled between paused and playing. note: manually setting the currenttime will eventually fire a canplaythrough event in firefox. other browsers might not fire this event. durationchange the metadata has loaded or changed, indicating a change in duration of the media. this is sent, for e...
...t the current amount of the media that has been downloaded is available in the media element's buffered attribute. ratechange sent when the playback speed changes. seeked sent when a seek operation completes. seeking sent when a seek operation begins. stalled sent when the user agent is trying to fetch media data, but data is unexpectedly not forthcoming. suspend sent when loading of the media is suspended; this may happen either because the download has completed or because it has been paused for any other reason. timeupdate the time indicated by the element's currenttime attribute has changed. volumechange sent when the audio volume changes (both when the volume is set and when the muted attribute is changed...
Overview of events and handlers - Developer guides
web browsers can handle. events and event handling provide a core technique in javascript for reacting to incidents occurring when a browser accesses a web page, including events from preparing a web page for display, from interacting with the content of the web page, relating to the device on which the browser is running, and from many other causes such as media stream playback or animation timing. events and event handling become central to web programming with the addition of the language to browsers, accompanying a switch in the rendering architecture of browsers from fetch and load page rendering to event driven, reflow based, page rendering. initially, browsers wait, until they receive all of the resources associated with a page, to parse, process, draw, and present the page to the ...
... be partially rendered even when the browser has not finished retrieving all resources; this approach also allows for event driven actions, which javascript leverages. (the talk is available from several sources, including this one.) currently, all execution environments for javascript code use events and event handling. the event design pattern the event system, at its core, is simply a programming design pattern. the pattern starts with an agreement over a kind of event and: the name string used for the event, the type of the data structure used to represent the key properties of that event, and the javascript object which will 'emit' that event. the pattern is implemented by defining a javascript function which takes as an argument the data structure which was agreed upon, and ...
Event developer guide - Developer guides
Web › Guide › Events
the overview page provides an introduction to the design pattern and a summary of the types of incidents which are defined and reacted to by modern web browsers. the custom events page describes how the event code design pattern can be used in custom code to define new event types emitted by user objects, register listener functions to handle those events, and trigger the events in user code. ...
...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 ...
Mobile-friendliness - Developer guides
entation) “make websites that work well on a variety of screen sizes.” these days, users can access the web on devices in a wide range of form factors, including phones, tablets, and ereaders. needless to say, a fixed-width, three-column layout filled with complex javascript animations and mouse-over effects is not going to look or feel quite right on a phone with a 2-inch-wide screen and a diminutive processor. a slimmed-down, linearized page layout with elements sized for a touchscreen would be much more appropriate. that’s why this first goal is all about presenting your content in a way that makes life easy for users on mobile device. goal #2 (content) “adjust your content for mobile users.” think about what your users want to do at your site if they are on a phone. a great exam...
...eless data connection can still be pretty painful. this makes it more essential than ever to practice good performance practices, only sending the user the bits they will actually need. know your audience while not strictly a part of the definition of being mobile friendly, defining who your target audience is makes these goals much more concrete. for example, it is absolutely critical to keep in mind which browsers and devices you will target when picking a mobile strategy. if your audience is full of early-adopters, you can focus on tablets and smartphones with standards-friendly browsers. on the other hand, if many of your site’s users are on devices with less capable browsers, that may eliminate certain strategies as viable options. approaches to mobile web development the following app...
User input and controls - Developer guides
fullscreen api helps you in displaying your app in fullscreen mode. using features such as contenteditable elements you can implement fast rich-text editors and with drag&drop let users moving elements inside your app. when screen orientation matters for your application, through the screen orientation api you can read the screen orientation state and perform other actions. you should always be mindful of keyboard accessibility where appropriate — many web users only use keyboard to navigate web sites and apps, and locking them out of your functionality is a bad idea. the following is a set of recommendations and best practices for using such tools in open web apps. decide what input mechanism you’re using keyboard keyboard input can be controlled by your app. for example if you wa...
...reen.unlockorientation method removes all the previous screen locks that have been set. note: more information about the screen orientation api can be found in managing screen orientation. fullscreen you might need to present an element of your application (such as a <video>, for example) in fullscreen mode. you can achieve this by calling element.requestfullscreen() on that element. ...
Writing forward-compatible websites - Developer guides
on them). as browsers converge behavior, they both add features and remove them. they also fix bugs. all three of these have happened in the past and will happen again. so don't sniff for one feature or object and then assume that, because it exists or doesn't exist, some other feature or object must also exist or not exist. don't ua-sniff this is really a particularly common instance of assuming that one feature (the presence of a particular substring in the user agent (ua) string) implies something about the presence or absence of other features. if you have to ua-sniff, only sniff for past browser versions if you have to resort to ua sniffing, only use it to target past browser versions of particular browsers. first, have a default code path that runs in unknown browsers and in the ...
...th 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. browser-specific features and prefixes don't target hacks at current or future versions of browsers this is also a common instance of assuming that present correlation between bugs implies future correlation between bugs. targeting hacks at old versions of browsers whose current versions no longer have the bug you're relying on for your hack is ok; once a browser has fixed bug x, you can know for certain that all releases that had bug x also had bug y and use the presence of bug x to target workarounds for bug y. for the purpose of th...
HTML attribute: pattern - HTML: Hypertext Markup Language
compassing all three components of the phone number, expecting 3-digits, 3-digits and 4-digits respectively, as defined by the pattern attribute set on each. if the values are too long or too short, or contain characters that aren't digits, the patternmismatch will be true. when true, the element matches the :invalid css pseudo-classes. input:invalid { border: red solid 3px; } had we used minlength and maxlength attributes instead, we may have seen validitystate.toolong or validitystate.tooshort being true. 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). the ...
...if used, must describe the pattern. relying on the title attribute for the visual display of text content is generally discouraged as many user agents do not expose the attribute in an accessible manner. some browsers show a tooltip when an element with a title is hovered, but that leaves out keyboard-only and touch-only users. this is one of the several reasons you must include information informing users how to fill out the the control to match the requirements. while titles are used by some browsers to populate error messaging, because browsers sometimes also show the title as text on hover, it therefore shows in non-error situations, so be careful not to word titles as if an error has occurred. specifications specification status comment html living standardthe...
HTML attribute: rel - HTML: Hypertext Markup Language
Web › HTML › Attributes › rel
er proceeds to the next-most appropriate, and so on. note: apple's ios does not use this link type, nor the sizes attribute, like others mobile browsers do, to select a webpage icon for web clip or a start-up placeholder. instead it uses the non-standard apple-touch-icon and apple-touch-startup-image respectively. the shortcut link type is often seen before icon, but this link type is non-conforming, ignored and web authors must not use it anymore. alternate indicates an alternate representation of the current document. valid for link, a, and area, the meaning depends on the values of the other attributes. with the stylesheet keyword on a <link>, it creates an alternate stylesheet. <!-- a persistent style sheet --> <link rel="stylesheet" href="default.css"> <!-- alternate style s...
... proceeds to the next-most appropriate, and so on. note: apple's ios does not use this link type, nor the sizes attribute, like others mobile browsers do, to select a webpage icon for web clip or a start-up placeholder. instead it uses the non-standard apple-touch-icon and apple-touch-startup-image respectively. the shortcut link type is often seen before icon, but this link type is non-conforming, ignored and web authors must not use it anymore. license valid on the <a>, <area>, <form>, <link> elements, the license value indicates that the hyperlink leads to a document describing the licensing information; that the main content of the current document is covered by the copyright license described by the referenced document. if not inside the <head> element, the standard doesn't dis...
HTML attribute reference - HTML: Hypertext Markup Language
the upper bound of the lower range. manifest <html> specifies the url of the document's cache manifest. note: this attribute is obsolete, use <link rel="manifest"> instead. max <input>, <meter>, <progress> indicates the maximum value allowed. maxlength <input>, <textarea> defines the maximum number of characters allowed in the element. ...
...ifest <html> specifies the url of the document's cache manifest. note: this attribute is obsolete, use <link rel="manifest"> instead. max <input>, <meter>, <progress> indicates the maximum value allowed. maxlength <input>, <textarea> defines the maximum number of characters allowed in the element. minlength <input>, <textarea> defines the minimum number of characters allowed in the element. media <a>, <area>, <link>, <source>, <style> specifies a hint of the media for which the linked resource was designed. method <form> defines which http method to use when submitting the form. can be get (default) or post. min <input>, <meter> indicates the minimum value allowed. multiple <inp...
<bgsound>: The Background Sound element (obsolete) - HTML: Hypertext Markup Language
Web › HTML › Element › bgsound
the internet explorer only html background sound element (<bgsound>) sets up a sound file to play in the background while the page is used; use <audio> instead. do not use this! in order to embed audio in a web page, you should be using the <audio> element. attributes balance this attribute defines a number between -10,000 and +10,000 that determines how the volume will be divided between the speakers. ...
... example <bgsound src="sound1.mid"> <bgsound src="sound2.au" loop="infinite"> usage notes historically, the <embed> element could be used with audio player plug-ins to play audio in the background in most browsers. ...
<button>: The Button element - HTML: Hypertext Markup Language
Web › HTML › Element › button
understanding wcag, guideline 4.1 explanations understanding success criterion 4.1.2 | w3c understanding wcag 2.0 size and proximity size interactive elements such as buttons should provide an area large enough that it is easy to activate them. 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. a minimum interactive size of 44×44 css pixels is recommended. understanding success criterion 2.5.5: target size | w3c understanding wcag 2.1 target size and 2.5.5 | adrian roselli quick test: large touch targets - the a11y project proximity large amounts of interactive content — including buttons — placed in close visual proximity to each other should have space separating them. this spa...
...border on a focused button. 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 { }. if overridden, it is important to ensure that the state change when focus is moved to the button is high enough that people experiencing low vision conditions will be able to perceive it. color contrast ratio is determined by comparing the luminosity of the button text and background color values compared to the background the button is placed on. in order to meet current web content accessibility guidelines (wcag), a ratio of 4.5:1 is required for text content and 3:1 for large text. (large text is defined as 18.66px and bold or larger, or 24px or larger.) webaim: color contrast checker mdn understanding wca...
<embed>: The Embed External Content element - HTML: Hypertext Markup Language
Web › HTML › Element › embed
-in. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. note: this topic documents only the element that is defined as part of html5. it does not address earlier, non-standardized implementation of the element. keep in mind that most modern browsers have deprecated and removed support for browser plug-ins, so relying upon <embed> is generally not wise if you want your site to be operable on the average user's browser. content categories flow content, phrasing content, embedded content, interactive content, palpable content. permitted content none, it is an empty element. tag omissi...
...e="video/quicktime" src="movie.mov" width="640" height="480" title="title of my video"> accessibility concerns use the title attribute on an embed element to label its content so that people navigating with assistive technology such as a screen reader can understand what it contains. the title's value should concisely describe the embedded content. without a title, they may not be able to determine what its embedded content is. this context shift can be confusing and time-consuming, especially if the embed element contains interactive content like video or audio. specifications specification status comment html living standardthe definition of '<embed>' in that specification. living standard html5the definition of '<embed>' in that specificatio...
<iframe>: The Inline Frame element - HTML: Hypertext Markup Language
Web › HTML › Element › iframe
l include the path. same-origin: a referrer will be sent for same origin, but cross-origin requests will contain no referrer information. strict-origin: only send the origin of the document as the referrer when the protocol security level stays the same (https→https), but don't send it to a less secure destination (https→http). strict-origin-when-cross-origin: send a full url when performing a same-origin request, only send the origin when the protocol security level stays the same (https→https), and send no header to a less secure destination (https→http). unsafe-url: the referrer will include the origin and the path (but not the fragment, password, or username). this value is unsafe, because it leaks origins and paths from tls-protected resources to insecure origins. sa...
...ult accessibility concerns people navigating with assistive technology such as a screen reader can use the title attribute on an <iframe> to label its content. the title's value should concisely describe the embedded content: <iframe title="wikipedia page for avocados" src="https://en.wikipedia.org/wiki/avocado"></iframe> without this title, they have to navigate into the <iframe> to determine what its embedded content is. 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. specifications specification status comment referrer policythe definition of 'referrerpolicy attribute' in that specification. candidate recommendation added the ref...
<input type="color"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › color
wer-case, it will be stored in lower-case form. the value is never in any other form, and is never empty. note: setting the value to anything that isn't a valid, fully-opaque, rgb color in hexadecimal notation will result in the value being set to #000000. in particular, you can't use css's standardized color names, or any css function syntax, to set the value. this makes sense when you keep in mind that html and css are separate languages and specifications. in addition, colors with an alpha channel are not supported; specifying a color in 9-character hexadecimal notation (e.g. #009900aa) will also result in the color being set to #000000. note: any web browser that doesn't support an input of type color will naturally fall back to the type text. because users can write colors in many d...
...ba()), you'll have to convert them to hexadecimal before setting the value. tracking color changes as is the case with other <input> types, there are two events that can be used to detect changes to the color value: input and change. input is fired on the <input> element every time the color changes. the change event is fired when the user dismisses the color picker. in both cases, you can determine the new value of the element by looking at its value. here's an example that watches changes over time to the color value: colorpicker.addeventlistener("input", updatefirst, false); colorpicker.addeventlistener("change", watchcolorpicker, false); function watchcolorpicker(event) { document.queryselectorall("p").foreach(function(p) { p.style.color = event.target.value; }); } selectin...
<isindex> - HTML: Hypertext Markup Language
Web › HTML › Element › isindex
wser and the server to react to the query. <isindex> is removed html standard. it was deprecated in html 4.01. the same behaviour can be achieved with an html form. all major browsers have now removed <isindex>. attributes like all other html elements, this element accepted the global attributes. prompt this attribute added its value as a prompt for text field. action this attribute determined the server url to which the query was sent. example <head> <isindex prompt="search document..." action="/search"> </head> in past browsers, this would generate, at parse time, a dom tree equivalent to the following html: <form action="/search"> <hr> <label> search document... <input name="isindex"> </label> <hr> </form> history on june 1992, dan connolly would prefer a...
... the current www framework with a specific httpd configuration and defined that some uris mapping create search queries. in 2016, after it was removed from edge and chrome, it was proposed to remove isindex from the standard; this removal was completed the next day, after which safari and firefox also removed support. html reference the html standard classifies it as a obsolete and non-conforming feature. isindex element deprecated in html 4.01 isindex in html 3.2 isindex in html 2.0 as well the description of the behavior in queries and indexes (html 2.0) isindex in html+ ...
<nextid>: The NeXT ID element (Obsolete) - HTML: Hypertext Markup Language
Web › HTML › Element › nextid
<nextid> is an obsolete html element that served to enable the next web designing tool to generate automatic name labels for its anchors. it was generated by that web editing tool automatically and was not to be adjusted or entered by hand. this element has the distinction of being the first element to become one of the "lost tags" by being eliminated from the official public dtd's of the html versions. it is also probably one of the least understood of all of the early html elements. html "0.a" - from the beginning through january 10, 1991 this tag had not been invented as yet, so no examples are found from this period. html "0.c" - from january 23, 1991 though november 23, 1992 this early version of html introduced <nextid> in a non-sgml compliant form that simply used the numeric ...
...marked like this: <h2><a name="z4">first section name</a></h2>. this continues for the next three sections, z5, z6, and z7 (and table of contents entries named z1, z2, and z3), each automatically given anchors with these names. the user then saves and closes the document. next would then add, within the header of the html document, a special tag, <nextid n="z8">, to inform where to continue its naming convention. imagine the web author opens the document for further editing. they want to add a couple new sections after the second section, appending four more sections at the end. when opening the document, the next editor finds and reads this <nextid n="z8"> tag, and now knows to give the first of these new sections the name of z8 in the table of contents, and z14 to the content body. this mig...
<picture>: The Picture element - HTML: Hypertext Markup Language
Web › HTML › Element › picture
<img> element's src attribute is selected. the selected image is then presented in the space occupied by the <img> element. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. to decide which url to load, the user agent examines each <source>'s srcset, media, and type attributes to select a compatible image that best matches the current layout and capabilities of the display device. the <img> element serves two purposes: it describes the size and other attributes of the image and its presentation. it provides a fallback in case none of the offered <source> elements are able to provide a usable image. common use ...
... element change the selection of the image inside <picture>. the media attribute the media attribute specifies a media condition (similar to a media query) that the user agent will evaluate for each <source> element. if the <source>'s media condition evaluates to false, the browser skips it and evaluates the next element inside <picture>. <picture> <source srcset="mdn-logo-wide.png" media="(min-width: 600px)"> <img src="mdn-logo-narrow.png" alt="mdn"> </picture> the srcset attribute the srcset attribute is used to offer list of possible images based on size. it is composed of a comma-separated list of image descriptors. each image descriptor is composed of a url of the image, and either... a width descriptor, followed by a w (such as 300w); or a pixel density descriptor, fol...
<progress>: The Progress Indicator element - HTML: Hypertext Markup Language
Web › HTML › Element › progress
ted by the progress element requires. the max attribute, if present, must have a value greater than 0 and be a valid floating point number. the default value is 1. value this attribute specifies how much of the task that has been completed. it must be a valid floating point number between 0 and max, or between 0 and 1 if max is omitted. ...
...ault value is 1. value this attribute specifies how much of the task that has been completed. it must be a valid floating point number between 0 and max, or between 0 and 1 if max is omitted. if there is no value attribute, the progress bar is indeterminate; this indicates that an activity is ongoing with no indication of how long it is expected to take. note: unlike the <meter> element, the minimum value is always 0, and the min attribute is not allowed for the <progress> element. note: the :indeterminate pseudo-class can be used to match against indeterminate progress bars. to change the progress bar to indeterminate after giving it a value you must remove the value attribute with element.removeattribute('value'). examples <progress value="70" max="100">70 %</progress> result ...
<tbody>: The Table Body element - HTML: Hypertext Markup Language
Web › HTML › Element › tbody
horizontal alignment of each cell content will be handled. possible values are: left, aligning the content to the left of the cell center, centering the content in the cell right, aligning the content to the right of the cell justify, inserting spaces into the textual content so that the content is justified in the cell char, aligning the textual content on a special character with a minimal offset, defined by the char and charoff attributes. if this attribute is not set, the left value is assumed. as this attribute is deprecated, use the css text-align property instead. note: the equivalent text-align property for the align="char" is not implemented in any browsers yet. see the text-align's browser compatibility section for the <string> value. bgcolor the backgro...
... first, the resulting table, so you know what we're building: html the revised html looks like this: <table> <thead> <tr> <th>student id</th> <th>name</th> </tr> </thead> <tbody> <tr> <th colspan="2">computer science</th> </tr> <tr> <td>3741255</td> <td>jones, martha</td> </tr> <tr> <td>4077830</td> <td>pierce, benjamin</td> </tr> <tr> <td>5151701</td> <td>kirk, james</td> </tr> </tbody> <tbody> <tr> <th colspan="2">russian literature</th> </tr> <tr> <td>3971244</td> <td>nim, victor</td> </tr> </tbody> <tbody> <tr> <th colspan="2">astrophysics</th> </tr> <tr> <td>4100332</td> <td>petrov, alexandra</td> </tr> <...
<var>: The Variable element - HTML: Hypertext Markup Language
Web › HTML › Element › var
it's typically presented using an italicized version of the current typeface, although that behavior is browser-dependent. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. content categories flow content, phrasing content, palpable content. permitted content phrasing content. tag omission none, both the starting and ending tag are mandatory. ...
...quation: <var>x</var> = <var>y</var> + 2 </p> the output: overriding the default style using css, you can override the default style for the <var> element. in this example, variable names are rendered using bold courier if it's available, otherwise it falls back to the default monospace font. css var { font: bold 15px "courier", "courier new", monospace; } html <p>the variables <var>minspeed</var> and <var>maxspeed</var> control the minimum and maximum speed of the apparatus in revolutions per minute (rpm).</p> this html uses <var> to enclose the names of two variables. result specifications specification status comment html living standardthe definition of '<var>' in that specification. living standard html5the definition ...
inputmode - HTML: Hypertext Markup Language
editing the element or its contents. it can have the following values: none no virtual keyboard. for when the page implements its own keyboard input control. text (default value) standard input keyboard for the user's current locale. decimal fractional numeric input keyboard containing the digits and decimal separator for the user's locale (typically . or ,). devices may or may not show a minus key (-). numeric numeric input keyboard, but only requires the digits 0–9. devices may or may not show a minus key. tel a telephone keypad input, including the digits 0–9, the asterisk (*), and the pound (#) key. inputs that require a telephone number should typically use <input type="tel">instead. search a virtual keyboard optimized for search input. for instance, the return/submit k...
... optimizations. inputs that require a search query should typically use <input type="search"> instead. email a virtual keyboard optimized for entering email addresses. typically includes the @ character as well as other optimizations. inputs that require email addresses should typically use <input type="email"> instead. url a keypad optimized for entering urls. this may have the / key more prominent, for example. enhanced features could include history access and so on. inputs that require a url should typically use <input type="url"> instead. specifications specification status comment html living standardthe definition of 'inputmode' in that specification. living standard ...
itemscope - HTML: Hypertext Markup Language
</p> <span itemprop="description">this is my grandmother's apple pie recipe. ...
...ng" itemscope itemtype="http://schema.org/aggregaterating"> <span itemprop="ratingvalue">4.0</span> stars based on <span itemprop="reviewcount">35</span> reviews </span> <br> prep time: <time datetime="pt30m" itemprop="preptime">30 min</time><br> cook time: <time datetime="pt1h" itemprop="cooktime">1 hou</time>r<br> total time: <time datetime="pt1h30m" itemprop="totaltime">1 hour 30 min</time><br> yield: <span itemprop="recipeyield">1 9" pie (8 servings)</span><br> <span itemprop="nutrition" itemscope itemtype="http://schema.org/nutritioninformation"> serving size: <span itemprop="servingsize">1 medium slice</span><br> calories per serving: <span itemprop="calories">250 cal</span><br> fat per serving: <span itemprop="fatcontent">12 g</span><br> </span> <p> ...
Evolution of HTTP - HTTP
f the messages exchanged between the server and client. ssl was put on the standards track and eventually became tls, with versions 1.0, 1.1, 1.2, and 1.3 appearing successfully to close vulnerabilities. during the same time, the need for an encrypted transport layer raised: the web left the relative trustiness of a mostly academic network, to a jungle where advertisers, random individuals or criminals compete to get as much private information about people, try to impersonate them or even to replace data transmitted by altered ones. as the applications built over http became more and more powerful, having access to more and more private information like address books, e-mail, or the geographic position of the user, the need to have tls became ubiquitous even outside the e-commerce use case.
...rs) or the content security policy (csp). in addition to these large extensions, numerous other headers have been added, sometimes experimentally only. notable headers are do not track (dnt) header to control privacy, x-frame-options, or upgrade-insecure-requests but many more exist. http/2 – a protocol for greater performance over the years, web pages have become much more complex, even becoming applications in their own right. the amount of visual media displayed, the volume and size of scripts adding interactivity, has also increased: much more data is transmitted over significantly more http requests. http/1.1 connections need requests sent in the correct order. theoretically, several parallel connections could be used (typically between 5 and 8), bringing considerable overhead and ...
MIME types (IANA media types) - HTTP
type) is a standard that indicates the nature and format of a document, file, or assortment of bytes. it is defined and standardized in ietf's rfc 6838. the internet assigned numbers authority (iana) is responsible for all official mime types, and you can find the most up-to-date and complete list at their media types page. important: browsers use the mime type, not the file extension, to determine how to process a url, so it's important that web servers send the correct mime type in the response's content-type header. if this is not correctly configured, browsers are likely to misinterpret the contents of files and sites will not work correctly, and downloaded files may be mishandled. structure of a mime type the simplest mime type consists of a type and a subtype; these are each strin...
... opus the most common audio codecs. audio/ogg an audio file in the ogg container format. vorbis is the most common audio codec used in such a container; however, opus is now supported by ogg as well. video/ogg a video file, possibly with audio, in the ogg container format. theora is the usual video codec used within it; vorbis is the usual audio codec, although opus is becoming more common. application/ogg an audio or video file using the ogg container format. theora is the usual video codec used within it; vorbis is the usual audio codec. multipart/form-data the multipart/form-data type can be used when sending the values of a completed html form from browser to server. as a multipart document format, it consists of different parts, delimited by a...
Access-Control-Max-Age - HTTP
ntained in the access-control-allow-methods and access-control-allow-headers headers) can be cached. header type response header forbidden header name no syntax access-control-max-age: <delta-seconds> directives <delta-seconds> maximum number of seconds the results can be cached. uxp caps this at 24 hours (86400 seconds). ...
...of seconds the results can be cached. uxp caps this at 24 hours (86400 seconds). chromium (prior to v76) caps at 10 minutes (600 seconds). chromium (starting in v76) caps at 2 hours (7200 seconds). chromium also specifies a default value of 5 seconds. a value of -1 will disable caching, requiring a preflight options check for all calls. examples cache results of a preflight request for 10 minutes: access-control-max-age: 600 specifications specification status comment fetchthe definition of 'access-control-max-age' in that specification. living standard initial definition. ...
If-Range - HTTP
Web › HTTP › Headers › If-Range
s. this header can be used either with a last-modified validator, or with an etag, but not with both. the most common use case is to resume a download, to guarantee that the stored resource has not been modified since the last fragment has been received. header type request header forbidden header name no syntax if-range: <day-name>, <day> <month> <year> <hour>:<minute>:<second> gmt if-range: <etag> directives <etag> an entity tag uniquely representing the requested resource. it is a string of ascii characters placed between double quotes (like "675af34563dc-tr34") and may be prefixed by w/ to indicate that the weak comparison algorithm should be used. <day-name> one of "mon", "tue", "wed", "thu", "fri", "sat", or "sun" (case-sensitive). <day> 2 ...
...k comparison algorithm should be used. <day-name> one of "mon", "tue", "wed", "thu", "fri", "sat", or "sun" (case-sensitive). <day> 2 digit day number, e.g. "04" or "23". <month> one of "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" (case sensitive). <year> 4 digit year number, e.g. "1990" or "2016". <hour> 2 digit hour number, e.g. "09" or "23". <minute> 2 digit minute number, e.g. "04" or "59". <second> 2 digit second number, e.g. "04" or "59". gmt greenwich mean time. http dates are always expressed in gmt, never in local time. examples if-range: wed, 21 oct 2015 07:28:00 gmt specifications specification title rfc 7233, section 3.2: if-range hypertext transfer protocol (http/1.1): range requests ...
Referrer-Policy - HTTP
oss-origin (see https://github.com/whatwg/fetch/pull/952), consider using this value (or a stricter one), if possible, when changing the referrer-policy. origin only send the origin of the document as the referrer. for example, a document at https://example.com/page.html will send the referrer https://example.com/. origin-when-cross-origin send the origin, path, and query string when performing a same-origin request, but only send the origin of the document for other cases. same-origin a referrer will be sent for same-site origins, but cross-origin requests will send no referrer information. strict-origin only send the origin of the document as the referrer when the protocol security level stays the same (https→https), but don't send it to a less secure destination (https→http)...
...me-origin a referrer will be sent for same-site origins, but cross-origin requests will send no referrer information. strict-origin only send the origin of the document as the referrer when the protocol security level stays the same (https→https), but don't send it to a less secure destination (https→http). strict-origin-when-cross-origin send the origin, path, and querystring when performing a same-origin request, only send the origin when the protocol security level stays the same while performing a cross-origin request (https→https), and send no header to any less-secure destinations (https→http). unsafe-url send the origin, path, and query string when performing any request, regardless of security. this policy will leak potentially-private information from https resource...
Tk - HTTP
Web › HTTP › Headers › Tk
k: ! (under construction) tk: ? (dynamic) tk: g (gateway or multiple parties) tk: n (not tracking) tk: t (tracking) tk: c (tracking with consent) tk: p (potential consent) tk: d (disregarding dnt) tk: u (updated) directives ! under construction. the origin server is currently testing its communication of tracking status. ? dynamic. the origin server needs more information to determine tracking status. g gateway or multiple parties. the server is acting as a gateway to an exchange involving multiple parties. n not tracking. t tracking. c tracking with consent. the origin server believes it has received prior consent for tracking this user, user agent, or device. p potential consent. the origin server does not know, in real-time, whether it has received prior consent ...
... n not tracking. t tracking. c tracking with consent. the origin server believes it has received prior consent for tracking this user, user agent, or device. p potential consent. the origin server does not know, in real-time, whether it has received prior consent for tracking this user, user agent, or device, but promises not to use or share any dnt:1 data until such consent has been determined, and further promises to delete or permanently de-identify within 48 hours any dnt:1 data received for which such consent has not been received. d disregarding dnt. the origin server is unable or unwilling to respect a tracking preference received from the requesting user agent. u updated. the request resulted in a potential change to the tracking status applicable to this user, user agent,...
Transfer-Encoding - HTTP
transfer-encoding is a hop-by-hop header, that is applied to a message between two nodes, not to a resource itself. each segment of a multi-node connection can use different transfer-encoding values. ...
...ding: identity // several values can be listed, separated by a comma transfer-encoding: gzip, chunked directives chunked data is sent in a series of chunks. the content-length header is omitted in this case and at the beginning of each chunk you need to add the length of the current chunk in hexadecimal format, followed by '\r\n' and then the chunk itself, followed by another '\r\n'. the terminating chunk is a regular chunk, with the exception that its length is zero. it is followed by the trailer, which consists of a (possibly empty) sequence of entity header fields. compress a format using the lempel-ziv-welch (lzw) algorithm. the value name was taken from the unix compress program, which implemented this algorithm. like the compress program, which has disappeared from most unix di...
HTTP Messages - HTTP
Web › HTTP › Messages
-readable message is now divided up into http frames, providing optimization and performance improvements. web developers, or webmasters, rarely craft these textual http messages themselves: software, a web browser, proxy, or web server, perform this action. they provide http messages through config files (for proxies or servers), apis (for browsers), or other interfaces. the http/2 binary framing mechanism has been designed to not require any alteration of the apis or config files applied: it is broadly transparent to the user. http requests, and responses, share similar structure and are composed of: a start-line describing the requests to be implemented, or its status of whether successful or a failure. this start-line is always a single line. an optional set of http headers speci...
...pers. this is an additional step in http/2, between http/1.1 messages and the underlying transport protocol. no changes are needed in the apis used by web developers to utilize http frames; when available in both the browser and the server, http/2 is switched on and used. conclusion http messages are the key in using http; their structure is simple, and they are highly extensible. the http/2 framing mechanism adds a new intermediate layer between the http/1.x syntax and the underlying transport protocol, without fundamentally modifying it: building upon proven mechanisms. ...
An overview of HTTP - HTTP
Web › HTTP › Overview
sarily a single machine, but several server software instances can be hosted on the same machine. with http/1.1 and the host header, they may even share the same ip address. proxies between the web browser and the server, numerous computers and machines relay the http messages. due to the layered structure of the web stack, most of these operate at the transport, network or physical levels, becoming transparent at the http layer and potentially making a significant impact on performance. those operating at the application layers are generally called proxies. these can be transparent, forwarding on the requests they receive without altering them in any way, or non-transparent, in which case they will change the request in some way before passing it along to the server. proxies may perform nu...
...ookies are added to the workflow, allowing session creation on each http request to share the same context, or the same state. http and connections a connection is controlled at the transport layer, and therefore fundamentally out of scope for http. though http doesn't require the underlying transport protocol to be connection-based; only requiring it to be reliable, or not lose messages (so at minimum presenting an error). among the two most common transport protocols on the internet, tcp is reliable and udp isn't. http therefore relies on the tcp standard, which is connection-based. before a client and server can exchange an http request/response pair, they must establish a tcp connection, a process which requires several round-trips. the default behavior of http/1.0 is to open a separat...
Protocol upgrade mechanism - HTTP
decides to upgrade the connection, it sends back a 101 switching protocols response status with an upgrade header that specifies the protocol(s) being switched to. if it does not (or cannot) upgrade the connection, it ignores the upgrade header and sends back a regular response (for example, a 200 ok). right after sending the 101 status code, the server can begin speaking the new protocol, performing any additional protocol-specific handshakes as necessary. effectively, the connection becomes a two-way pipe as soon as the upgraded response is complete, and the request that initiated the upgrade can be completed over the new protocol. common uses for this mechanism here we look at the most common use cases for the upgrade header. upgrading to a websocket connection by far, the most common...
...is complete, and the request that initiated the upgrade can be completed over the new protocol. common uses for this mechanism here we look at the most common use cases for the upgrade header. upgrading to a websocket connection by far, the most common use case for upgrading an http connection is to use websockets, which are always implemented by upgrading an http or https connection. keep in mind that if you're opening a new connection using the websocket api, or any library that does websockets, most or all of this is done for you. for example, opening a websocket connection is as simple as: websocket = new websocket("ws://destination.server.ext", "optionalprotocol"); the websocket() constructor does all the work of creating an initial http/1.1 connection then handling the handshaking...
HTTP range requests - HTTP
the if-range http request header makes a range request conditional: if the condition is fulfilled, the range request will be issued and the server sends back a 206 partial content answer with the appropriate body. if the condition is not fulfilled,...
...equests, the 200 ok status is sent back from a server. comparison to chunked transfer-encoding the transfer-encoding header allows chunked encoding, which is useful when larger amounts of data are sent to the client and the total size of the response is not known until the request has been fully processed. the server sends data to the client straight away without buffering the response or determining the exact length, which leads to improved latency. range requests and chunking are compatible and can be used with or without each other. ...
HTTP
Web › HTTP
less common requests like options, delete, or trace. http status response codes http response codes indicate whether a specific http request has been successfully completed. responses are grouped in five classes: informational responses, successful responses, redirections, client errors, and servers errors. ...
... redbot tools to check your cache-related headers how browsers work a very comprehensive article on browser internals and request flow through http protocol. a must-read for any web developer. ...
About JavaScript - JavaScript
what is javascript? javascript® (often shortened to js) is a lightweight, interpreted, object-oriented language with first-class functions, and is best known as the scripting language for web pages, but it's used in many non-browser environments as well. it is a prototype-based, multi-paradigm scripting language that is dynamic, and supports object-oriented, imperative, and functional programming styles. javascript runs on the client side of the web, which can be used to design / program how the web pages behave on the occurrence of an event. javascript is an easy to learn and also powerful scripting language, widely used for controlling web page behavior. contrary to popular misconception, javascript is not "interpreted java". in a nutshell, javascript is a dynamic scripting language su...
...nt (or prototype) for creating similar objects. javascript's dynamic capabilities include runtime object construction, variable parameter lists, function variables, dynamic script creation (via eval), object introspection (via for ... in), and source code recovery (javascript programs can decompile function bodies back into their source text). for a more in depth discussion of javascript programming follow the javascript resources links below. what javascript implementations are available? the mozilla project provides two javascript implementations. the first ever javascript was created by brendan eich at netscape, and has since been updated to conform to ecma-262 edition 5 and later versions. this engine, code named spidermonkey, is implemented in c/c++. the rhino engine, created primari...
Concurrency model and the event loop - JavaScript
s, messages are added anytime an event occurs and there is an event listener attached to it. if there is no listener, the event is lost. so a click on an element with a click event handler will add a message—likewise with any other event. the function settimeout is called with 2 arguments: a message to add to the queue, and a time value (optional; defaults to 0). the time value represents the (minimum) delay after which the message will actually be pushed into the queue. if there is no other message in the queue, and the stack is empty, the message is processed right after the delay. however, if there are messages, the settimeout message will have to wait for other messages to be processed. for this reason, the second argument indicates a minimum time—not a guaranteed time. here is an...
...ack will fire-off after zero milliseconds. calling settimeout with a delay of 0 (zero) milliseconds doesn't execute the callback function after the given interval. the execution depends on the number of waiting tasks in the queue. in the example below, the message ''this is just a message'' will be written to the console before the message in the callback gets processed, because the delay is the minimum time required for the runtime to process the request (not a guaranteed time). basically, the settimeout needs to wait for all the code for queued messages to complete even though you specified a particular time limit for your settimeout. (function() { console.log('this is the start'); settimeout(function cb() { console.log('callback 1: this is a msg from call back'); }); // has ...
Regular expressions - JavaScript
ally (actually searching for a "*", for instance), you must escape it by putting a backslash in front of it. for instance, to search for "a" followed by "*" followed by "b", you'd use /a\*b/ — the backslash "escapes" the "*", making it literal instead of special. similarly, if you're writing a regular expression literal and need to match a slash ("/"), you need to escape that (otherwise, it terminates the pattern). for instance, to search for the string "/example/" followed by one or more alphabetic characters, you'd use /\/example\/[a-z]+/i—the backslashes before each slash make them literal. to match a literal backslash, you need to escape the backslash. for instance, to match the string "c:\" where "c" can be any letter, you'd use /[a-z]:\\/ — the first backslash escapes the one af...
... ranges, quantifiers, unicode property escapes using special characters to verify input in the following example, the user is expected to enter a phone number. when the user presses the "check" button, the script checks the validity of the number. if the number is valid (matches the character sequence specified by the regular expression), the script shows a message thanking the user and confirming the number. if the number is invalid, the script informs the user that the phone number is not valid. within non-capturing parentheses (?: , the regular expression looks for three numeric characters \d{3} or | a left parenthesis \( followed by three digits \d{3}, followed by a close parenthesis \), (end non-capturing parenthesis )), followed by one dash, forward slash, or decimal point and when...
Text formatting - JavaScript
ect is useful for formatting date and time. the following formats a date for english as used in the united states. (the result is different in another time zone.) const msperday = 24 * 60 * 60 * 1000; // july 17, 2014 00:00:00 utc. const july172014 = new date(msperday * (44 * 365 + 11 + 197)); const options = { year: '2-digit', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', timezonename: 'short' }; const americandatetime = new intl.datetimeformat('en-us', options).format; console.log(americandatetime(july172014)); // 07/16/14, 5:00 pm pdt number formatting the numberformat object is useful for formatting numbers, for example currencies. const gasprice = new intl.numberformat('en-us', { style: 'currency', currency: 'usd', ...
...ame: 'short' }; const americandatetime = new intl.datetimeformat('en-us', options).format; console.log(americandatetime(july172014)); // 07/16/14, 5:00 pm pdt number formatting the numberformat object is useful for formatting numbers, for example currencies. const gasprice = new intl.numberformat('en-us', { style: 'currency', currency: 'usd', minimumfractiondigits: 3 }); console.log(gasprice.format(5.259)); // $5.259 const handecimalrmbinchina = new intl.numberformat('zh-cn-u-nu-hanidec', { style: 'currency', currency: 'cny' }); console.log(handecimalrmbinchina.format(1314.25)); // ¥ 一,三一四.二五 collation the collator object is useful for comparing and sorting strings. for example, there are actua...
SyntaxError: missing ) after argument list - JavaScript
syntaxerror: missing ) after argument list (firefox) error type syntaxerror. what went wrong? there is an error with how a function is called. this might be a typo, a missing operator, or an unescaped string, for example. examples because there is no "+" operator to concatenate the string, javascript expects the argument for the log function to be just "pi: ". ...
...es because there is no "+" operator to concatenate the string, javascript expects the argument for the log function to be just "pi: ". in that case, it should be terminated by a closing parenthesis. console.log('pi: ' math.pi); // syntaxerror: missing ) after argument list you can correct the log call by adding the "+" operator: console.log('pi: ' + math.pi); // "pi: 3.141592653589793" unterminated strings console.log('"java" + "script" = \"' + 'java' + 'script\"); // syntaxerror: missing ) after argument list here javascript thinks that you meant to have ); inside the string and ignores it, and it ends up not knowing that you meant the ); to end the function console.log. to fix this, we could put a' after the "script" string: console.log('"java" + "script" = \"' + 'java' + 'script\...
SyntaxError: missing ) after condition - JavaScript
the javascript exception "missing ) after condition" occurs when there is an error with how an if condition is written. it must appear in parenthesis after the if keyword. message syntaxerror: expected ')' (edge) syntaxerror: missing ) after condition (firefox) error type syntaxerror what went wrong? there is an error with how an if condition is written. in any programming language, code needs to make decisions and carry out actions accordingly depending on different inputs. the if statement executes a statement if a specified condition is truthy. in javascript, this condition must appear in parenthesis after the if keyword, like this: if (condition) { // do something if the condition is true } examples missing parenthesis it might just be an oversight, carefully check all you p...
...f the condition is true } examples missing parenthesis it might just be an oversight, carefully check all you parenthesis in your code. if (3 > math.pi { console.log("wait what?"); } // syntaxerror: missing ) after condition to fix this code, you would need to add a parenthesis that closes the condition. if (3 > math.pi) { console.log("wait what?"); } misused is keyword if you are coming from another programming language, it is also easy to add keywords that don't mean the same or have no meaning at all in javascript. if (done is true) { console.log("we are done!"); } // syntaxerror: missing ) after condition instead you need to use a correct comparison operator. for example: if (done === true) { console.log("we are done!"); } ...
SyntaxError: missing ; before statement - JavaScript
s a semicolon (;) missing somewhere and can't be added by automatic semicolon insertion (asi). you need to provide a semicolon, so that javascript can parse the source code correctly. message syntaxerror: expected ';' (edge) syntaxerror: missing ; before statement (firefox) error type syntaxerror. what went wrong? there is a semicolon (;) missing somewhere. javascript statements must be terminated with semicolons. some of them are affected by automatic semicolon insertion (asi), but in this case you need to provide a semicolon, so that javascript can parse the source code correctly. however, oftentimes, this error is only a consequence of another error, like not escaping strings properly, or using var wrongly. you might also have too many parenthesis somewhere. carefully check the syn...
...ties with var you cannot declare properties of an object or array with a var declaration. ...
Arrow function expressions - JavaScript
gth }) => length); // [8, 6, 7, 9] no separate this before arrow functions, every new function defined its own this value based on how the function was called: a new object in the case of a constructor. undefined in strict mode function calls. the base object if the function was called as an "object method". etc. this proved to be less than ideal with an object-oriented style of programming. function person() { // the person() constructor defines `this` as an instance of itself. this.age = 0; setinterval(function growup() { // in non-strict mode, the growup() function defines `this` // as the global object (because it's where growup() is executed.), // which is different from the `this` // defined by the person() constructor. this.age++; }, 1000); } v...
...n have either a "concise body" or the usual "block body". in a concise body, only an expression is specified, which becomes the implicit return value. in a block body, you must use an explicit return statement. 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 = () => { foo: 1 }; // calling func() returns undefined! var func = () => { foo: function() {} }; // syntaxerror: function statement requires a name this is because the code inside braces ({}) is parsed as a sequence of statements (i.e. foo is treated like a label, not a...
The arguments object - JavaScript
ay-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 are formally declared to accept. this technique is useful for functions that can be passed a variable number of arguments, such as math.min(). this example function accepts any number of string arguments and returns the longest one: function longeststring() { var longest = ''; for (var i=0; i < arguments.length; i++) { if (arguments[i].length > longest.length) { longest = arguments[i]; } } return longest; } you can use arguments.length to count how many arguments the function was called with. if you instead w...
...; } you can use arguments.length to count how many arguments the function was called with. if you instead want to count how many parameters a function is declared to accept, inspect that function's length property. 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. forbidden in strict mode. arguments.length the number of arguments that were passed to the function. arguments[@@iterator] returns a new array iterator object that contains the values ...
Array.prototype.copyWithin() - JavaScript
prototype, 'copywithin', { value: function(target, start/*, end*/) { // steps 1-2. if (this == null) { throw new typeerror('this is null or not defined'); } var o = object(this); // steps 3-5. var len = o.length >>> 0; // steps 6-8. ...
...); } var o = object(this); // steps 3-5. var len = o.length >>> 0; // steps 6-8. var relativetarget = target >> 0; var to = relativetarget < 0 ? math.max(len + relativetarget, 0) : math.min(relativetarget, len); // steps 9-11. var relativestart = start >> 0; var from = relativestart < 0 ? math.max(len + relativestart, 0) : math.min(relativestart, len); // steps 12-14. var end = arguments[2]; var relativeend = end === undefined ? len : end >> 0; var final = relativeend < 0 ? math.max(len + relativeend, 0) : math.min(relativeend, len); // step 15. var count = math.min(final - from, len - to); // steps 16-17. var direction = 1; if (from < to && to < (from + count)) { d...
Array.prototype.every() - JavaScript
e been deleted, or which have never been assigned values. callback is invoked with three arguments: the value of the element, the index of the element, and the array object being traversed. if a thisarg parameter is provided to every, it will be used as callback's this value. otherwise, the value undefined will be used as its this value. the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. every does not mutate the array on which it is called. the range of elements processed by every is set before the first invocation of callback. therefore, callback will not run on elements that are appended to the array after the call to every begins. if existing elements of the array are changed, their value as passed ...
...given condition.) polyfill every was added to the ecma-262 standard in the 5th edition, and it may not be present in other implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of every in implementations which do not natively support it. this algorithm is exactly the one specified in ecma-262, 5th edition, assuming object and typeerror have their original values, and that callbackfn.call evaluates to the original value of function.prototype.call. if (!array.prototype.every) { array.prototype.every = function(callbackfn, thisarg) { 'use strict'; var t, k; if (this == null) { throw new typeerror('this is null or not defined'); } // 1. let o be the result of calling toobject pas...
Array.prototype.filter() - JavaScript
simply skipped, and are not included in the new array. callback is invoked with three arguments: the value of the element the index of the element the array object being traversed if a thisarg parameter is provided to filter, it will be used as the callback's this value. otherwise, the value undefined will be used as its this value. the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. filter() does not mutate the array on which it is called. the range of elements processed by filter() is set before the first invocation of callback. elements which are appended to the array (from callback) after the call to filter() begins will not be visited by callback. if existing elements of the array are deleted i...
...er() was added to the ecma-262 standard in the 5th edition. therefore, it may not be present in all implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of filter() in ecma-262 implementations which do not natively support it. this algorithm is exactly equivalent to the one specified in ecma-262, 5th edition, assuming that fn.call evaluates to the original value of function.prototype.bind(), and that array.prototype.push() has its original value. if (!array.prototype.filter){ array.prototype.filter = function(func, thisarg) { 'use strict'; if ( ! ((typeof func === 'function' || typeof func === 'function') && this) ) throw new typeerror(); var len = this.length >>> 0, res = new ...
Array.prototype.forEach() - JavaScript
t invoked for index properties that have been deleted or are uninitialized. (for sparse arrays, see example below.) callback is invoked with three arguments: the value of the element the index of the element the array object being traversed if a thisarg parameter is provided to foreach(), it will be used as callback's this value. the thisarg value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. the range of elements processed by foreach() is set before the first invocation of callback. elements which are appended to the array after the call to foreach() begins will not be visited by callback. if existing elements of the array are changed or deleted, their value as passed to callback will be the value at the tim...
... or reduce() it always returns the value undefined and is not chainable. the typical use case is to execute side effects at the end of a chain. foreach() does not mutate the array on which it is called. (however, callback may do so) there is no way to stop or break a foreach() loop other than by throwing an exception. if you need such behavior, the foreach() method is the wrong tool. early termination may be accomplished with: a simple for loop a for...of / for...in loops array.prototype.every() array.prototype.some() array.prototype.find() array.prototype.findindex() array methods: every(), some(), find(), and findindex() test the array elements with a predicate returning a truthy value to determine if further iteration is required. foreach expects a synchronous function for...
Array.from() - JavaScript
m() was added to the ecma-262 standard in the 6th edition (es2015). as such, it may not be present in other implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of array.from() in implementations that don't natively support it. polyfill notes: this algorithm is exactly as specified in ecma-262 6th edition (assuming object and typeerror have their original values and that callback.call() evaluates to the original value of function.prototype.call()). in addition, since true iterables cannot be polyfilled, this implementation does not support generic iterables as defined in the 6th edition of ecma-262. // production steps of ecma-262, edition 6, 22.1.2.1 if (!array.from) { array.from = (function () { ...
...on (value) { var number = number(value); if (isnan(number)) return 0; if (number === 0 || !isfinite(number)) return number; return (number > 0 ? 1 : -1) * math.floor(math.abs(number)); }; var maxsafeinteger = math.pow(2, 53) - 1; var tolength = function (value) { var len = tointeger(value); return math.min(math.max(len, 0), maxsafeinteger); }; var setgetitemhandler = function setgetitemhandler(isiterator, items) { var iterator = isiterator && items[symboliterator](); return function getitem(k) { return isiterator ? iterator.next() : items[k]; }; }; var getarray = function getarray( t, a, ...
Array.isArray() - JavaScript
given a typedarray instance, false is always returned. polyfill running the following code before any other code will create array.isarray() if it's not natively available. ...
... array. array.isarray([1, 2, 3]); // true array.isarray({foo: 123}); // false array.isarray('foobar'); // false array.isarray(undefined); // false syntax array.isarray(value) parameters value the value to be checked. return value true if the value is an array; otherwise, false. description if the value is an array, true is returned; otherwise, false is. see the article “determining with absolute accuracy whether or not a javascript object is an array” for more details. given a typedarray instance, false is always returned. polyfill running the following code before any other code will create array.isarray() if it's not natively available. if (!array.isarray) { array.isarray = function(arg) { return object.prototype.tostring.call(arg) === '[object array]'; }...
Array.prototype.map() - JavaScript
you're not returning a value from the callback. parameters in detail callback is invoked with three arguments: the value of the element, the index of the element, and the array object being mapped. if a thisarg parameter is provided, it will be used as callback's this value. otherwise, the value undefined will be used as its this value. the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. map does not mutate the array on which it is called (although callback, if invoked, may do so). the range of elements processed by map is set before the first invocation of callback. elements which are appended to the array after the call to map begins will not be visited by callback. if existing elements of the array a...
...me indices blank. polyfill map was added to the ecma-262 standard in the 5th edition. therefore, it may not be present in all implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of map in implementations which do not natively support it. this algorithm is exactly the one specified in ecma-262, 5th edition, assuming object, typeerror, and array have their original values and that callback.call evaluates to the original value of function.prototype.call. // production steps of ecma-262, edition 5, 15.4.4.19 // reference: http://es5.github.io/#x15.4.4.19 if (!array.prototype.map) { array.prototype.map = function(callback/*, thisarg*/) { var t, a, k; if (this == null) { throw new typeerror('...
Array.prototype.push() - JavaScript
, ...[, elementn]]]) parameters elementn the element(s) to add to the end of the array. return value the new length property of the object upon which the method was called. description the push method appends values to an array. push is intentionally generic. this method can be used with call() or apply() on objects resembling arrays. the push method relies on a length property to determine where to start inserting the given values. if the length property cannot be converted into a number, the index used is 0. this includes the possibility of length being nonexistent, in which case length will also be created. although strings are native, array-like objects, they are not suitable in applications of this method, as strings are immutable. similarly for the native, array-like object...
...suitable in applications of this method, as strings are immutable. similarly for the native, array-like object arguments. examples adding elements to an array the following code creates the sports array containing two elements, then appends two elements to it. the total variable contains the new length of the array. let sports = ['soccer', 'baseball'] let total = sports.push('football', 'swimming') console.log(sports) // ['soccer', 'baseball', 'football', 'swimming'] console.log(total) // 4 merging two arrays this example uses apply() to push all elements from a second array. do not use this method if the second array (morevegs in the example) is very large because the maximum number of parameters that one function can take is limited in practice. see apply() for more details. l...
Array.prototype.some() - JavaScript
een deleted or which have never been assigned values. callback is invoked with three arguments: the value of the element, the index of the element, and the array object being traversed. if a thisarg parameter is provided to some(), it will be used as the callback's this value. otherwise, the value undefined will be used as its this value. the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. some() does not mutate the array on which it is called. the range of elements processed by some() is set before the first invocation of callback. elements appended to the array after the call to some() begins will not be visited by callback. if an existing, unvisited element of the array is changed by callback, its valu...
...or any condition! polyfill some() was added to the ecma-262 standard in the 5th edition, and it may not be present in all implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of some() in implementations which do not natively support it. this algorithm is exactly the one specified in ecma-262, 5th edition, assuming object and typeerror have their original values and that fun.call evaluates to the original value of function.prototype.call(). // production steps of ecma-262, edition 5, 15.4.4.17 // reference: http://es5.github.io/#x15.4.4.17 if (!array.prototype.some) { array.prototype.some = function(fun, thisarg) { 'use strict'; if (this == null) { throw new typeerror('array.prototype.som...
Array - JavaScript
arrot"] (the original array is changed) console.log(removeditems) // ["turnip", "radish"] copy an array let shallowcopy = fruits.slice() // this is how to make a copy // ["strawberry", "mango"] accessing array elements javascript arrays are zero-indexed. the first element of an array is at index 0, and the last element is at the index value equal to the value of the array's length property minus 1. using an invalid index number returns undefined. let arr = ['this is the first element', 'this is the second element', 'this is the last element'] console.log(arr[0]) // logs 'this is the first element' console.log(arr[1]) // logs 'this is the second element' console.log(arr[arr.length - 1]) // logs 'this is the last element' array elements are object properties...
...totype.find() returns the found element in the array, if some element in the array satisfies the testing function, or undefined if not found. array.prototype.findindex() returns the found index in the array, if an element in the array satisfies the testing function, or -1 if not found. array.prototype.foreach() calls a function for each element in the array. array.prototype.includes() determines whether the array contains a value, returning true or false as appropriate. array.prototype.indexof() returns the first (least) index of an element within the array equal to an element, or -1 if none is found. array.prototype.join() joins all elements of an array into a string. array.prototype.keys() returns a new array iterator that contains the keys for each index in the array. array.p...
Date.UTC() - JavaScript
or, but treats them as utc. it returns the number of milliseconds since january 1, 1970, 00:00:00 utc. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax since ecmascript 2017: date.utc(year[, month[, day[, hour[, minute[, second[, millisecond]]]]]]) ecmascript 2016 and earlier: (month used to be required) date.utc(year, month[, day[, hour[, minute[, second[, millisecond]]]]]) parameters year a full year. month an integer between 0 (january) and 11 (december) representing the month. (up through ecmascript 2016, month was a required parameter. as of es2017, it no longer is.) day optional an integer b...
...rs year a full year. month an integer between 0 (january) and 11 (december) representing the month. (up through ecmascript 2016, month was a required parameter. as of es2017, it no longer is.) day optional an integer between 1 and 31 representing the day of the month. if omitted, defaults to 1. hour optional an integer between 0 and 23 representing the hours. if omitted, defaults to 0. minute optional an integer between 0 and 59 representing the minutes. if omitted, defaults to 0. second optional an integer between 0 and 59 representing the seconds. if omitted, defaults to 0. millisecond optional an integer between 0 and 999 representing the milliseconds. if omitted, defaults to 0. return value a number representing the number of milliseconds for the given date since januar...
Date.prototype.getYear() - JavaScript
the getyear() method returns the year in the specified date according to local time. because getyear() does not return full years ("year 2000 problem"), it is no longer used and has been replaced by the getfullyear() method. syntax dateobj.getyear() return value a number representing the year of the given date, according to local time, minus 1900. description for years greater than or equal to 2000, the value returned by getyear() is 100 or greater. for example, if the year is 2026, getyear() returns 126. for years between and including 1900 and 1999, the value returned by getyear() is between 0 and 99. for example, if the year is 1976, getyear() returns 76. for years less than 1900, the value returned by getyear() is less than 0. for example, if the year is 1800, getyear() retur...
...ear is 1800, getyear() returns -100. to take into account years before and after 2000, you should use getfullyear() instead of getyear() so that the year is specified in full. backward compatibility behavior in javascript 1.2 and earlier the getyear() method returns either a 2-digit or 4-digit year: for years between and including 1900 and 1999, the value returned by getyear() is the year minus 1900. for example, if the year is 1976, the value returned is 76. for years less than 1900 or greater than 1999, the value returned by getyear() is the four-digit year. for example, if the year is 1856, the value returned is 1856. if the year is 2026, the value returned is 2026. examples years between 1900 and 1999 the second statement assigns the value 95 to the variable year. var xmas =...
Intl.DateTimeFormat.prototype.formatRangeToParts() - JavaScript
ethod receives two dates and returns an array of objects containing the locale-specific tokens representing each part of the formatted date range. ...
.../ > 'wed, 10 jan 2007 11:00:00 gmt' let fmt = new intl.datetimeformat("en", { hour: 'numeric', minute: 'numeric' }); console.log(fmt.formatrange(date1, date2)); // > '10:00 – 11:00 am' fmt.formatrangetoparts(date1, date2); // return value: // [ // { type: 'hour', value: '10', source: "startrange" }, // { type: 'literal', value: ':', source: "startrange" }, // { type: 'minute', value: '00', source: "startrange" }, // { type: 'literal', value: ' – ', source: "shared" }, // { type: 'hour', value: '11', source: "endrange" }, // { type: 'literal', value: ':', source: "endrange" }, // { type: 'minute', value: '00', source: "endrange" }, // { type: 'literal', value: ' ', source: "shared" }, // { type: 'dayperiod', value...
Intl.DateTimeFormat - JavaScript
(new intl.datetimeformat('de-de', options).format(date)); // → "donnerstag, 20. ...
...console.log(new intl.datetimeformat('en-au', options).format(date)); // → "2:00:00 pm aedt" // sometimes you want to be very precise options.fractionalseconddigits = 3; console.log(new intl.datetimeformat('en-au', options).format(date)); // → "2:00:00.200 pm aedt" // sometimes even the us needs 24-hour time options = { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: false, timezone: 'america/los_angeles' }; console.log(new intl.datetimeformat('en-us', options).format(date)); // → "12/19/2012, 19:00:00" // to specify options but use the browser's default locale, use 'default' console.log(new intl.datetimeformat('default', options).format(date)); // → "12/19/2012, 19:00:00" // sometimes it's helpful to inclu...
Intl - JavaScript
timeformat() constructor for objects that enable language-sensitive relative time formatting. static methods intl.getcanonicallocales() returns canonical locale names. 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. locales argument the locales argument requests that a particular locale (or a locale from a list of them) be considered for use in a given operation. a single locale may be sp...
...gorithm specified in the options.localematcher property. locales argument the locales argument requests that a particular locale (or a locale from a list of them) be considered for use in a given operation. a single locale may be specified by either an intl.locale object or a string that is a unicode bcp 47 locale identifier. multiple locales may be specified (and a best-supported locale determined by evaluating each of them in order and comparing against the locales supported by the implementation) by passing an array (or array-like object, with a length property and corresponding indexed elements) whose elements are either intl.locale objects or values that convert to unicode bcp 47 locale identifier strings. if the locales argument is not provided or is undefined, the runtime's defaul...
Map - JavaScript
note: since ecmascript 2015, objects do preserve creation order for string and symbol keys. in javascript engines that comply with the ecmascript 2015 spec, iterating over an object with only string keys will yield the keys in order of insertion. size the number of items in a map is easily retrieved from its size property. the number of items in an object must be determined manually. iteration a map is an iterable, so it can be directly iterated. iterating over an object requires obtaining its keys in some fashion and iterating over them. performance performs better in scenarios involving frequent additions and removals of key-value pairs. not optimized for frequent additions and removals of key-value pairs. s...
... maps can be merged, maintaining key uniqueness: let first = new map([ [1, 'one'], [2, 'two'], [3, 'three'], ]) let second = new map([ [1, 'uno'], [2, 'dos'] ]) // merge two maps. the last repeated key wins. // spread operator essentially converts a map to an array let merged = new map([...first, ...second]) console.log(merged.get(1)) // uno con...
Math.fround() - JavaScript
entation of the given number. description javascript uses 64-bit double floating-point numbers internally, which offer a very high precision. however, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a float32array. this can create confusion: checking a 64-bit float and a 32-bit float for equality may fail even though the numbers are seemingly identical. to solve this, math.fround() can be used to cast the 64-bit float to a 32-bit float. internally, javascript continues to treat the number as a 64-bit float, it just performs a "round to even" on the 23rd bit of the mantissa, and sets all following mantissa bits to 0. if the number is outside the range of a 32-bit float, infinity or -infinity is returned. because fround() is a stat...
...32array(1)); supporting older browsers is slower, but also possible: if (!math.fround) math.fround = function(arg) { arg = number(arg); // return early for ±0 and nan. if (!arg) return arg; var sign = arg < 0 ? -1 : 1; if (sign < 0) arg = -arg; // compute the exponent (8 bits, signed). var exp = math.floor(math.log(arg) / math.ln2); var powexp = math.pow(2, math.max(-126, math.min(exp, 127))); // handle subnormals: leading digit is zero if exponent bits are all zero. var leading = exp < -127 ? 0 : 1; // compute 23 bits of mantissa, inverted to round toward zero. var mantissa = math.round((leading - arg / powexp) * 0x800000); if (mantissa <= -0x800000) return sign * infinity; return sign * powexp * (leading - mantissa / 0x800000); }; examples using math.fround...
Math - JavaScript
the result of the 32-bit integer multiplication of x and y. math.log(x) returns the natural logarithm (㏒e; also, ㏑) of x. math.log1p(x) returns the natural logarithm (㏒e; also ㏑) of 1 + x for the number x. math.log10(x) returns the base-10 logarithm of x. math.log2(x) returns the base-2 logarithm of x. math.max([x[, y[, …]]]) returns the largest of zero or more numbers. math.min([x[, y[, …]]]) returns the smallest of zero or more numbers. math.pow(x, y) returns base x to the exponent power y (that is, xy). math.random() returns a pseudo-random number between 0 and 1. math.round(x) returns the value of the number x rounded to the nearest integer. math.sign(x) returns the sign of the x, indicating whether x is positive, negative, or zero. math.sin(x) returns t...
...tiplied by the tangent of the angle is equal to the opposite. in javascript, we can do this with the following: 50 * math.tan(degtorad(60)). we use our degtorad() function to convert 60 degrees to radians, as math.tan() expects an input value in radians. returning a random integer between two bounds this can be achieved with a combination of math.random() and math.floor(): function random(min, max) { const num = math.floor(math.random() * (max - min + 1)) + min; return num; } random(1, 10); specifications specification ecmascript (ecma-262)the definition of 'math' in that specification. ...
Object.prototype.hasOwnProperty() - JavaScript
e clone https://github.com/mdn/interactive-examples and send us a pull request. syntax obj.hasownproperty(prop) parameters prop the string name or symbol of the property to test. return value a boolean indicating whether or not the object has the specified property as own property. description all descendents of object inherit the hasownproperty method. this method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check for a property in the object's prototype chain. if an object is an array, hasownproperty method can check whether an index exists. note hasownproperty returns true even if the value of the property is null or undefined. o = new object(); o.propone = null; o.haso...
..., hasownproperty method can check whether an index exists. note hasownproperty returns true even if the value of the property is null or undefined. o = new object(); o.propone = null; o.hasownproperty('propone'); // returns true o.proptwo = undefined; o.hasownproperty('proptwo'); // returns true examples using hasownproperty to test for a property's existence the following example determines whether the o object contains a property named prop: o = new object(); o.hasownproperty('prop'); // returns false o.prop = 'exists'; o.hasownproperty('prop'); // returns true direct vs. inherited properties the following example differentiates between direct properties and properties inherited through the prototype chain: o = new object(); o.prop = 'exists'; o.hasownproperty('prop'); ...
Promise() constructor - JavaScript
time when the constructor generates the new promiseobj, it also generates a corresponding pair of functions for resolutionfunc and rejectionfunc; these are "tethered" to the promiseobj. therefore, the code within the executor has the opportunity to perform some operation and then reflect the operation's outcome(if the value is not another promise object) as either "fulfilled" or "rejected" by terminating with an invocation of either the resolutionfunc or the rejectionfunc, respectively. the executor has no meaningful return value. it communicates via the side-effect caused by resolutionfunc or rejectionfunc. the side-effect is that the promiseobj becomes "resolved." typically, it works like this: the operation within executor is asynchronous and provides a callback. the callback is defi...
...ionfunc or the rejectionfunc, respectively. the executor has no meaningful return value. it communicates via the side-effect caused by resolutionfunc or rejectionfunc. the side-effect is that the promiseobj becomes "resolved." typically, it works like this: the operation within executor is asynchronous and provides a callback. the callback is defined within the executor code. the callback terminates by invoking resolutionfunc. the invocation of resolutionfunc includes a value parameter. the value is passed back to the tethered promiseobj. the promiseobj (asynchronously) invokes any .then() associated with it. the value received by promiseobj.then() is passed to the invocation of handlefulfilled as an input parameter (see "chained promises" section). the executor might also include a t...
Reflect.isExtensible() - JavaScript
the static reflect.isextensible() method determines if an object is extensible (whether it can have new properties added to it). it is similar to object.isextensible(), but with some differences. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax reflect.isextensible(target) parameters target the target object which to check if it is extensible. return value a boolean indicating whether or not the target is extensible. exceptions a typeerror, if target is not an object. ...
...ect, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax reflect.isextensible(target) parameters target the target object which to check if it is extensible. return value a boolean indicating whether or not the target is extensible. exceptions a typeerror, if target is not an object. description the reflect.isextensible method allows you determine if an object is extensible (whether it can have new properties added to it). it is the same method as object.isextensible(). examples using reflect.isextensible() see also object.isextensible(). // new objects are extensible. let empty = {} reflect.isextensible(empty) // === true // ...but that can be changed. reflect.preventextensions(empty) reflect.isextensible(empty) // === false // s...
String.prototype.startsWith() - JavaScript
the startswith() method determines whether a string begins with the characters of a specified string, returning true or false as appropriate. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.startswith(searchstring[, position]) parameters searchstring the characters to be searched for at the start of this string. position optional the position in this string at which to begin searching for searchstring. defaults to 0. return value true if the given characters are found at the beginning of the string; otherwise, false. ...
...st. syntax str.startswith(searchstring[, position]) parameters searchstring the characters to be searched for at the start of this string. position optional the position in this string at which to begin searching for searchstring. defaults to 0. return value true if the given characters are found at the beginning of the string; otherwise, false. description this method lets you determine whether or not a string begins with another string. this method is case-sensitive. polyfill this method has been added to the ecmascript 2015 specification and may not be available in all javascript implementations yet. however, you can polyfill string.prototype.startswith() with the following snippet: if (!string.prototype.startswith) { object.defineproperty(string.prototype, 'startswith...
Symbol - JavaScript
ies, so that this array will be empty unless you've set symbol properties on the object. constructor symbol() creates a new symbol object. it is incomplete as a constructor because it does not support the syntax "new symbol()". static properties symbol.asynciterator a method that returns the default asynciterator for an object. used by for await...of. ...
...used by string.prototype.match(). symbol.matchall a method that returns an iterator, that yields matches of the regular expression against a string. used by string.prototype.matchall(). symbol.replace a method that replaces matched substrings of a string. used by string.prototype.replace(). ...
TypedArray.prototype.includes() - JavaScript
the position in this array at which to begin searching for searchelement; defaults to 0. return value a boolean. ...
...ropriate. this method has the same algorithm as array.prototype.includes(). typedarray is one of the typed array types here. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax typedarray.includes(searchelement[, fromindex]); parameters searchelement the element to search for. fromindex optional. the position in this array at which to begin searching for searchelement; defaults to 0. return value a boolean. 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...
WebAssembly.Global() constructor - JavaScript
portable across one or more webassembly.module instances. this allows dynamic linking of multiple modules. syntax new webassembly.global(descriptor, value); parameters descriptor a globaldescriptor dictionary object, which contains two properties: value: a usvstring representing the data type of the global. this can be one of i32, i64, f32, and f64. mutable: a boolean value that determines whether the global is mutable or not. by default, this is false. value the value the variable contains. this can be any value, as long as its type matches the variable's data type. if no value is specified, a typed 0 value is used, as specified by the defaultvalue algorithm. examples creating a new global instance the following example shows a new global instance being created us...
...{ output.innerhtml += `testing ${msg}: `; if (got !== expected) output.innerhtml += `fail!<br>got: ${got}<br>expected: ${expected}<br>`; else output.innerhtml += `success! ...
WebAssembly.Instance() constructor - JavaScript
the webassembly.instance() constructor creates a new instance object which is a stateful, executable instance of a webassembly.module. syntax important: since instantiation for large modules can be expensive, developers should only use the instance() constructor when synchronous instantiation is absolutely required; the asynchronous webassembly.instantiatestreaming() method should be used at all other times. new webassembly.instance(module, importobject); parameters module the webassembly.module object to be instantiated. importobject optional an object containing the values to be imported into the newly-created instance, such as functions or webassembly.memory objects. there must be one matching property for each declared import of module or else a webassembly.linkerror is throw...
... 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(); }) however, the preferred way to get an instance is through the asynchronous webassembly.instantiatestreaming() function, for example 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()); specifications specification webassembly javascript interfacethe definition of 'instance' in that specificat...
WebAssembly.Instance.prototype.exports - JavaScript
readonly property of the webassembly.instance object prototype returns an object containing as its members all the functions exported from the webassembly module instance, to allow them to be accessed and used by javascript. ...
...e using fetch, we compile and instantiate the module using the webassembly.instantiatestreaming() function, importing a javascript function into the webassembly module in the process. we then call an exported webassembly function that is exported by the instance. var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); note: you can also find this example as instantiate-streaming.html on github (view it live also). specifications specification webassembly javascript interfacethe definition of 'webassembly.instance: exports' in that specification. browser compatibility the compatibility ta...
WebAssembly.Instance - JavaScript
specifications specification webas...
... specifications specification webassembly javascript interfacethe definition of 'instance' in that specification. browser compatibility the compatibility table on this page is generated from ...
WebAssembly.Memory() constructor - JavaScript
00 pages (6.4mib). its buffer property will return an arraybuffer. var memory = new webassembly.memory({initial:10, maximum:100}); the second way to get a webassembly.memory object is to have it exported by a webassembly module. ...
...exported by a webassembly module. 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. it then stores some values in that memory, then exports a function and uses it to sum some values. webassembly.instantiatestreaming(fetch('memory.wasm'), { js: { mem: memory } }) .then(obj => { var i32 = new uint32array(memory.buffer); for (var i = 0; i < 10; i++) { i32[i] = i; } var sum = obj.instance.exports.accumulate(0, 10); console.log(sum); }); creating a shared memory by default, webassembly memories are unshared. you can create a shared memory by passing shared: true in the constructor's initializatio...
WebAssembly.Memory.prototype.buffer - JavaScript
the buffer prototype property of the webassembly.memory object returns the buffer contained in the memory. 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. it then stores some values in that memory, then exports a function and uses it to sum some values. ...
... memory. 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. it then stores some values in that memory, then exports a function and uses it to sum some values. webassembly.instantiatestreaming(fetch('memory.wasm'), { js: { mem: memory } }) .then(obj => { var i32 = new uint32array(memory.buffer); for (var i = 0; i < 10; i++) { i32[i] = i; } var sum = obj.instance.exports.accumulate(0, 10); console.log(sum); }); specifications specification webassembly javascript interfacethe definition of 'buffer' in that specification. browser compatibility...
WebAssembly.Memory - JavaScript
0 pages (6.4mib). its buffer property will return an arraybuffer. var memory = new webassembly.memory({initial:10, maximum:100}); the second way to get a webassembly.memory object is to have it exported by a webassembly module. ...
...xported by a webassembly module. 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. it then stores some values in that memory, then exports a function and uses it to sum some values. webassembly.instantiatestreaming(fetch('memory.wasm'), { js: { mem: memory } }) .then(obj => { var i32 = new uint32array(memory.buffer); for (var i = 0; i < 10; i++) { i32[i] = i; } var sum = obj.instance.exports.accumulate(0, 10); console.log(sum); }); creating a shared memory by default, webassembly memories are unshared. you can create a shared memory by passing shared: true in the constructor's initializatio...
WebAssembly.Table() constructor - JavaScript
both elements are null. ...
...get(0)() rather than get(0)) . ...
WebAssembly.Table.prototype.get() - JavaScript
n reference — this is an exported webassembly function, a javascript wrapper for an underlying wasm function. exceptions if index is greater than or equal to table.prototype.length, a rangeerror is thrown. ...
...ion. exceptions if index is greater than or equal to table.prototype.length, a rangeerror is thrown. 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. it then retrieves the references stored in the exported table. webassembly.instantiatestreaming(fetch('table.wasm')) .then(function(obj) { var tbl = obj.instance.exports.tbl; console.log(tbl.get(0)()); // 13 console.log(tbl.get(1)()); // 42 }); note how you've got to include a second function invocation operator at the end of the accessor to actually retrieve the value stored inside the reference (e.g. get(0)() rather than get(0)) — it is a function rather than a simple value. ...
WebAssembly.Table.prototype.set() - JavaScript
eferences (they currently return null). ...
...get(0)() rather than get(0)) . this example shows that we're creating...
WebAssembly.Table - JavaScript
both elements are null. ...
...get(0)() rather than get(0)) . ...
Addition assignment (+=) - JavaScript
the addition assignment operator (+=) adds the value of the right operand to a variable and assigns the result to the variable. the types of the two operands determine the behavior of the addition assignment operator. addition or concatenation is possible. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...or of the addition assignment operator. addition or concatenation is possible. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
this - JavaScript
it can't be set by assignment during execution, and it may be different each time the function is called. ...
... o = new c(); console.log(o.a); // 37 function c2() { this.a = 37; return {a: 38}; } o = new c2(); console.log(o.a); // 38 in the last example (c2), because an object was returned during construction, the new object that this was bound to simply gets discarded. (this essentially makes the statement "this.a = 37;" dead code. it's not exactly dead because it gets executed, but it can be eliminated with no outside effects.) as a dom event handler when a function is used as an event handler, its this is set to the element on which the listener is placed (some browsers do not follow this convention for listeners added dynamically with methods other than addeventlistener()). // when called as a listener, turns the related element blue function bluify(e) { // always true console.log(...
Expressions and operators - JavaScript
refix decrement operators. a++ postfix increment operator. a-- postfix decrement operator. ++a prefix increment operator. --a prefix decrement operator. unary operators a unary operation is operation with only one operand. delete the delete operator deletes a property from an object. void the void operator discards an expression's return value. typeof the typeof operator determines the type of a given object. + the unary plus operator converts its operand to number type. - the unary negation operator converts its operand to number type and then negates it. ~ bitwise not operator. ! logical not operator. arithmetic operators arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value. + addi...
...literals or variables) as their operands and return a single numerical value. + addition operator. - subtraction operator. / division operator. * multiplication operator. % remainder operator. ** exponentiation operator. relational operators a comparison operator compares its operands and returns a boolean value based on whether the comparison is true. in the in operator determines whether an object has a given property. instanceof the instanceof operator determines whether an object is an instance of another object. < less than operator. > greater than operator. <= less than or equal operator. >= greater than or equal operator. note: => is not an operator, but the notation for arrow functions. equality operators the result of evaluating an equality operat...
async function - JavaScript
he function. the await mechanism may be used. return value a promise which will be resolved with the value returned by the async function, or rejected with an exception thrown from, or uncaught within, the async function. description async functions can contain zero or more await expressions. await expressions suspend progress through an async function, yielding control and subsequently resuming progress only when an awaited promise-based asynchronous operation is either fulfilled or rejected. the resolved value of the promise is treated as the return value of the await expression. use of async / await enables the use of ordinary try / catch blocks around asynchronous code. the await keyword is only valid inside async functions. if you use it outside of an async function's body, you w...
...ync function foo() { const result1 = await new promise((resolve) => settimeout(() => resolve('1'))) const result2 = await new promise((resolve) => settimeout(() => resolve('2'))) } foo() note how the promise chain is not built-up in one go. instead, the promise chain is constructed in stages as control is successively yielded from and returned to the async function. as a result, we must be mindful of error handling behavior when dealing with concurrent asynchronous operations. for example, in the following code an unhandled promise rejection error will be thrown, even if a .catch handler has been configured further along the promise chain. this is because p2 will not be "wired into" the promise chain until control returns from p1. async function foo() { const p1 = new promise((res...
break - JavaScript
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax break [label]; label optional identifier associated with the label of the statement. if the statement is not a loop or switch, this is required. description the break statement includes an optional label that allows the program to break out of a labeled statement. the break statement needs to be nested within the referenced label. ...
...ement can be any block statement; it does not have to be preceded by a loop statement. a break statement, with or without a following label, cannot be used within the body of a function that is itself nested within the current loop, switch, or label statement that the break statement is intended to break out of. examples break in while loop the following function has a break statement that terminates the while loop when i is 3, and then returns the value 3 * x. function testbreak(x) { var i = 0; while (i < 6) { if (i == 3) { break; } i += 1; } return i * x; } break in labeled blocks the following code uses break statements with labeled blocks. a break statement must be nested within any label it references. notice that inner_block is nested within outer_bloc...
continue - JavaScript
in a for loop, it jumps to the update expression. ...
...eration. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax continue [label]; label identifier associated with the label of the statement. description in contrast to the break statement, continue does not terminate the execution of the loop entirely: instead, in a while loop, it jumps back to the condition. in a for loop, it jumps to the update expression. the continue statement can include an optional label that allows the program to jump to the next iteration of a labeled loop statement instead of the current loop. in this case, the continue statement needs to be nested within this labeled sta...
let - JavaScript
rror' 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 + 55) evaluates to the if block's foo, and not the overlying variable foo with the value of 33. in the same line, the if block's foo has already been created in the lexical environment, but has not yet reached (and terminated) its initialization (which is part of the statement itself). the if block's foo is still in the temporal dead zone. function test(){ var foo = 33; if(foo) { let foo = (foo + 55); // referenceerror } } test(); this phenomenon may confuse you in a situation like the following. the instruction let n of n.a is already inside the private scope of the for loop's block. so, the ide...
...} test(); this phenomenon may confuse you in a situation like the following. the instruction let n of n.a is already inside the private scope of the for loop's block. so, the identifier n.a is resolved to the property 'a' of the 'n' object located in the first part of the instruction itself (let n). this is still in the temporal dead zone as its declaration statement has not been reached and terminated. function go(n) { // n here is defined! console.log(n); // object {a: [1,2,3]} for (let n of n.a) { // referenceerror console.log(n); } } go({a: [1, 2, 3]}); other situations when used inside a block, let limits the variable's scope to that block. note the difference between var, whose scope is inside the function where it is declared. var a = 1; var b = 2; if (a === 1) { ...
throw - JavaScript
the source for this interactive example is stored in a github repository. ...
... examples throw an object you can specify an object when you throw an exception. you can then reference the object's properties in the catch block. the following example creates an object of type userexception and uses it in a throw statement. function userexception(message) { this.message = message; this.name = 'userexception'...
display - Web app manifests
the display mode changes how much of browser ui is shown to the user and can range from browser (when the full browser window is shown) to fullscreen (when the app is full-screened). note: if the display member is not specified, it defaults to browser. note: you can selectively apply css to your app based on the display mode, using the display-mode media feature. this can be used to provide a consistent user experience between launching a site from an url and launching it from a desktop icon. ...
... area is used and no user agent chrome is shown. standalone standalone the application will look and feel like a standalone application. this can include the application having a different window, its own icon in the application launcher, etc. in this mode, the user agent will exclude ui elements for controlling navigation, but can include other ui elements such as a status bar. minimal-ui minimal-ui the application will look and feel like a standalone application, but will have a minimal set of ui elements for controlling navigation. the elements will vary by browser. browser browser the application opens in a conventional browser tab or new window, depending on the browser and platform. this is the default. (none) example "display": "s...
<mtable> - MathML
Web › MathML › Element › mtable
table> element resets the displaystyle attribute to false. if you want to use this element as an inline-block, you might want to set <mtable displaystyle="true">...</mtable>. attributes align specifies the vertical alignment of the table with respect to its environment. possible values are: axis (default): the vertical center of the table aligns on the environment's axis (typically the minus sign). baseline: the vertical center of the table aligns on the environment's baseline. bottom: the bottom of the table aligns on the environments baseline. center: see baseline. top: the top of the table aligns on the environments baseline. in addition, values of the align attribute can end with a rownumber (e.g. align="center 3"). this allows you to align the specified row of the t...
...tire table. possible values are: none (default), solid and dashed. framespacing specifies additional space added between the table and frame. groupalign unimplemented href used to set a hyperlink to a specified uri. mathbackground the background color. you can use #rgb, #rrggbb and html color names. mathcolor the text color. you can use #rgb, #rrggbb and html color names. unimplemented minlabelspacing a length value specifing the minimum space between a label and the adjacent cell in the row. rowalign specifies the vertical alignment of the cells. multiple values separated by space are allowed and apply to the corresponding rows (e.g. rowalign="top bottom axis"). possible values are: axis, baseline (default), bottom, center and top. rowlines specifies row borders. multiple val...
MathML documentation index - MathML
Web › MathML › Index
element indicates that the content should be rendered as an identifier such as function names, variables or symbolic constants. you can also have arbitrary text in it to mark up terms. 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). child elements of <mlabeledtr> must be <mtd> elements. the first child is the label whereas all other children are representing row contents and are treated identically to children of <mtr> elements. 19 <mmultiscripts> mathml, mathml reference, mathml:element, mathml:script and limit schemata the mathml <mmultiscripts> elem...
...thml <mrow> element is used to group sub-expressions, which usually contain one or more operators with their respective operands (such as <mi> and <mn>). this element renders as a horizontal row containing its arguments. 27 <ms> mathml, mathml reference, mathml:element, mathml:token elements the mathml <ms> element represents a string literal meant to be interpreted by programming languages and computer algebra systems. 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. note that quotation marks should not be specified unless they are part of the string literal. the content of an <ms> element is not an ascii string per se, but rather a sequence of characters ...
Media container formats (file types) - Web media technologies
firefox support for aac relies upon the operating system's media infrastructure, so it is available as long as the os supports it. adts audio data transport stream (adts) is a container format specified by mpeg-4 part 3 for audio data, intended to be used for streamed audio, such as for internet radio. it is, essentially, an almost bare stream of aac audio data, comprised of adts frames with a minimal header. adts media mime types audio audio/aac[1] audio/mpeg[1] [1] the mime type used for adts depends on what kind of audio frames are contained within. if adts frames are used, the audio/aac mime type should be used. if the audio frames are in mpeg-1/mpeg-2 audio layer i, ii, or iii format, the mime type should be audio/mpeg. audio codecs supported...
...t) defines the mpeg-4 (mp4) version 2 container format iso/iec 14496-1 (mpeg-4 part 1 systems) defines the original mpeg-4 (mp4) container format rfc 3533 defines the ogg container format rfc 5334 defines the ogg media types and file extensions quicktime file format specification defines the quicktime movie (mov) format multimedia programming interface and data specifications 1.0 the closest thing to an official wave specification resource interchange file format (used by wav) defines the riff format; wave files are a form of riff webm container guidelines guide for adapting matroska for webm matroska specifications the specification for the matroska container format upon which webm is based ...
Handling media support issues in web content - Web media technologies
ich media file types and codecs to support. this places a small, but reasonably easily overcome, burden on the web developer: to properly handle the situation when the user's browser can't handle a particular type of media. this guide covers techniques you can use to develop web content that meets your media needs while providing the most broadly compatible experience possible. topics we will examine fallbacks, baseline media formats, and error handling practices that will let your content work in as many situations as possible. using poster frames a poster frame is a still image that's representative of the content of a video. this may be simply the first frame of video; however, in many cases, the first frame is blank, or contains nothing but the logo of a business, or some other image t...
... 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. note: progressive (or interlaced) images are inherently slightly larger than the non-progressive versions of the same images. whether the interlacing will benefit your users is up to you to determine. specifying multiple sources checking compatibility in javascript htmlmediaelement.canplaytype and mediasource.istypesupported... detecting playback errors adapting presentation with css memory management ...
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. in this article, we look at how it is used in our js13kpwa example (see the source code also). we examine how to add offline functionality. service workers explained service workers are a virtual proxy between the browser and the network. they finally fix issues that front-end developers have struggled with for years — most notably how to properly cache the assets of a website and make them available when the user’s device is offline. they run on a separate thread from the main javascript code of our page, and don't have any access to th...
...network. they finally fix issues that front-end developers have struggled with for years — most notably how to properly cache the assets of a website and make them available when the user’s device is offline. they run on a separate thread from the main javascript code of our page, and don't have any access to the dom structure. this introduces a different approach from traditional web programming — the api is non-blocking, and can send and receive communication between different contexts. 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. they can do a lot more than "just" offering offline capabilities, including handling notifications, performing heavy calculations on a separate thread, etc. service ...
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
ice worker will receive data from the push server, which can then be shown using the notifications system, or another mechanism if desired. the technology is still at a very early stage — some working examples use the google cloud messaging platform, but are being rewritten to support vapid (voluntary application identification), which offers an extra layer of security for your app. you can examine the service workers cookbook examples, try to set up a push messaging server using firebase, or build your own server (using node.js for example). as mentioned before, to be able to receive push messages, you have to have a service worker, the basics of which are already explained in the making pwas work offline with service workers article. inside the service worker, a push service subscriptio...
...e server. the server stores all the information received when the user subscribed, so the messages can be sent later on when needed. to receive push messages, we can listen to the push event in the service worker file: self.addeventlistener('push', function(e) { /* ... */ }); the data can be retrieved and then shown as a notification to the user immediately. this, for example, can be used to remind the user about something, or let them know about new content being available in the app. push example push needs the server part to work, so we're not able to include it in the js13kpwa example hosted on github pages, as it offers hosting of static files only. it is all explained in the service worker cookbook — see the push payload demo. this demo consists of three files: index.js, whic...
Media - Progressive web apps (PWAs)
in: 1in;} this rule ensures that every h1 element starts on a new page: h1 {page-break-before: always;} more details for full details of css support for paged media, see paged media in the css specification. like other features of css, printing depends on browser choice and its settings. for example, the mozilla browser supplies default margins, headers, and footers for printing. keep in mind that you can't completely control the printed format. it is impossible to anticipate every user's browser choice and settings at the time of printing. user interfaces css has some special properties for devices that support a user interface, like computer displays. these properties dynamically change the appearance of content as the user works with the interface. there are five special selec...
... ...
begin - SVG: Scalable Vector Graphics
Web › SVG › Attribute › begin
d of another animation. a valid syncbase-value consists of an id reference to another animation element followed by a dot and either begin or end to identify whether to synchronize with the beginning or active end of the referenced animation element. an optional offset value as defined in <offset-value> can be appended. <event-value> this value defines an event and an optional offset that determines the time at which the element's animation should begin. the animation start time is defined relative to the time that the specified event is fired. a valid event-value consists of an element id followed by a dot and one of the supported events for that element. all valid events (not necessarily supported by all elements) are defined by the dom and html specifications. those are: focus, blur, f...
...put as parameter. an optional offset value as defined in <offset-value> can be appended. <wallclock-sync-value> this value defines the animation start time as a real-world clock time. a valid wallclock-sync-value consists of the function wallclock() with a time value as parameter. the time syntax is based upon the syntax defined in iso 8601. indefinite the begin of the animation will be determined by a beginelement() method call or a hyperlink targeted to the element. discard for <discard>, begin defines when the target element will be discarded. the <discard> element has an implicit simple duration of indefinite. as soon as the element's active duration starts, the element identified by the href attribute is discarded. the behavior is the same as if node.removechild() were called on...
d - SVG: Scalable Vector Graphics
Web › SVG › Attribute › d
elliptical arc curves are curves defined as a portion of an ellipse. it is sometimes easier to draw highly regular curves with an elliptical arc than with a bézier curve. command parameters notes a (rx ry angle large-arc-flag sweep-flag x y)+ draw an arc curve from the current point to the coordinate x,y. the center of the ellipse used to draw the arc is determined automatically based on the other parameters of the command: rx and ry are the two radii of the ellipse; angle represents a rotation (in degrees) of the ellipse relative to the x-axis; large-arc-flag and sweep-flag allows to chose which arc must be drawn as 4 possible arcs can be drawn out of the other parameters. large-arc-flag allows to chose one of the large...
...t for the next command. all subsequent sets of parameters are considered implicit absolute arc curve (a) commands. a (rx ry angle large-arc-flag sweep-flag dx dy)+ draw an arc curve from the current point to a point for which coordinates are those of the current point shifted by dx along the x-axis and dy along the y-axis. the center of the ellipse used to draw the arc is determined automatically based on the other parameters of the command: rx and ry are the two radii of the ellipse; angle represents a rotation (in degrees) of the ellipse relative to the x-axis; large-arc-flag and sweep-flag allows to chose which arc must be drawn as 4 possible arcs can be drawn out of the other parameters. large-arc-flag allows a choice of large arc (1)...
edgeMode - SVG: Scalable Vector Graphics
the edgemode attribute 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. 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. value duplicate | wrap | none default value duplicate animatable yes duplicate this value indicates that the input image is extended along each of its borders as necessary by duplicating the color values at the given edge of t...
...ended along each of its borders as necessary by duplicating the color values at the given edge of the input image. wrap this value indicates that the input image is extended by taking the color values from the opposite edge of the image. none this value indicates that the input image is extended with pixel values of zero for r, g, b and a. fegaussianblur for <fegaussianblur>, 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. value duplicate | wrap | none default value none animatable yes duplicate this value indicates that the input image is extended along each of its borders as necessary by dupl...
end - SVG: Scalable Vector Graphics
Web › SVG › Attribute › end
d of another animation. a valid syncbase-value consists of an id reference to another animation element followed by a dot and either begin or end to identify whether to synchronize with the beginning or active end of the referenced animation element. an optional offset value as defined in <offset-value> can be appended. <event-value> this value defines an event and an optional offset that determines the time at which the element's animation should end. the animation end time is defined relative to the time that the specified event is fired. a valid event-value consists of an element id followed by a dot and one of the supported events for that element. all valid events (not necessarily supported by all elements) are defined by the dom and html specifications. those are: focus, blur, focu...
...e input as parameter. an optional offset value as defined in <offset-value> can be appended. <wallclock-sync-value> this value defines the animation end time as a real-world clock time. a valid wallclock-sync-value consists of the function wallclock() with a time value as parameter. the time syntax is based upon the syntax defined in iso 8601. indefinite the end of the animation will be determined by an svganimationelement.endelement() method call. examples offset example <svg width="120" height="120" viewbox="0 0 120 120" xmlns="http://www.w3.org/2000/svg" version="1.1"> <!-- animated rectangles --> <rect x="10" y="35" height="15" width="0"> <animate attributetype="xml" attributename="width" to="100" begin="0s" end="8s" fill="...
<animate> - SVG: Scalable Vector Graphics
Web › SVG › Element › animate
the svg <animate> element provides a way to animate an attribute of an element over time. ...
...ovides a way to animate an attribute of an element over time. ...
<animateMotion> - SVG: Scalable Vector Graphics
e type: <string>; default value: none; animatable: no rotate this attribute defines a rotation applied to the elment animated along a path, usually to make it pointing in the direction of the animation. ...
...one; animatable: no rotate this attribute defines a rotation applied to the elment animated along a path, usually to make it pointing in the direction of the animation. ...
<marker> - SVG: Scalable Vector Graphics
Web › SVG › Element › marker
e: <length> ; default value: 3; animatable: yes orient this attribute defines the orientation of the marker relative to the shape it is attached to. value type: auto|auto-start-reverse|<angle> ; default value: 0; animatable: yes preserveaspectratio this attribute defines how the svg fragment must be deformed if it is embedded in a container with a different aspect ratio. value type: (none| xminymin| xmidymin| xmaxymin| xminymid| xmidymid| xmaxymid| xminymax| xmidymax| xmaxymax) (meet|slice)? ; default value: xmidymid meet; animatable: yes refx this attribute defines the x coordinate for the reference point of the marker. value type: left|center|right|<coordinate> ; default value: 0; animatable: yes refy this attribute defines the y coordinate for the reference point of the marker. ...
...aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role usage notes categoriescontainer elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elementsstructural elementsgradient elements<a>, <altglyphdef>, <clippath>, <color-profile>, <cursor>, <filter>, <font>, <font-face>, <foreignobject>, <image>, <marker>, <mask>, <pattern>, <script>, <style>, ...
<set> - SVG: Scalable Vector Graphics
Web › SVG › Element › set
dth="10" height="10"> <set attributename="class" to="round" begin="me.click" dur="2s" /> </rect> </svg> attributes to this attribute defines the value to be applied to the target attribute for the duration of the animation. the value must match the requirements of the target attribute. ...
...ributename="class" to="round" begin="me.click" dur="2s" /> </rect> </svg> attributes to this attribute defines the value to be applied to the target attribute for the duration of the animation. the value must match the requirements of the target attribute. ...
<text> - SVG: Scalable Vector Graphics
Web › SVG › Element › text
tributes class, style, font-family, font-size, font-size-adjust, font-stretch, font-style, font-variant, font-weight conditional processing attributes most notably: requiredextensions, systemlanguage event attributes global event attributes, graphical event attributes presentation attributes most notably: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, dominant-baseline, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, text-anchor, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-coli...
...aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role usage notes categoriesgraphics element, text content elementpermitted contentcharacter data and any number of the following elements, in any order:animation elementsdescriptive elementstext content elements<a> specifications specification status comment scalable vector graphics (svg) 2the definition of '<text>' in that specific...
<tspan> - SVG: Scalable Vector Graphics
Web › SVG › Element › tspan
animatable: yes global attributes core attributes most notably: id, tabindex styling attributes class, style conditional processing attributes most notably: requiredextensions, systemlanguage event attributes global event attributes, graphical event attributes presentation attributes most notably: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, dominant-baseline, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, text-anchor, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-coli...
...aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role usage notes categoriestext content element, text content child elementpermitted contentcharacter data and any number of the following elements, in any order:descriptive elements<a>, <altglyph>, <animate>, <animatecolor>, <set>, <tref>, <tspan> specifications specification status comment scalable vector graphics (svg) 2the defin...
Example - SVG: Scalable Vector Graphics
> <label>attraction to cursor:</label> <input id='attract_cursor' value='6'/> <br/> <label>repulsion from peers:</label> <input id='repel_peer' value='5'/> <br/> </p> </form> <script type='text/javascript'> <![cdata[ // array of motes var motes; // get the display element. function display() { return document.getelementbyid('display'); } // determine dimensions of the display element. // return this as a 2-tuple (x,y) in an array function dimensions() { // our rendering element var display = display(); var width = parseint( display.getattributens(null,'width') ); var height = parseint( display.getattributens(null,'height') ); return [width,height]; } // this is called by mouse move events var mouse_x = 200, mouse...
...height') ); return [width,height]; } // this is called by mouse move events var mouse_x = 200, mouse_y = 150; function onmousemove(evt) { mouse_x = evt.clientx; mouse_y = evt.clienty; var widget = document.getelementbyid('cursor'); widget.setattributens(null,'cx',mouse_x); widget.setattributens(null,'cy',mouse_y); } document.onmousemove = onmousemove; // determine (x,y) of the cursor function cursor() { return [mouse_x, mouse_y]; } // determine average (x,y) of the swarm function averagemoteposition() { if( !motes ) return [0,0]; if( motes.length == 0 ) return [0,0]; var i; var sum_x=0, sum_y=0; for(i=0; i<motes.length; i++) { sum_x += motes[i].x; sum_y += motes[i].y; } return [sum_x/motes.length,...
Namespaces crash course - SVG: Scalable Vector Graphics
a <title> element. how should the user agent distinguish between the two? in fact how does the user agent tell when xml content is something it knows about, and not just a meaningless xml file containing arbitrary element names unknown to it? contrary to popular opinion, the answer to this question is not "it can tell from the doctype declaration". dtds were never designed with mixed content in mind, and past attempts to create mixed content dtds are now considered to have failed. xml, and some xml dialects (svg included), don't require a doctype declaration, and svg 1.2 won't even have one. the fact that doctype declarations (usually) match the content in single content type files is merely coincidental. dtds are for validation only, not identification of content. user agents that cheat an...
...chever xml dialect has the namespace name 'http://www.w3.org/2000/svg' which is, of course, svg. note that the namespace declaration only needs to be provided once on a root element. the declaration defines the default namespace, so the user agent knows that all the <svg> element's descendants also belong to the same namespace. user agents check to see if they recognize the namespace name to determine if they know how to handle the markup. note that namespace names are just strings, so the fact that the svg namespace name also looks like a uri isn't important. uris are commonly used because they are unique, the intention is not to "link" somewhere. (in fact uris are used so frequently that the term "namespace uri" is commonly used instead of "namespace name".) redeclaring the default namesp...
Clipping and masking - SVG: Scalable Vector Graphics
ut-off-bottom)" /> </svg> centered at (100,100) a circle with radius 100 is painted. the attribute clip-path references a <clippath> element with a single rect element. this rectangular on its own would paint the upper half of the canvas black. note, that the clippath element is usually placed in a defs section. the rect will not be painted, however. instead its pixel data will be used to determine, which pixels of the circle "make it" to the final rendering. since the rectangle covers only the upper half of the circle, the lower half of the circle will vanish: screenshotlive sample we now have a semicircle without having to deal with arcs in path elements. for the clipping, every path inside the clippath is inspected and evaluated together with its stroke properties and transformation. ...
...200" fill="green" /> <rect x="0" y="0" width="200" height="200" fill="red" mask="url(#mask)" /> </svg> you see a green-filled rect at the lowest layer and on top a red-filled rect. the latter has the mask attribute pointing to the mask element. the content of the mask is a single rect element, that is filled with a black-to-white gradient. as a result the pixels of the red rectangle use the luminance value of the mask content as the alpha value (the transparency), and we see a green-to-red gradient as a result: screenshotlive sample transparency with opacity there is a simple possibility to set the transparency for a whole element. it's the opacity attribute: <rect x="0" y="0" width="100" height="100" opacity=".5" /> the above rectangle will be painted half-transparent. for the fill...
Fills and Strokes - SVG: Scalable Vector Graphics
ernal css file. most svg you'll find around the web use inline css, but there are advantages and disadvantages associated with each type. fill and stroke attributes painting basic coloring can be done by setting two attributes on the node: fill and stroke. using fill sets the color inside the object and stroke sets the color of the line drawn around the object. you can use the same css color naming schemes that you use in html, whether that's color names (that is red), rgb values (that is rgb(255,0,0)), hex values, rgba values, etc. <rect x="10" y="10" width="100" height="100" stroke="blue" fill="purple" fill-opacity="0.5" stroke-opacity="0.8"/> in addition, you can specify the opacity of either the fill or stroke separately in svg. these are controlled by the fill-opacity and s...
...bers, in which case the renderer loops the numbers twice to create an even pattern. so the first path renders 5 filled, 10 empty, 5 filled, and then loops back to create 5 empty, 10 filled, 5 empty. the pattern then repeats. there are additional stroke and fill properties available, including fill-rule, which specifies how to color in shapes that overlap themselves; stroke-miterlimit, which determines if a stroke should draw miters; and stroke-dashoffset, which specifies where to start a dasharray on a line. using css in addition to setting attributes on objects, you can also use css to style fills and strokes. not all attributes can be set via css. attributes that deal with painting and filling are usually available, so fill, stroke, stroke-dasharray, etc... can all be set this way, in ad...
Other content in SVG - SVG: Scalable Vector Graphics
width="128" height="146" transform="rotate(45)" xlink:href="https://developer.mozilla.org/static/img/favicon144.png"/> </svg> screenshotlive sample embedding arbitrary xml since svg is an xml application, you can of course always embed arbitrary xml anywhere in an svg document. but then you have no means to define how the surrounding svg should react on the content. actually, in a conforming viewer it will react in no way at all, the data will simply be omitted. therefore the specification adds the <foreignobject> element to svg. its sole purpose is to be a container for other markup and a carrier for svg styling attributes (most prominently width and height to define the space the object will take). the foreignobject element is a good way to embed xhtml in svg. if you have longer ...
... width and height to define the space the object will take). the foreignobject element is a good way to embed xhtml in svg. if you have longer texts, the html layout is more suitable and comfortable than the svg text element. another often cited use case is the embedding of formulas with mathml. for scientific applications of svg this is a very good way to join both worlds. note: please keep in mind, that the content of the foreignobject must be processable by the viewer. a standalone svg viewer is unlikely to be able to render html or mathml. since the foreignobject is an svg element, you can, like in the case of image, use any svg goodness with it, which then will be applied to its content. « previousnext » ...
Positions - SVG: Scalable Vector Graphics
the grid for all elements, svg uses a coordinate system or grid system similar to the one used by canvas (and by a whole lot of other computer drawing routines). that is, the top left corner of the document is considered to be the point (0,0), or point of origin. positions are then measured in pixels from the top left corner, with the positive x direction being to the right, and the positive y direction being to the bottom. ...
...ed. the default user coordinate system maps one user pixel to one device pixel. (however, the device may decide, what it understands as one pixel.) lengths in the svg file with specific dimensions, like "in" or "cm", are then calculated in a way that makes them appear 1:1 in the resulting image. a quote from the svg 1.1 specification illustrates this: [...] suppose that the user agent can determine from its environment that "1px" corresponds to "0.2822222mm" (i.e., 90dpi). then, for all processing of svg content: [...] "1cm" equals "35.43307px" (and therefore 35.43307 user units) « previousnext » ...
SVG fonts - SVG: Scalable Vector Graphics
</font-face> <missing-glyph><path d="m0,0h200v200h-200z"/></missing-glyph> <glyph unicode="!" horiz-adv-x="300"><!-- outline of exclam. pt. glyph --></glyph> <glyph unicode="@"><!-- outline of @ glyph --></glyph> <!-- more glyphs --> </font> we start with the <font> element. this bears an id attribute, to enable it to be referenced via a uri (see below). the horiz-adv-x attribute determines how wide a character is on average compared to the path definitions of the single glyphs. the value 1000 sets a reasonable value to work with. there are several accompanying attributes that help further define the basic glyph-box layout. the <font-face> element is the svg equivalent of the css @font-face declaration. it defines basic properties of the final font such as weight, style, etc. in ...
... can further restrict it to certain languages (represented by xml:lang on the target) exclusively. again, you can use arbitrary svg to define the glyph, which allows for great effects in supporting user agents. there are two further elements that can be defined inside font: <hkern> and <vkern>. each carries references to at least two characters (attributes u1 and u2) and an attribute k that determines how much the distance between those characters should be decreased. the below example instructs user agents to place the "a" and "v" characters closer together the standard distance between characters. <hkern u1="a" u2="v" k="20" /> referencing a font when you have put together your font declaration as described above, you can just use a simple font-family attribute to actually apply the fo...
Secure contexts - Web security
a secure context is a window or worker for which certain minimum standards of authentication and confidentiality are met. many web apis and features are accessible only in a secure context. the primary goal of secure contexts is to prevent mitm attackers from accessing powerful apis that could further compromise the victim of an attack. why should some features be restricted? some apis on the web are very powerful, giving an attacker the ability to do the following and more: invade a user's privacy. get low-level access to a user's computer. get access to data such as user credentials. when is a context considered secure? a context is considered secure when it meets certain minimum standards of authentication and confidentiality defined in the secure contexts specification. ...
...vered over tls within an <iframe>, its context is not considered secure if it has an ancestor that was not also delivered over tls. however, it’s important to note that if a non-secure context causes a new window to be created (with or without specifying noopener), then the fact that the opener was insecure has no effect on whether the new window is considered secure. that’s because the determination of whether or not a particular document is in a secure context is based only on considering it within the top-level browsing context with which it is associated — and not whether a non-secure context happened to be used to create it. locally-delivered resources such as those with http://127.0.0.1 urls, http://localhost urls (under certain conditions), and file:// urls are also considered ...
Types of attacks - Web security
being validated for malicious content. the malicious content often includes javascript, but sometimes html, flash, or any other code the browser can execute. the variety of attacks based on xss is almost limitless, but they commonly include transmitting private data like cookies or other session information to the attacker, redirecting the victim to a webpage controlled by the attacker, or performing other malicious operations on the user's machine under the guise of the vulnerable site. xss attacks can be put into three categories: stored (also called persistent), reflected (also called non-persistent), or dom-based. stored xss attacks the injected script is stored permanently on the target servers. the victim then retrieves this malicious script from the server when the browser sends ...
...t card information). the traffic is passed through, possibly with alterations. open wifi networks are a typically means of executing this attack. session hijacking session hijacking consists of gaining access to and misusing a user's authenticated session. this may happen by stealing a cookie for an existing session, or by fooling the user (or their browser) into setting a cookie with a predetermined session id. exfiltration avenues can be limited by deploying a strict content-security-policy. session fixation a third party is able to determine a user’s session identifier (i.e., by reading it or setting it), and therefore interact with the server as that user. stealing cookies is one way to do this. recall that a subdomain such as application.example.com can set a cookie to be sent wi...
Introduction to using XPath in JavaScript - XPath
is the evaluate function of the document object. document.evaluate this method evaluates xpath expressions against an xml based document (including html documents), and returns a xpathresult object, which can be a single node or a set of nodes. the existing documentation for this method is located at document.evaluate, but it is rather sparse for our needs at the moment; a more comprehensive examination will be given below. var xpathresult = document.evaluate( xpathexpression, contextnode, namespaceresolver, resulttype, result ); parameters the evaluate function takes a total of five parameters: xpathexpression: a string containing the xpath expression to be evaluated. contextnode: a node in the document against which the xpathexpression should be evaluated, including any and all of...
...any_type constant when the result type in the resulttype parameter is specified as any_type, the xpathresult object returned, will be whatever type that naturally results from the evaluation of the expression. it could be any of the simple types (number_type, string_type, boolean_type), but, if the returned result type is a node-set then it will only be an unordered_node_iterator_type. to determine that type after evaluation, we use the resulttype property of the xpathresult object. the constant values of this property are defined in the appendix. none yet =====any_type example===== <pre> </pre> examples within an html document the following code is intended to be placed in any javascript fragment within or linked to the html document against which the xpath expression is to be evaluate...
<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. syntax <xsl:decimal-format name=name decimal-separator=character grouping-separator=character infinity=string minus-sign=character nan=string percent=character per-mille=charater zero-digit=character digit=character pattern-separator=character /> required attributes none. optional attributes name specifies a name for this format. decimal-separator specifies the decimal point character. the default is (.). grouping-separator specifies the thousands separator character. the default is (,). infinity specifies ...
... pattern-separator=character /> required attributes none. optional attributes name specifies a name for this format. decimal-separator specifies the decimal point character. the default is (.). grouping-separator specifies the thousands separator character. the default is (,). infinity specifies the string used to represent infinity. the default is the string "infinity". minus-sign specifies the minus sign character. the default is the hyphen (-). nan specifies the string used when the value is not a number. the default is the string "nan". percent specifies the percentage sign character. the default is (%). per-mille specifies the per thousand character. the default is (‰). zero-digit specifies the digit zero character. the default is (0). ...
For Further Reading - XSLT: Extensible Stylesheet Language Transformations
kay length: 992 pages publisher: wrox; 2 edition (may 3, 2001) isbn: 0764543814 michael kay is a member of the w3c xsl working group and the developer of his own open-source xslt processor, saxon. he is also the author of the only book on this subject to have reached a second edition. this is a very big book, well laid out, and exhaustive, if sometimes exhausting, in detail, covering every possible base in the xslt story. ...
...ition. this is a very big book, well laid out, and exhaustive, if sometimes exhausting, in detail, covering every possible base in the xslt story. http://www.amazon.com/xslt-programme.../dp/0764543814 xslt author: doug tidwell length: 473 pages publisher: o'reilly media; 1 edition (august 15, 2001) isbn: 0596000537 doug tidwell is a senior developer at ibm and a prominent evangelist for xml technologies generally. he is the author of several articles and tutorials on various aspects of xml at ibm's extensive xml developer site. this book is somewhat less comprehensive than michael kay's, but it covers the basics well, and offers some intriguing examples. http://www.amazon.com/xslt-doug-tidwell/dp/0596000537 learning xml, second edition autho...
JavaScript/XSLT Bindings - XSLT: Extensible Stylesheet Language Transformations
cessor.importstylesheet(xslref); for the actual transformation, xsltprocessor requires an xml document, which is used in conjunction with the imported xsl file to produce the final result. the xml document can be a separate xml file loaded as shown in figure 1, or it can be part of the existing page. to process part of a page's dom, it is necessary to first create an xml document in memory. 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. document.importnode() allows transferring a dom fragment between documents, in this case from an html document to an xml document. the first parameter references the dom node to clone. by making the second parameter "true", it will...
.... ...
XSLT: Extensible Stylesheet Language Transformations
Web › XSLT
ml document is created based on the content of an existing document. then, the new document may be serialized (output) by the processor in standard xml syntax or in another format, such as html or plain text. xslt is most often used to convert data between different xml schemas or to convert xml data into web pages or pdf documents. documentation xslt element reference reference. transforming xml with xslt xslt allows a stylesheet author to transform a primary xml document in two significant ways: manipulating and sorting the content, including a wholesale reordering of it if so desired, and transforming the content into a different format. using the mozilla javascript interface to xsl transformations this document describes the javascript interface to the xslt processing engine i...
... the xslt processing engine in mozilla 1.2 and up. specifying parameters using processing instructions firefox allows stylesheet parameters to be specified when using the <?xml-stylesheet?> processing instruction. this is done using the <?xslt-param?> pi described in this document. xslt & xpath tutorial the topxml xslt tutorial introduces you to the basics of xslt concepts, syntax, and programming. xslt tutorial this w3schools tutorial teaches the reader how to use xslt to transform xml documents into other formats, like xhtml. what is xslt? this extensive introduction to xslt and xpath assumes no prior knowledge of the technologies and guides the reader through background, context, structure, concepts and introductory terminology. common xslt errors this article lists some common p...
Caching compiled WebAssembly modules - WebAssembly
if we do, we instantiate it with the given import object: console.log(`found ${url} in wasm cache`); return webassembly.instantiate(module, importobject); }, if not, we compile it from scratch and then store the compiled module in the database with a key of url, for next time we want to use it: errmsg => { console.log(errmsg); return webassembly.instantiatestreaming(fetch(url)).then(results => { storeindatabase(db, results.module); return results.instance; }); }) }, note: it is for this kind of usage that webassembly.instantiate() returns both a module and an instance: the module represents the compiled code and can be stored/retrieved in idb or shared between workers via postmessage(); the instance is stateful and contains the...
...tance is stateful and contains the callable javascript functions, therefore it cannot be stored/shared. if opening the database failed (for example due to permissions or quota), we fall back to simply fetching and compiling the module and don't try to store the results (since there is no database to store them into). ...
Exported WebAssembly functions - WebAssembly
t they are encapsulated by the exported wasm function object instance and there are only limited ways to access them. ...
... we then get the function exported from the module, retrieve the functions it references via tbl.get() and log the result of invoking each one to the console. next, we use set() to make the othertable table contain references to the same functions as the tbl table. to prove this, we then retrieve these references back from othertable and print their results to console too, which gives...
Loading Content Scripts - Archive of obsolete content
data = require("sdk/self").data; ... contentscriptfile: data.url("my-content-script.js") both contentscript and contentscriptfile accept an array of strings, so you can load multiple scripts, which can also interact directly with each other in the content process: // "data" is supplied by the "self" module var data = require("sdk/self").data; ... 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. this enables you to load a javascript library like jquery by url, then pass in a simple script inline that can use jquery. unless your content script is extremely simple and consists only of a static string, don't use contentscript: if you do, you may have p...
Reddit Example - Archive of obsolete content
finally, it registers a listener to the user-defined click event which in turn passes the url in...
Contributor's Guide - Archive of obsolete content
ithout writing a significant amount of boilerplate code. content processes a content process was supposed to run all the code associated with a single tab. conversely, an add-on process was supposed to run all the code associated with a single add-on. neither content or add-on proceses were ever actually implemented, but by the time they were cancelled, the sdk was already designed with them in mind. to understand this article, it's probably best to read it as if content and add-on processes actually exist. getting started learn how to contribute to the add-on sdk. modules a module is a self-contained unit of code, which is usually stored in a file, and has a well defined interface. the use of modules greatly improves the maintainability of code, by splitting it up into independ...
Module structure of the SDK - Archive of obsolete content
udes 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. if you need to use a different version of the modules, you can do this by checking out the version of the sdk that you need and passing the -o or --overload option to jpm run or jpm xpi. local modules at a minimum, an sdk-based add-on consists of a single module named main.js, but you can factor your add-on's code into a collection of separate commonjs modules. each module is a separate file stored under your add-on's "lib" directory, and exports the objects you want to make available to other modules in your add-on. see the tutorial on creating reusable modules for more details. to import a local mod...
SDK and XUL Comparison - Archive of obsolete content
arty modules that's not the whole story. if you need more flexibility than the sdk's high-level apis provide, you can use its low-level apis to load xpcom objects directly or to manipulate the dom directly as in a traditional bootstrapped extension. alternatively, you can load third-party modules, which extend the sdk's core apis. note that by doing this you lose some of the benefits of programming with the sdk including simplicity, compatibility, and to a lesser extent security. ...
Two Types of Scripts - Archive of obsolete content
y have access to different sets of apis. in the sdk documentation we call one sort "add-on code" and the other sort "content scripts". add-on code this is the place where the main logic of your add-on is implemented. your add-on is implemented as a collection of one or more commonjs modules. each module is supplied as a script stored under the lib directory under your add-on's root directory. 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. to learn how to implement and import your own modules, see the tutorial on implementing reusable modules. content scripts while your add-on will always have a "main.js" module, you will only need to write content scripts if your...
Working with Events - Archive of obsolete content
objects emit events on state changes that might be of interest to add-on code, such as browser windows opening, pages loading, network requests completing, and mouse clicks. by registering a listener function to an event emitter an add-on can receive notifications of these events. we talk about content scripts in more detail in the working with content scripts guide. 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. in this case one end of the conversation emits the events, and the other end listens to them. ...
context-menu - Archive of obsolete content
t least one image: require("sdk/context-menu").item({ label: "this page has images", contentscript: 'self.on("context", function (node) {' + ' return !!document.queryselector("img");' + '});' }); note that the listener function has a parameter called node. this is the node in the page that the user context-clicked to invoke the menu. you can use it to determine whether your item should be shown. you can both specify declarative contexts and listen for contexts in a content script. your context listener is called even if any declarative contexts are not current (since firefox 36). if you combine selectorcontext and the "context" event, be aware that the node argument passed to the "context" event will not always match the type specified in selectorcon...
notifications - Archive of obsolete content
"i have an icon!", iconurl: myiconurl }); this module depends on the underlying system's notification service. if the user's system does not support desktop notifications or if its notifications service is not running: if firefox was started normally, notifications are logged to firefox's error console if the user launched firefox from the command line, notifications are logged to the terminal. globals functions notify(options) displays a transient notification to the user. parameters options : object optional options: name type title string a string to display as the message's title. text string a string to display as the body of the message. iconurl string the url of an icon to display...
request - Archive of obsolete content
s designed to be used once. attempts to reuse them will throw an error. since the request is not being made by any particular website, requests made here are not subject to the same-domain restriction that requests made in web pages are subject to. with the exception of response, all of a request object's properties correspond with the options in the constructor. each can be set by simply performing an assignment. however, keep in mind that the same validation rules that apply to options in the constructor will apply during assignment. thus, each can throw if given an invalid value. the example below shows how to use request to get the most recent tweet from the @mozhacks account: var request = require("sdk/request").request; var latesttweetrequest = request({ url: "https://api.twitter.
High-Level APIs - Archive of obsolete content
s. system query the add-on's environment and access arguments passed to it. tabs open, manipulate, and access tabs, and receive tab events. timers set one-off and periodic timers. ui provides access to button, toolbar, and sidebar ui objects. url construct, validate, and parse urls. widget create a simple user interface for an add-on in firefox's add-on bar. windows enumerate and examine open browser windows, open new windows, and listen for window events. ...
core/heritage - Archive of obsolete content
el // => true pixel instanceof point // => true extend module exports extend utility function, that is useful for creating objects that inherit from other objects, without associated classes. it's very similar to object.create, only difference is that second argument is an object containing properties to be defined, instead of property descriptor map. also, keep in mind that returned object will be frozen. var { extend } = require('sdk/core/heritage'); var base = { a: 1 }; var derived = extend(base, { b: 2 }); derived.a // => 1 derived.b // => 2 base.isprototypeof(derived) // => true mix module exports mix utility function that is useful for mixing properties of multiple objects into a single one. functi...
loader/sandbox - Archive of obsolete content
1.5. load scripts this module provides a limited api for loading scripts from local urls. data: urls are supported. load(scope, 'resource://path/to/my/script.js'); load(scope, 'file:///path/to/script.js'); load(scope, 'data:,var a = 5;'); globals functions sandbox(source) make a new sandbox that inherits principals from source. parameters source : string|window|null an object that determines the privileges that will be given to the sandbox. this argument can be: a uri string, giving the sandbox the same privileges as a script loaded from that url a dom window object, giving the sandbox the same privileges as the dom window null, to give the sandbox chrome privileges. returns sandbox : a sandbox in which you can evaluate and load javascript. evaluate(sandbox, code, uri, lin...
places/history - Archive of obsolete content
t contain 'javascript' }); globals functions search(queries, options) queries can be performed on history entries by passing in one or more query options. each query option can take several properties, which are and'd together to make one complete query. for additional queries within the query, passing more query options in will or the total results. an options object may be specified to determine overall settings, like sorting and how many objects should be returned. parameters queries : object|array an object representing a query, or an array of objects representing queries. each query object can take several properties, which are queried against the history database. each property is and'd together, meaning that bookmarks must match each property within a query object. multiple quer...
platform/xpcom - Archive of obsolete content
aces. for example, this subclass implements the nsirequest interface: var { class } = require('sdk/core/heritage'); var { unknown } = require('sdk/platform/xpcom'); var request = class({ extends: unknown, interfaces: [ 'nsirequest' ], initialize: function initialize() { this.pending = false; }, ispending: function() { return this.pending; }, resume: function() { console.log('resuming...'); }, suspend: function() { console.log('suspending...'); }, cancel: function() { console.log('canceling...'); } }); this component definition: specifies that we support nsirequest using the interfaces property. initializes pending in initialize() adds our implementation of the nsirequest interface although request also implements nsisupports, there is no need to add it here, beca...
system/unload - Archive of obsolete content
uctor method. default is unload. when(callback) registers a function to be called when the module is unloaded. parameters callback : function a function that will be called when the module is unloaded. it is called with a single argument, one of the following strings describing the reason for unload: "uninstall", "disable", "shutdown", "upgrade", or "downgrade". if a reason could not be determined, undefined will be passed instead. note that if an add-on is unloaded with reason "disable", it will not be notified about "uninstall" while it is disabled. see bug 571049. ...
test/httpd - Archive of obsolete content
ule instead. an http server for the mozilla platform, which can be used in unit tests. usage the most basic usage is: var { startserverasync } = require("sdk/test/httpd"); var srv = startserverasync(port, basepath); require("sdk/system/unload").when(function cleanup() { srv.stop(function() { // you should continue execution from this point. }) }); this starts a server in background (assuming you're running this code in an application that has an event loop, such as firefox). the server listens at http://localhost:port/ and serves files from the specified directory. you can serve static content or use sjs scripts, as described in documentation on developer.mozilla.org. you can also use nshttpserver to start the server manually: var { nshttpserver } = require("sdk/test/httpd"); var ...
test/utils - Archive of obsolete content
. if the callback is defined, then the afterfn is considered asynchronous, and the callback must be invoked before the next test runs. waituntil(predicate, interval) waituntil returns a promise that resolves upon the predicate returning a truthy value, which is called every interval milliseconds. parameters predicate : function a function that gets called every interval milliseconds to determine if the promise should be resolved. interval : number the frequency in milliseconds to execute predicate. defaults to 10. returns promise : waituntil returns a promise that becomes resolved once the predicate returns a truthy value. the promise cannot be rejected. ...
ui/button/action - Archive of obsolete content
disabled buttons appear disabled in the ui, and do not respond to clicks. defaults to false. onclick function click handler for the button. badge number or string new in firefox 36. badge to attach to the button. the badge can contain as many characters (or digits) as you like, but only the first...
ui/frame - Archive of obsolete content
n (hidpi) display. this toolbar might look something like: scripting frames to add scripts to frames, include them directly from the frame's html content, as with a normal web page: <script type="text/javascript" src="frame.js"></script> as usual, the path to the script is relative to the html file's location. messages logged from a frame script using the console will not appear in the terminal when you run the add-on using jpm run. however, they will appear in the browser console. this issue is being tracked as bug 982385. 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(). a frame creates a separate iframe instance for each browser window. so there are three cases to consi...
Low-Level APIs - Archive of obsolete content
ent/worker used in the internal implementation of sdk modules which use content scripts to interact with web content. core/heritage helper functions for inheritance. core/namespace provides an api for creating namespaces for objects, which effectively may be used for creating fields that are not part of objects public api. core/promise implementation of promises to make asynchronous programming easier. dev/panel enables you to extend the firefox developer tools. event/core the event/core module allows the creation of apis to broadcast and subscribe to events. event/target create objects that broadcast events. frame/hidden-frame creates firefox frames (i.e. xul <iframe> elements) that are not displayed to the user. frame/utils provides helper functions for working with platfor...
cfx to jpm - Archive of obsolete content
"lib/main.js", although it can be set to a different file using the main field in package.json. in jpm, the entry point defaults to "index.js". so when switching over to jpm: either rename your "main.js" to "index.js" and move it from "lib" to the top level or add a main field to package.json with the value "lib/main.js". loading modules the jpm tool uses the same logic as node.js to determine how to resolve the argument to require(). in most respects this is the same as the old cfx logic. however there are a few differences, because old compatibility shims have been removed. requiring local modules suppose your add-on is structured into separate modules: my-addon lib main.js utils.js when you want to use the "utils" module in "main.js", you s...
jpm-mobile - Archive of obsolete content
ion 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. npm is included in node.js, so to install npm, visit nodejs.org and click the install button. after that you can install jpm just as you would any other npm package: npm install jpm-mobile -g depending on your setup, you might need to run this as an administrator: sudo npm install jpm-mobile -g at the command prompt, type: jpm-mobile you should see a screen summarizing the available jpm-mobile commands. note that unlike cfx, jpm-mobile is available in every command prompt you start, as long as you installed it with the -g flag. problems? if you don't see this, ask for help. sdk users and project team members discuss problems and proposals on...
Overview - Archive of obsolete content
elies on the since-removed widget api and no longer works with firefox. the widget api is deprecated from firefox 29 onwards. please see the ui module for replacements. in particular, for a simple button, try the action button or toggle button apis, and for a more complex widget try the toolbar or sidebar apis. the annotator uses content scripts to build user interfaces, get user input, and examine the dom of pages loaded by the user. meanwhile the main module contains the application logic and mediates interactions between the different sdk objects. we could represent the basic interactions between the main module and the various content scripts like this: user interface the annotator's main user interface consists of a widget and three panels. the widget is used to switch the an...
Storing annotations - Archive of obsolete content
rgia,serif; font-size: 1.5em; text-align:center; } save these in data/list as annotation-list.html and annotation-list.css respectively. updating main.js here's the code to create the panel, which can go in the main function. ...
Creating Event Targets - Archive of obsolete content
for example, you can listen to the tabs module's ready event or the panel object's show event. with the sdk, it's also simple to implement your own event targets. ...
Display a Popup - Archive of obsolete content
function handleclick(state) { text_entry.show(); } // when the panel is displayed it generated an event called // "show": we will listen for that event and when it happens, // send our own "show" event to the panel's script, so the // script can prepare the panel for display. text_entry.on("show", function() { text_entry.port.emit("show"); }); // listen for messages called "text-entered" coming from // the content script. the message payload is the text the user // entered. // in this implementation we'll just log the text to the console. text_entry.port.on("text-entered", function (text) { console.log(text); text_entry.hide(); }); the content script "get-text.js" looks like this: // when the user hits return, send the "text-entered" // message to main.js. // the message payload...
Open a Web Page - Archive of obsolete content
to do this, pass a callback function into open(). ...
Localization - Archive of obsolete content
izable string can take two or more placeholders, translators can define the order in which placeholders are inserted, without affecting the code. primarily, this is important because different languages have different rules for word order. even within the same language, though, translators should have the freedom to define word order. for example, suppose we want to include a localized string naming a person's home town. there are two placeholders: the name of the person and the name of the home town: var _ = require("sdk/l10n").get; console.log(_("home_town_id", "bob", "london")); an english translator might want to choose between the following: "<town_name> is <person_name>'s home town." "<person_name>'s home town is <town_name>" to choose the first option, the .properties file can...
Bookmarks - Archive of obsolete content
e nsinavbookmarksservice.getitemtitle() method: var thistitle = bmsvc.getitemtitle(newbkmkid); this code will display an alert containing the title of the item referenced by the id newbkmkid. the item uri similarly, you can obtain the uri corresponding to a given bookmark item by calling the nsinavbookmarksservice.getbookmarkuri() method. var thisuri = bmsvc.getbookmarkuri(newbkmkid); assuming you've run all the code samples previous to this one, this will output "http://google.com". you can use the nsinavbookmarksservice.changebookmarkuri() method to update the uri for a given bookmark item: var uri = ios.newuri("http://mozilla.com/", null, null); bmsvc.changebookmarkuri(newbkmkid, uri); this example changes the bookmark to refer to the mozilla web site instead of google. note...
Canvas code snippets - Archive of obsolete content
pixels.data.length; var amount = 0; for (i = 0; i < all; i += 4) { if (pixels.data[i] === r && pixels.data[i + 1] === g && pixels.data[i + 2] === b) { amount++; } } return amount; }; getting the color of a pixel in a canvas this following snippet returns an object with the rgba values of the pixel at position x and y of the canvas. this can be used to determine if the mouse cursor is inside a certain shape or not. function getpixelcolour(canvas, x, y) { var cx = canvas.getcontext('2d'); var pixel = cx.getimagedata(x, y, 1, 1); return { r: pixel.data[0], g: pixel.data[1], b: pixel.data[2], a: pixel.data[3] }; } chaining methods this class provides jquery-style chained access to 2d context methods and properties. function can...
Customizing the download progress bar - Archive of obsolete content
wnloadoverlay" xmlns="http://www.mozilla.org/keymaster/gat...re.is.only.xul"> </overlay> in jar.mn, make sure that there is an asterisk in front of the entry for myextension.css so that it will be preprocessed. this is required since it contains platform-specific directives, as we will see. ...
Dialogs and Prompts - Archive of obsolete content
("name").value, description:document.getelementbyid("description").value, enabled:document.getelementbyid("enabled").checked}; return true; } see also passing parameter to a dialog and getting return values from it. displaying the standard "open file"/"save file"/"select folder" dialogs nsifilepicker prompts and the prompt service now that you understand dialogs, let's examine prompts. prompts differ from dialogs in that they don't require custom xul. because of this, however, they are less customizable. most web developers are familiar with the alert() function: this is a prime example of a prompt. nsipromptservice is an xpcom interface available to c++ and chrome javascript code (not to web pages' js), that provides methods for displaying a few simple types of d...
File I/O - Archive of obsolete content
useful to provide a content type hint to prevent the file system from doing a potentially expensive content type look up (which would be synchronous i/o). in this case an nsichannel object has to be explicitly created from the file: components.utils.import("resource://gre/modules/netutil.jsm"); // content type hint is useful on mobile platforms where the filesystem // would otherwise try to determine the content type. var channel = netutil.newchannel(file); channel.contenttype = "application/json"; netutil.asyncfetch(channel, function(inputstream, status) { ... }); writing to a file write a string this sample uses netutil.jsm and fileutils.jsm. components.utils.import("resource://gre/modules/netutil.jsm"); components.utils.import("resource://gre/modules/fileutils.jsm"); // file is n...
HTML in XUL for rich tooltips - Archive of obsolete content
this example demonstrates the dynamic injection of html into a xul element. specifically, we create a rich tooltip that uses html instead of plain text. dynamic html in xul tooltip insert the appropriate code from below into your xul overlay. ...
JS XPCOM - Archive of obsolete content
metimes javascript is clever enough to know all the interfaces available on a component, but in most cases you will have to explicitly check for an interface. with the preferences service from the previous example we can do the following: var preferences = preferences.queryinterface(components.interfaces.nsiprefbranch2); this allows you to use the methods in the nsiprefbranch2 interface. ...
JavaScript Debugger Service - Archive of obsolete content
components.interfaces.jsdiexecutionhook.return_continue; } }; filters jsd also allows the use of filters to track which scripts should trigger the hooks. note that the jsdifilter only applies to jsdiexecutionhooks, which are breakpointhook, debughook, debuggerhook, interrupthook and throwhook. note that filters are matched in a first in, first compared fashion. the first filter to match determines whether or not the hook is called. we create a generic createfilter function that acts as a jsdifilter factory. function createfilter(pattern, pass) { var jsdifilter = components.interfaces.jsdifilter; var filter = { globalobject: null, flags: pass ? (jsdifilter.flag_enabled | jsdifilter.flag_pass) : jsdifilter.flag_enabled, urlpattern: pattern, startline: 0, endline: 0 }; ret...
Miscellaneous - Archive of obsolete content
the text to be inserted"); disabling javascript programmatically // disable js in the currently active tab from the context of browser.xul gbrowser.docshell.allowjavascript = false; if this isn't your browser, you should save the value and restore it when finished. if you wish to block selected scripts based on their uri, implement nsicontentpolicy. 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. that was attempt number %s. these properties can be accessed from javascript in the following manner: var common = { _bundle: components.classes["@mozilla.org/intl/stringbundle;1"] .getservice(components.interfaces.nsistringbundleservice) .createbundle("...
Progress Listeners - Archive of obsolete content
note that the browser uses a weak reference to your listener object, so make sure to keep an external reference to your object to ensure that it stays in memory. when used with a tabbrowser, you cannot choose which types of events that will be received. instead, you receive those events that the tabbrowser is interested in, except that the onlinkicon...
Sidebar - Archive of obsolete content
chrome://yourextension/content/whatever.xul") { // call "yournotificationfunction" in the sidebar's context: sidebarwindow.yournotificationfunction(anyarguments); } testing which sidebar is open the sidebar content may contain different panels (bookmarks, history, webpanel, etc.) and sometimes one wants to only act on the sidebar when it contains a specific panel. ...
Tabbox - Archive of obsolete content
obsolete since gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. ...
Toolbar - Archive of obsolete content
the user has to drag it onto the toolbar. ...
URI parsing - Archive of obsolete content
when dealing with the facilities of nsiuri, the task of parsing a uri can still require additional work. it's advised that you use the nsieffectivetldservice. grabbing the main domain using the effectivetldservice even using the etldservice, you're unable to get just the base domain sans tld. so, here's some sample code to determine the base domain without any suffixes: var etldservice = components.classes["@mozilla.org/network/effective-tld-service;1"]. getservice(components.interfaces.nsieffectivetldservice); var suffix = etldservice.getpublicsuffix(auri); var basedomain = etldservice.getbasedomain(auri); // this includes the tld basedomain = basedomain.substr(0, (basedomain.length - suffix.length - 1)); // - 1 to remove the period before the tld ...
Communication between HTML and your extension - Archive of obsolete content
blur action to a little javascript function that performed a standard ajax request to get a result. the onreadystatechange was set to another little javascript function that would update a specific element on the html page with the result. the result of the ajax request was the something that i wanted the extension to find. there were only a handful of events that seemed relevant (load, change, dominsertnode, dominsertnodeintodocument, domactivate) and i tried them all in many different ways. some of the events only apply to certain types of elements so i included trying to modify the result of the ajax request to be of the appropriate element type (img, which supports "onload," rather than span, which doesn't, for example). the problem with the events is the timing. i wasn't sure about the d...
Displaying web content in an extension without security issues - Archive of obsolete content
or just that scenario: var target = entry.getelementsbyclassname("description")[0]; var fragment = components.classes["@mozilla.org/feed-unescapehtml;1"] .getservice(components.interfaces.nsiscriptableunescapehtml) .parsefragment(description, false, null, target); target.appendchild(fragment); this will add the html code to the specified node — minus all the potentially dangerous content. ...
Downloading JSON and JavaScript in extensions - Archive of obsolete content
json if the extension is downloading json, then the developer should be using one of the json decoding methods discussed here and not using eval() at all. json is about state and does not allow functions to be decoded. the json decoding methods available to extension developers protect the extension from malicious json and javascript. downloading state from a remote webserver using json is becoming extremely popular. use the json decoders, not eval()! downloading javascript of course there are times when javascript code modules are downloaded and injected into the extension. this usually happens because the extension is trying to keep some of its code fresh and dynamic, and the developers don't want to create a new version of the extension for each script change. in this case, javascript...
Interaction between privileged and non-privileged pages - Archive of obsolete content
* @returns {e4x} the (unchecked) detail data from the page. * you must check the data. * @see <https://developer.mozilla.org/docs/code_snippets/ * interaction_between_privileged_and_non-privileged_pages#security_notes> */ function geteventdata(event) { if (event.target.ownerdocument != targetdoc) throw "event from unex...
Listening to events in Firefox extensions - Archive of obsolete content
ar about changes relating to loads of the content contained within them. simple dom events registering for a dom event is done using with code such as the following: function callback(evt) { // do your processing here. check evt.target for the target of the event. } b.addeventlistener("event", callback, false) where b is the browser or tabbrowser you wish to watch for events from. keep in mind that the events may come from any frame within the browser or, for a tabbrowser, any of the browsers within it. some of the more interesting dom events you may wish to monitor are listed here: event description domlinkadded dispatched when a new html <link> element is detected in the document. domtitlechanged dispatched when the title of the page changes. ...
Migrating raw components to add-ons - Archive of obsolete content
ate binary components not because they want to interact with firefox at the c++ level, but strictly so that they can make use of third party dlls. 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. it allows javascript code to load functions from dlls on windows, and should allow you to eliminate your dependence on binary components entirely. this leads to a better compatibility path as new versions of firefox are released. ...
Adding windows and dialogs - Archive of obsolete content
nal comma-separated list of features, which describe the behavior and appearance of the window. if this value is null or empty, the default toolbars of the main window will be added to the new one, which is rarely what you want. the window.open page has a detailed description of the features you can use and their values. the following features are very important and you should always keep them in mind: chrome. this can only be used from the chrome, not from regular html javascript. it indicates that a chrome document is being opened, not a web page. this means that the document defines the whole window, and not only the inner content area. you should always include it when opening a xul window or dialog. modal. modal windows block their parent window until action is taken on them. an aler...
Appendix F: Monitoring DOM changes - Archive of obsolete content
he x-tag library. the code below contains an inefficient fallback implementation for older browsers. it is worth noting, however, that while the animation-based implementation will fire any time an element which previously did not match the given selector is changed so that it does (when a class is added, for instance), the fallback will only match nodes when they are inserted into the dom tree. minor changes are also required if one wishes to support other browsers, or to run in non-chrome-privileged scopes. /** * watches for nodes matching the given css selector to become * available. * * @param {string} selector the css selector of nodes about which you * want to be notified. * @param {function(event)} callback the function which is to be called * when matching nodes becom...
Getting Started with Firefox Extensions - Archive of obsolete content
p bubble. you should see another pop-up telling you that you are installing an unverified add-on. click "install". after the extension is installed, you'll be asked to restart firefox. installing, uninstalling, enabling and disabling add-ons require a restart to complete, with the exception of npapi plugins, add-ons sdk extensions and bootstrapped extensions. this is an important point to keep in mind if you're building an extension that manipulates other extensions or themes. after installing, look at the main firefox window and see if you notice anything different. did you see it? there's a new menu on the main menu, labeled "hello world!". if you open the menu and then the menu item below, you'll see a nice alert message (for some definitions of 'nice'). click on the ok button to clos...
Local Storage - Archive of obsolete content
g it unless you really have to. you'll still need to understand at least a little about rdf when you read the documentation about templates. templates templates are a very powerful tool in firefox. they allow you to automatically generate xul content using information from a datasource, and automatically update the content once the datasource changes. they were designed with rdf datasources in mind, but since firefox 3 they have been extended to support sqlite datasources as well. handling templates can also be complicated, but it is worth the effort if you need to display long lists or trees with complex data. if you manage to get your display code to use templates, you will have saved a lot of coding. since templates are not necessary for most extensions and they're a complicated subjec...
Observer Notifications - Archive of obsolete content
he notifyobservers call is used to notify all registered observers about the notification topic "xulschoolhello-test-topic". the input parameter is an instance of nsisupportsstring with some text and the last input parameter is a string "hello". in a chrome browser overlay file, we register an observer to listen to the notification topic "xulschoolhello-test-topic" when the window loads. keep in mind that you have to remove observers that are not longer needed. not doing so will result in memory leaks. therefore, the registered observer is unregistered when the browser window is unloaded. /** * controls the browser overlay for the hello world extension. */ xulschoolchrome.browseroverlay = { /* observer service. */ _observerservice : null, /** * initializes this object. */ ...
XPCOM Objects - Archive of obsolete content
ize_is(acount), retval] out string achildarray); this method returns an array of strings. the first parameter is an input that tells the method where to start looking. the second one will hold the length of the return array, and the third parameter will hold the array itself. note the metadata included in the square brackets, indicating that the parameter is an array, and that its size is determined by the acount parameter. here's one way to invoke this method: let childarrayobj = new object(); let childarray; this._prefservice.getchildlist("", {}, childarrayobj); // .value holds the actual array. childarray = childarrayobj.value; the general rule for out parameters is that you can pass an empty object, and then you can get the result by accessing the value attribute in this objec...
Extensions support in SeaMonkey 2 - Archive of obsolete content
h users and developers compared to the old xpinstall/-style extensions. the basics to support seamonkey 2 as a target application, you need to add it to the list of target applications in the extension's install.rdf file. the code for that will look something like this: <em:targetapplication> <!-- seamonkey --> <description> <em:id>{92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a}</em:id> <em:minversion>2.0</em:minversion> <em:maxversion>2.*</em:maxversion> </description> </em:targetapplication> the install.js is not supported any more and should be removed. differences as compared to other toolkit/-based applications you need to overlay/open different chrome urls as compared to firefox. some urls are listed below: url in firefox url in seamonkey ...
Setting up an extension development environment - Archive of obsolete content
however, it is usually easier to place extension files in a temporary location, which also protects source file...
Tabbed browser - Archive of obsolete content
{ title: url } ], usertypedvalue: url, usertypedclear: 2, lastaccessed: tab.lastaccessed, index: 1, hidden: false, attributes: {}, image: null })); reusing tabs rather than open a new browser or new tab each and every time one is needed, it is good practice to try to re-use an existing tab which already displays the desired url--if one is already open. following this practice minimizes the proliferation of tabs and browsers created by your extension. reusing by url/uri a common feature found in many extensions is to point the user to chrome:// uris in a browser window (for example, help or about information) or external (on-line http(s)://) html documents when the user clicks an extension's button or link. the following code demonstrates how to re-use an existing tab th...
Firefox addons developer guide - Archive of obsolete content
"the <code>init()</code> method is as shown...". if you use the interface template when mentioning interfaces by name, mdc will automatically format them and generate links to their documentation, like this: nsiconsoleservice. if you prefer, you can just link to the articles directly. either way, these links should be added. 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. todo: all fixme notes inside the documents; add abbreviation definition to acronyms; add some link to the internal mdc documentation when it makes sense; indent source code; make sure documentation is relev...
Using the Stylesheet Service - Archive of obsolete content
tylesheetservice); var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uri = ios.newuri("chrome://myext/content/myext.css", null, null); sss.loadandregistersheet(uri, sss.user_sheet); note: loadandregistersheet will load the stylesheet synchronously, so you should only call this method using local uris. determining whether a sheet has been loaded if you are writing an extension and adding your stylesheet in an onload handler, you'll want to see if your sheet has already been added. if you don't check, you will wind up adding your sheet once per window load. var sss = components.classes["@mozilla.org/content/style-sheet-service;1"] .getservice(components.interfaces.nsistylesheetservi...
Search Extension Tutorial (Draft) - Archive of obsolete content
at the end, and should be used where possible. changing default preference values there are two common ways of changing default preference values. the simplest, which works only for traditional, non-restartless add-ons, is to add the preference changes to a file in an extension's defaults/preferences/ directory. the following file, for instance, would change the default keyword search engine, assuming that an engine with the name example engine is installed, as described below: // this is a localizable preference, so it must contain a url which // points at a properties file containing the preference name as a // property. we use a data: url for simplicity. pref("browser.search.defaultenginename", "data:text/plain,browser.search.defaultenginename=example engine"); in the case or restartless e...
Add-ons - Archive of obsolete content
itional extensions. the user interface for the preferences defined with this new syntax appears in the extension's detail view in the add-on manager. this functionality originally appeared in firefox mobile and is now available in firefox on the desktop as well. install manifests an install manifest is the file an add-on manager-enabled xul application (e.g. firefox or thunderbird) uses to determine information about an add-on as it is being installed. it contains metadata identifying the add-on, providing information about who created it, where more information can be found about it, which versions of what applications it is compatible with, how it should be updated, and so on. interaction between privileged and non-privileged pages an easy way to send data from a web page to an extensio...
Adding preferences to an extension - Archive of obsolete content
next, we call our own refreshinformation() method to immediately fetch and display the current information about the stock the extension is configured to monitor. we'll look at the details of how this method works later. the last thing the startup() method does is to call the window.setinterval() dom method to set up a callback that will automatically run our refreshinformation() method every 10 minutes. the interval time is specified in milliseconds. shutdown() the stockwatcher.shutdown() method deactivates the observer on the preferences. this is also where we would add any other shutdown tasks we need to perform. shutdown: function() { this.prefs.removeobserver("", this); }, observe() the stockwatcher.observe() function is called whenever an event occurs on the preference branch...
Underscores in class and ID Names - Archive of obsolete content
upport for underscores in css has greatly improved since this article was originally published in 2001 and the following recommendation is no longer accurate for most circumstances. summary: the use of the underscore character in css can lead to major display problems in multiple browsers. learn why this is so, and how to keep your sites from being bitten by this problem. this technical note examines the use of underscores in css, and why they should be generally avoided in most circumstances. it is a fairly common practice in many programming languages to use the underscore character (_) in the place of a "space" in variable and function names. for example, a function whose job is to "get the length of a string" might be called get_string_length, and a variable representing the number of ...
XUL user interfaces - Archive of obsolete content
y tuesday wednesday thurdsay friday saturday clear today june 27, 2005 notes about this demonstration: the xul document links the stylesheet as usual, and it also links the script. the script is not important in this demonstration. much of the style that you see is determined by your browser's theme. examine the document's stylesheet to ensure that you understand all the rules there. if there is a rule that you do not understand, comment it out and refresh your browser to see the effect on the document. challenge use the dom inspector tool to examine the date textbox. it is made up of other elements that are generated by its xbl binding. discover t...
Beginner tutorials - Archive of obsolete content
lthis page illustrates how you can use css in mozilla to improve the structure of complex applications, making code and resources more easily reusable.underscores in class and id namessummary: the use of the underscore character in css can lead to major display problems in multiple browsers. learn why this is so, and how to keep your sites from being bitten by this problem. this technical note examines the use of underscores in css, and why they should be generally avoided in most circumstances.xml datathis page contains an example of how you can use css with xml data.xul user interfacesthis page illustrates mozilla's specialized language for creating user interfaces. ...
chargingchange - Archive of obsolete content
ion none properties the event callback doesn't receive any event objects, but properties can be read from the batterymanager object received from the navigator.getbattery method. property type description batterymanager.charging boolean the system's battery charging status. returns true if the battery is charging, if the state of the system's battery is not determinable, or if no battery is attached to the system. returns false if the battery is discharging. read only. example navigator.getbattery().then(function(battery) { console.log("battery charging? " + (battery.charging ? "yes" : "no")); battery.addeventlistener('chargingchange', function() { console.log("battery charging? " + (battery.charging ? "yes" : "no")); }); }); related e...
Getting the page URL in NPAPI plugin - Archive of obsolete content
work in mozillas older than firefox 1.0 via npp_newstream from braden mcdaniel: if you want the uri of the resource for which the plug-in is invoked, the most npapi-friendly way to do that is to get it from the npstream that is passed to npp_newstream. tradeoffs: npapi only probably works in all browsers, all versions is sort of backwards (?) advantages / disadvantages ? via dom from benjamin smedberg: the npapi gives you the ability to get access to the nsidomwindow object which contains the current plugin via the npnvdomelement enum passed to npn_getvalue. this returns an addrefed nsidomelement interface pointer from which you can call .ownerdocument (on nsidomnode), queryinterface that object to nsidom3document, and call .documenturi. tradeoffs: is inherently incompatible with ot...
Install.js - Archive of obsolete content
mes[locale] + '/' + this.extshortname + '/'; install.registerchrome(install.locale | installtype, jarpath, regpath); } // register skins for (var skin in this.extskinnames) { var regpath = 'skin/' + this.extskinnames[skin] + '/' + this.extshortname + '/'; install.registerchrome(install.skin | installtype, jarpath, regpath); } // perform install var err = install.performinstall(); if (err == install.success || err == install.reboot_needed) { if (!this.silentinstall && this.extpostinstallmessage) { install.alert(this.extpostinstallmessage); } } else { this.handleerror(err); return; } }, parsearguments: function() { // can't use string handling in install, so use if statement instead var args = install.arguments; if (args == ...
List of Former Mozilla-Based Applications - Archive of obsolete content
ut now i believe the have a web-based tool (need reference for that) miro (formerly democracy player) video switched from xulrunner 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 ...
Localizing an extension - Archive of obsolete content
« previousnext » this article expands upon the previous samples on extension writing by adding localization support to our stock watcher extension. performing a few simple steps makes your extension much easier to localize into various languages without having to edit the xul or javascript files themselves. if you haven't already created an extension, or would like to refresh your memory, take a look at the previous articles in this series: creating a status bar extension creating a dynamic status bar extension adding preferences to an extension download the sample you can download this article's sample code so you can look at it side-by-side with the article, or to use it as a basis for your own extension. download the sample localizing strings in xul files create the n...
cert_override.txt - Archive of obsolete content
4.2.1 00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:ff:ee:dd:cc:bb:aa:99:88:77:66:55:44:33:22:11:00 u aaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa== fields fields are separated by a tab character. each line is terminated by a line feed character (unix format). 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...
Using content preferences - Archive of obsolete content
view / zoom example: "1.10000002384186" (rounding variant of "1.1") related about:config preferences: browser.zoom.full boolean, set by the menu item view / zoom / zoom text only. despite the confusion in names, this preference is not site-specific. browser.zoom.sitespecific toolkit.zoommanager.zoomvalues zoom.maxpercent and zoom.minpercent browser.download.lastdir path of a filesystem directory related about:config preferences: browser.download.lastdir the last directory for any site use downloadlastdir.jsm for access to these preferences. browser.upload.lastdir path of a filesystem directory this preference is stored and ...
Visualizing an audio spectrum - Archive of obsolete content
dio.mozframebufferlength; fft = new fft(framebufferlength / channels, rate); } function audioavailable(event) { var fb = event.framebuffer, t = event.time, /* unused, but it's there */ signal = new float32array(fb.length / channels), magnitude; for (var i = 0, fbl = framebufferlength / 2; i < fbl; i++ ) { // assuming interlaced stereo channels, // need to split and merge into a stero-mix mono signal signal[i] = (fb[2*i] + fb[2*i+1]) / 2; } fft.forward(signal); // clear the canvas before drawing spectrum ctx.clearrect(0,0, canvas.width, canvas.height); for (var i = 0; i < fft.spectrum.length; i++ ) { // multiply spectrum by a zoom value ...
Working with BFCache - Archive of obsolete content
frozen runs to completion, as it would if it were being closed, for example. after that, only scripts running on other windows can touch this window; if they modify the dom, the cached dom and window is thrown away. q: and to detect this we use pagehide/pageshow, correct? a: that's correct. the pagehide event tells you whether the page is going into bfcache; the pageshow tells you whether it's coming from bfcache. note that just because a page went into bfcache doesn't mean it'll ever come out again, like any other cache. q: hmm, so what event tells me “you'll never get a pageshow so you can drop the megabytes of info you've saved in firebug side table for that page?” a: an observer notification with the topic "inner-window-destroyed" whose subject is an nsisupportspruint64 containing th...
Other Mozilla customization pages - Archive of obsolete content
...
Conclusion - Archive of obsolete content
alling the extension, restarting mozilla, and see if it works. if the version you created in this tutorial doesn't work, compare it to this working version to help figure out the problem. future directions for development of the tutorial and/or coursework: in addition to build status, tinderbox also tells you if the cvs tree is open or closed for check-ins. how would you use javascript to determine whether the tree is open or closed and css to style the icon accordingly? mozilla applications often store their css and image files in a separate skin subdirectory within the installation directory. how would you modify the xpi structure and installer script to install these files in that subdirectory? how could you modify the extension to load the tinderbox page when you click on the statu...
Enabling the behavior - updating the status periodically - Archive of obsolete content
httprequest.open("get", "http://tinderbox.mozilla.org/seamonkey/panel.html"); gxmlhttprequest.send(null); window.settimeout(loadtinderboxstatus, 60000); } window.settimeout(loadtinderboxstatus, 1000); window.settimeout schedules functions to run at some future time. we use it inside the loadtinderboxstatus function to make that function run a second (1,000 milliseconds) after startup and a minute (60,000 milliseconds) after each invocation. this allows users to get relatively frequent updates about tinderbox without overloading the tinderbox server or slowing down mozilla with requests. our code is now ready to run, but mozilla doesn't know about it yet. to enable its functionality, we have to add a reference to our javascript code into navigator.xul, just as we put a reference to our...
Finding the file to modify - Archive of obsolete content
is defined by a single xul file (in some cases other xul files called overlays contribute portions of another window's structure). to add a tinderbox status icon to mozilla, we need to find the xul file that defines the structure of the browser window. the best way to find a xul file for a window is to use the dom inspector. the dom inspector is a tool bundled with mozilla that allows you to examine the dom of web pages and xul windows. to access it, go to the "tools" menu, select the "web development" submenu, then select the "dom inspector" item. the dom inspector will load in a new window. in the dom inspector window, go to the file menu, select the inspect a window submenu, then select the mozilla browser window item (named after the page currently loaded in the browser). the dom inspe...
Making it into a dynamic overlay and packaging it up for distribution - Archive of obsolete content
make sure that file and directory are on the top level of the archive. « previousnext » ...
install.rdf - Archive of obsolete content
version="1.0"?> <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest"> <em:id>author@oftheme.com</em:id> <em:version>2.0b1</em:version> <!-- seamonkey --> <em:targetapplication> <description> <em:id>{92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a}</em:id> <em:minversion>2.0b1pre</em:minversion> <em:maxversion>2.0b2pre</em:maxversion> </description> </em:targetapplication> <!-- front end metadata --> <em:name>my_theme</em:name> <em:description>my first theme</em:description> <!-- front end integration hooks (used by theme manager)--> <em:creator>john johnson</em:creator> <em:contributor>john johnson</em:contribut...
Creating a Microsummary - Archive of obsolete content
ame "firefox download count": <?xml version="1.0" encoding="utf-8"?> <generator xmlns="http://www.mozilla.org/microsummaries/0.1" name="firefox download count"> </generator> adding an xslt transform sheet generators must include an xslt transform sheet (also known as an xslt stylesheet) which transforms the page content into its microsummary. xslt is a powerful language for transforming documents into different representations of the same information. add the xslt transform sheet to the generator by including it within a <template> 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"> </tra...
FAQ - Archive of obsolete content
e problems. when the mozilla developers make changes like this, they increase the skin version number. this is the number that is defined in contents.rdf. test your skin with every major release of mozilla. if a message appears in the preferences window telling you that it's an old skin, you're going to have to look over the code to see what changed. developers try to keep changes like this to a minimum, but sometimes it just can't be helped. what is an access key? an access key is a keyboard shortcut to access something. in the case of skins the access key that you are defining is accessible by going to edit->preferences, appearance->themes, and then pressing a letter. c will select classic and m will select modern. ...
Dehydra Frequently Asked Questions - Archive of obsolete content
general questions where did the name dehydra come from? initially dehydra was written as an easy way to look for patterns in control flow graphs (cfgs). images of those graphs reminded me of the multiheaded hydra monster. thus de-hydra can be thought of as a decapitating tool for slaying cfgs. currently dehydra does not provide the cfg functionality, this functionality is now provided by treehydra. what is the status of gcc 4.5 support? development version of dehydra should work with gcc 4.5 on any c++ codebase. if you encounter bugs or crashes, report them. where does one report dehydra bugs? use this link to file bugs. for crashes reports attach a minimized input file. use either a source files that rely on standard headers or a compressed .ii file (pass -save-temps to gcc to get .i...
Dehydra - Archive of obsolete content
dehydra. ...
Devmo 1.0 Launch Roadmap - Archive of obsolete content
...
Download Manager improvements in Firefox 3 - Archive of obsolete content
firefox 3 offers improvements to the download manager that allow multiple progress listeners, use of the storage api for data management, download resuming, and more. in addition, you can augment or replace the download manager's user interface by implementing the new nsidownloadmanagerui interface. note: these changes will require some modest revisions to code using the download manager; several methods have had minor changes. download manager interfaces nsidownloadmanager gives applications and extensions access to the download manager, allowing them to add and remove files to the download list, retrieve information about past and present downloads, and request notifications as to the progress of downloads. nsidownload describes a file in the download queue; ...
Drag and Drop Example - Archive of obsolete content
o do anything special for the ondragover function, so no code is added in its body. the ondrop handler first uses the createelement function to create a new element of the type stored in the drag session. next, appendchild is called to add the new element to the stack, which is the target of the event. finally, we set some attributes on the new element. the position of elements in a stack is determined by the left and top attributes. the values of the pagex and pagey properties store the mouse pointer coordinates on the window where the drop occured. this allows us to place the new element at the position where the mouse button was released. this isn't quite the correct way to do this as we actually need to calculate the coordinates of the event relative to the stack. it works here because th...
Drag and drop events - Archive of obsolete content
these events are new in the current working draft of the html 5 specification. note: the drag and drop event support advertised in the firefox 3 release notes is not the same as the events described in the drag and drop section of the html 5 working draft. e.g. firefox 3 does not support the 'drag' event. this support is added in firefox 3.5, and is documented separately on the page [drag and drop]. drag sent when a drag operation begins. dragend sent when a drag operation ends. for more information about drag and drop, see the article drag and drop. ...
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
directories. if your code cannot find the gre and keeps throwing filenotfoundexceptions during the getgrepathwithproperties(...) call, check whether you already registered the gre on your system: gre registration the initembedding method kicks off the embedding process, allowing the java application to work with xpcom and mozilla. once the java application is done using mozilla, it needs to terminate the embedding process: try { mozilla.termembedding(); } catch (xpcomexception e) { // this exception is thrown if termembedding failed } working with xpcom objects now that mozilla is embedded, the java application can work with xpcom objects. the mozilla class provides several methods to facilitate this, such as getservicemanager, getcomponentmanager, and newlocalfile. in additio...
Exception logging in JavaScript - Archive of obsolete content
nce of logging "expected" errors at length into the console. javascript code is sometimes designed to throw exceptions to report a result condition back to the c++ caller. these might be perfectly normal circumstances, but the exceptions were dutifully logged nonetheless. exception reporting in firefox 3 firefox 3 improves reporting of unhandled exceptions by establishing a set of rules that determines whether or not an exception is worth reporting: any methods on interfaces annotated with the [function] attribute in idl (see, for example, nsidomeventlistener) that throw exceptions always report those exceptions into the error console. any exceptions that are generated by xpconnect -- that is, those exceptions whose result codes are defined in nsixpconnect.idl -- are always logged into the...
Extension Frequently Asked Questions - Archive of obsolete content
for thunderbird, you may also find the extension howto or faq pages helpful. if you're looking for a place to get started, try our tutorial, building an extension or mozillazine's getting started tutorial. use the extension wizard to generate a template to start with. be sure to set the development preferences. todo: add content. ...
Building Firefox with Rust code - Archive of obsolete content
this page is a rough guide for people using rust in firefox. see also the documentation on this topic on the oxidation wiki page. adding rust code we generally target stable rust, but sometimes issues temporarily require a beta or custom toolchain build. ...
Repackaging Firefox - Archive of obsolete content
upgraded. on the other hand, if you create a dex which supports all locales, you can only ship on a few, and later expand your set without any upgrade hassles. of course, this strategy only works when your strings either do not need localization, or are programmatically localizable (for example, simply adding the locale to a url, like http://<locale>.example.com/). but it's something to keep in mind when planning your locale support. preferences preferences are one of the two main things you will want to set in your extension (the other is bookmarks). there are two kinds of preferences in firefox, both set in the partner.js file: localizable preferences, which have a value of a chrome:// uri pointing to the properties file where firefox can fetch the localized value from. non-localiza...
Using microformats - Archive of obsolete content
oformat, nothing is returned. getparent() returns the parent node of the specified microformat or child of a microformat. var parentnode = microformats.getparent(node); parameters node the node whose parent you wish to retrieve. return value the parent of the specified node. returns nothing if the specified node isn't a microformat or the child of a microformat. ismicroformat() determines whether or not the specified dom node is a microformat. var flag = microformats.ismicroformat(node); parameters node the dom node to check to see if it's a microformat. return value true if the node is a microformat, otherwise false. note: this method doesnot return true if the node is a child of a microformat. see also microformats.org ...
Syncing custom preferences - Archive of obsolete content
when preferences sync is enabled, firefox sync will synchronize preferences between the same application based on a whitelist. that means preferences between firefox and fennec, for instance, are never synced. to sync preferences between firefoxes, fennecs, thunderbirds, etc., ensure the prefs are whitelisted. the whitelist is determined as follows: for each services.sync.prefs.sync.<pref> preference that is set to true, firefox sync will sync the <pref> preference. for example, if your add-on had a pref called extension.frobnaz.foobar, to have it synced, create a bool preference called services.sync.prefs.sync.extension.frobnaz.foobar and set it to true. the most convenient place for this would be your add-on's default preferences, though if you want to give the user a choice to opt-...
HTTP Class Overview - Archive of obsolete content
tions processes http response codes intercepts progress notifications nshttpconnection implements nsistreamlistener & nsistreamprovider talks to the socket transport service feeds data to its transaction object routes progress notifications nshttpconnectioninfo identifies a connection nshttptransaction implements nsirequest encapsulates a http request and response parses incoming data nshttpchunkeddecoder owned by a transaction strips chunked transfer encoding nshttprequesthead owns a nshttpheaderarray knows how to fill a request buffer nshttpresponsehead owns a nshttpheaderarray knows how to parse response lines performs common header manipulations/calculations nshttpheaderarray stores http "<header>:<value>" pairs nshttpauthcache stores aut...
Creating a Help Content Pack - Archive of obsolete content
giving the entry a unique rdf:id attribute. then, to describe that entry, you set an rdf:about attribute to the value of the entry's rdf:id, prefixed by a #. nesting as described above works exactly the same no matter how deeply or shallowly nested your entry is. nesting theoretically can work to any number of levels, but for practical reasons nesting is limited to roughly 20 levels. if you're coming anywhere close to this limit, however, you probably should be considering exactly why you need so much nesting. the table of contents file the table of contents file is the most important data source you'll create. the help viewer will display the table of contents when you start the viewer. in some versions of the viewer, it will be the only data source ever directly displayed. it's the prima...
Hidden prefs - Archive of obsolete content
, under to:, cc:, bcc:, newsgroup:, etc. for example: when that mail gets sent, approved: test@test.com will be in the message in the headers. this is a useful trick for newsgroup moderators who want moderate from mozilla. mail/news prefs "autcollect addresses" prefs from mailnews.js: // by default, only collect addresses the user sends to (outgoing) pref("mail.collect_email_address_incoming", false); pref("mail.collect_email_address_outgoing", true); pref("mail.collect_email_address_newsgroup", false); // by default, use the personal addressbook for collection pref("mail.collect_addressbook","moz-abmdbdirectory://abook.mab"); for the reasons why the defaults changed, see this document on the collected address book. there is ui for the "mail.collect_email_address_outgoing" pref. ...
Settings - Archive of obsolete content
with the above manifest the following stored properties are available in the jetpack's code: * jetpack.storage.settings.twitter.username * jetpack.storage.settings.twitter.password * jet...
Settings - Archive of obsolete content
with the above manifest the following stored properties are available in the jetpack's code: jetpack.storage.settings.twitter.username jetpack.storage.settings.twitter.password jetpack.
Storage - Archive of obsolete content
note: this page documents the jetpack prototype, which is no longer under active development. read the experiment report for what we learned from it and the blog post announcing the first sdk release for what we're up to next! simple storage an easy-to-use persistent object data store file access interface for performing file i/o settings settings persist across browser sessions and are accessible to jetpacks via simple object retrieval and assignment. ...
Clipboard Test - Archive of obsolete content
od>.name>.param:not(:last-child):after{content: ","; padding-right: .5em; } .method>.name>.param:not(:last-child):after{content: ","; padding-right: .5em; } .method>.name>.param>.name:after{content: " as "; font-weight: normal; } .method>.params{display: block; color:#555;} .method>.params>.param{display: block; margin-bottom:5px;} .method>.params>.param>.name{font-weight:bold; margin-right:.5em; min-width:80px; display:inline-block;} .method>.params>.param>.description{display:inline-block; width:300px; vertical-align:top;margin-right:30px} .method>.params>.param>.type{display:inline-block; width:100px; vertical-align:top;font-weight:bold;} .method>.params>.param>.type:before{content: "type "; color: #888; font-weight:normal;} .method>.params>.param>.default{display:inline-block; width:100px...
Menu - Archive of obsolete content
Archive › Mozilla › Jetpack › UI › Menu
face, such as a bookmark on the bookmarks toolbar. a contextmenuset object. note: sometimes jetpack.menu.context.browser.on() does not work as expected. for example, jetpack.menu.context.browser.on("*").add("foo") does not add "foo" to the tab strip's and location bar's context menus, but it does on the bookmark toolbar's context menu. to work around this limitation, try using beforeshow and examining the node that the user clicked. for example, to add an item to the tabs' context menu, try: jetpack.menu.context.browser.beforeshow = function (menu, context) { menu.reset(); if (context.node.localname === "tab") menu.add("hey, a tab!"); }; (the reason this problem exists is because document.queryselectorall() does not match anonymous content in xul. many parts of firefox's interfac...
Mac OS X Build Prerequisites/fink - Archive of obsolete content
to macports. it doesn't seem to be as well maintained (in terms of available packages) as macports, so it is strongly suggested that you use macports instead of fink. you may download the most recent version of fink that is compatible with your operating system release. fink installs in /sw by default. the installer should configure the fink environment for you, making it available in any new terminal window. if you perform a major operating system upgrade on your computer, such as an upgrade from tiger to leopard, you should remove the /sw directory and re-install fink and the packages below. libidl, glib using fink. libidl is included in the orbit installation. $ sudo apt-get update $ sudo apt-get install orbit orbit-dev glib autoconf-2.13 using fink. autoconf is installed at /sw/bin/au...
Makefile.mozextension.2 - Archive of obsolete content
>http://$(project).mozdev.org/</homepageurl> <optionsurl>chrome://$(project)/content/settings.xul</optionsurl> <abouturl>chrome://$(project)/content/about.xul</abouturl> <iconurl>chrome://$(project)/skin/mainicon.png</iconurl> <updateurl>http://$(project).mozdev.org/update.rdf</updateurl> <type>2</type> <targetapplication> <description> <id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</id> <minversion>2.0</minversion> <maxversion>9.0</maxversion> </description> </targetapplication> </description> </rdf> endef export install_rdf install.rdf: @echo generating $(project)/install.rdf @echo "$$install_rdf" > $(project)/install.rdf ###### define overlay_xul <overlay id="$(project)-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"><script src="overla...
Message Summary Database - Archive of obsolete content
is that we haven't been able to justify the very large cost of doing so because there won't be any benefit to the end-user, at least in the short term. here are some of the trade-offs: the mork file format is ascii text, but unreadable. if it were binary, there would be less complaints, and it would be smaller. the mdb interfaces are overly complex, and unfamiliar. the mork code uses a lot of terminology of its own invention, as near as i can tell (though i suspect most db code would be that way). it's difficult to fix bugs in mork. but, on the other hand, there are very few bugs in the mork code. mork loads the whole database in memory, and keeps it there. this makes it very fast to access our database objects, but it does increase memory usage. mork assumes the caller will do file locking,...
LIR - Archive of obsolete content
48 not in use immediate 49 immi int immediate 50 immq 64 bit quad immediate 51 immd double immediate 52 not in use comparisons 53 eqi integer int equality 54 lti integer signed int less-than 55 gti integer signed int greater-than 56 lei integer signed...
How to Write and Land Nanojit Patches - Archive of obsolete content
for mozilla people it's probably best done in your tracemonkey repo, for adobe people it's probably best done in your tamarin-redux repo. once the patch seems ready, copy it to the other two repositories and test it. [njn: it's possible that the other tm/tr public repo hasn't been updated from nanojit-central sufficiently recently, in which case the patch won't apply cleanly. if the breakage is minor you'll be able to fix it by hand. if it's major you'll need to do a private update of that other repo in order to test. but don't push that update, as that should only be done by a member of that public repo.] once it passes testing, file the patch to bugzilla (file a bug under the "nanojit" component in the "core" product) and get a review. generally, patches by mozilla people should be revi...
Plug-n-Hack - Archive of obsolete content
without integration between security tools and browsers, a user must often switch between the tool and their browser several times to perform a simple task, such as intercepting an http(s) request. pnh allows security tools to declare the functionality that they support which is suitable for invoking directly from the browser. a browser that supports pnh can then allow the user to invoke such f...
Configuration - Archive of obsolete content
hould be opened in the default browser, rather than in the web app. syntax is the same as for include. trayicon indicates that a system tray (notification area) icon should be displayed for the application on windows: yes or no. iconic specifies that the application should be opened in iconic state. currently support only on windows in conjunction with the trayicon, causes the application to open minimized to the system tray: yes or no. launch prism with -webapp [bundle] to load the specified web profile and install the webapp to your prism profile folder. once the webapp is installed, it can be launched using -webapp [webapp-id] and prism will skip the installation and run the webapp directly. any of the profile parameters can also be passed directly on the command line as well. example her...
Extensions - Archive of obsolete content
er to install an extension in prism, you need to follow the guidelines for building a mozilla-based extension. to support prism specifically, you'll need to add prism to the list of target applications in the extension's install.rdf file. the code snippet will look something like this: <em:targetapplication> <!– prism –> <description> <em:id>prism@developer.mozilla.org</em:id> <em:minversion>0.8</em:minversion> <em:maxversion>1.0.0.*</em:maxversion> </description> </em:targetapplication> in addition to the install manifest changes, you may want to expose your extension into the prism ui. prism does have a few ui elements, such as a toolbox, toolbar, menubar, popup menus, statusbar and a container for the browser. you can use these ui elements to merge in your extension ...
HostWindow - Archive of obsolete content
the window does have some ui components (as shown in the screenshot below). prism can be configured to show or hide several of the ui components. location bar - a readonly textbox that contains the currently displayed url. when not displayed the entire location bar section is hidden. sidebar - section of window area used to display ancillary web content, including web applications. when the sidebar is displayed, the splitter can be used to change the width or quickly collapse it. the splitter itself cannot be hidden as it is the only ui to show a collapsed sidebar. when not displayed the entire sidebar area, including the splitter are hidden. ...
Priority Content - Archive of obsolete content
ot been migrated at all appears there. book length works in progress: netscape gecko plugin api reference 1.0 original: netscape gecko plugin api reference 1.0 wiki location: gecko plugin api reference migrators: started: core javascript reference 1.5 original: core javascript reference 1.5 wiki location: core javascript 1.5 reference migrators: deb richardson in progress: transforming xml: netscape and xslt 1.0 original: transforming xml: netscape and xslt 1.0 wiki location: transforming xml with xslt migrators: serge k. keller in progress: rapid application development with mozilla original: author's page and planned host, ben's temporary host wiki location: toc and links page still under construction. migrators: nigel mcfarlane and ben karel shorter works most...
Proxy UI - Archive of obsolete content
products firefox menu: preferences > advanced tab > networking tab > connection button. thunderbird menu: preferences > advanced tab > networking tab > connection button. seamonkey menu: preferences > advanced group > proxies panel menu: right-click on offline-online button (on browser windows). camino configured in os (networking preferences) (recently added - some support for reading os and account settings.)ui elements preferences panel overview the ui is based on selecting a proxy mode, then filling out any additional needed information in "related" ui. the "ok" button saves the preferences. the preference changes selecting the proxy "mode" all product's proxy preference panels share a basic design: a radio button that selects the proxy mode, then "related proxy mode" ui...
RDF Datasource How-To - Archive of obsolete content
set of properties that you will use to express relationships between elements (resources and literals) in your data model. the first question that you must answer is "should i use an existing vocabulary, or invent my own?" a reasonable answer is, "use an existing vocabulary unless you absolutely must invent your own." this will allow your datasource to be integrated with other datasources with a minimum of effort. there are several existing vocabularies of note, including: the rdf schema specification. this vocabulary is a "meta vocabulary" that is used to specify other vocabularies. the dublin core. this vocabulary is useful for describing electronic resources. it contains elements for authorship, subject, publication date, etc. mapping your data to nodes and arcs [write me!] implementing...
Remotely debugging Firefox for Metro - Archive of obsolete content
fferent computer or a different port, enter the appropriate hostname and port number and then press "connect." in the windows 8 (metro) browser next you'll see a dialog in firefox for metro asking you to confirm the connection. press the "ok" button to continue. tip: if the remote connection times out, flip to the desktop via the desktop tile and check if windows firewall has thrown up an incoming connection permissions prompt. on the desktop next, the desktop shows you a dialog that looks something like this: this is asking whether you want to debug web content running in a browser tab, or to debug the browser code itself. you'll see one entry under "available remote tabs" for each open tab, and clicking it will attach the debugging tools to the web content hosted by that tab. if...
Remote debugging - Archive of obsolete content
mand line, and make firefox crash. when firefox crashes, a core will be placed in /cores. you can then load the core file into gdb (gdb firefox-bin corefile), and it will be as if you caught the crash while running firefox under gdb! when transferring a mac or linux core dump, you'll also have to transfer the firefox executable (and maybe more). core dumps on windows on windows you can produce a "minidump". see here for instructions on how to do so with microsoft's free debugger, windbg. debugging over bugzilla explain in the bug that you have a core file or can reproduce the crash as many times as needed. the developer can give you appropriate commands to type into the debugger. examples: 367650, 374356, 393325, 418139 debugging over irc find the developer on irc and explain that you've caug...
Frequently Asked Questions - Archive of obsolete content
but if it was, just think how much further on with our svg implementation we could be! we're always looking for help from anyone willing to lend a hand. if you're a c++ programmer interested in working on the svg implementation, please contact us and we'll be happy to help you get involved. alternatively, if you're an svg user you can help by testing the svg enabled nightlies and filing bugs with minimal testcases whenever you encounter a problem. if you can't do either of these things you should still feel free to ask us friendly questions and give us constructive feedback. who's currently working on what? other than reviewing patches and fixing the occassional bug, alex is currently taking a break from active svg development to concentrate on 'real work' and cool stuff like xtf and jssh. ...
SpiderMonkey coding conventions - Archive of obsolete content
js_newobject. extern but library-private function names use a js_ prefix and mixed case, e.g. js_searchscope. most static function names have unprefixed, mixed-case names: getchar. ...
open - Archive of obsolete content
ecurity holes, and not well tested. summary opens the file, specifying file mode and type. syntax open(mode,type) parameters mode a comma-delimited list describing the method to use to open the file, described in detail here. type a string describing the type of file being opened. description this method opens the file, preparing its resources for use by subsequent methods to examine or modify the file. certain methods of file, such as read and write should not be used when the file is not open. other methods, such as remove may not be used when the file is open. valid file types are text, binary and unicode. text indicates ascii text without nul characters. binary indicates utf-8 files. unicode indicates ucs-2 files. for all file types, carriage returns and linefeeds are t...
File object - Archive of obsolete content
e compilation of your spidermonkey engine. if you are building a standalone version of spidermonkey (see: spidermonkey build documentation), this variable can be added on the make command line, like so: cd mozilla/js/src make -f makefile.ref js_has_file_object=1 alternatively, if you are building a larger product (such as a browser) and want to include the file object, you may need to perform minor makefile surgery. summary non-standard server-side object this object lets you work files and directories on the local filesystem, and create os pipelines. creating a pipeline involves spawning arbitrary processes; this means that giving a script access to the file object is exactly equivalent to giving the script access to the unix shell or dos command interpreter. filesystem access is imp...
Standalone XPCOM - Archive of obsolete content
the contents of this standalone xpcom in general are: nspr : mozilla/nsprpub xpcom : mozilla/xpcom note 1: xpcom apis are not frozen yet. by xpcom 1.0 release they will be. note 2: xpcom standalone differs from the xpcom built with mozilla. hence cannot be used with the mozilla browser. ...
Table Cellmap - Border Collapse - Archive of obsolete content
it can have 4 values: ns_side_top ns_side_right ns_side_bottom ns_side_left the size of the smaller border that goes into that corner. if this corner is a start for a hor...
Actionscript Acceptance Tests - Archive of obsolete content
ocally, but makes it easy to differentiate between binary-only abc files and generated abcs. support directories in some cases a test may require additional files to successfully run. there are two kinds of support directories available. files to be included when compiling the test: if a test requires additional .as files to be included when compiling, a directory with the same name as the test (minus any extension) can be created. the name is case-sensitive. e.g: given a test named inheritclass.as, the user can create a directory named inheritclass and place files a.as and b.as in that directory. when the harness compiles the inheritclass.as test, the files in inheritclass will be included: java -jar asc.jar -import builtin.abc -in shell.as -in inheritclass/a.as -in inheritclass/b.as inher...
Running Tamarin performance tests - Archive of obsolete content
l.abc) -b --builtinabc location of builtin.abc -s --shellabc location of shell_toplevel.abc -x --exclude comma separated list of directories to skip -h --help display help and exit -t --notime do not generate timestamps (cleaner diffs) -f --forcerebuild force rebuild all test files -c --config sets the config string [default os-tvm] -q --quiet display minimum output during testrun -l --log also log all output to given logfile --summaryonly only display final summary --rebuildtests rebuild the tests only - do not run against vm --showtimes shows the time for each test --ascargs args to pass to asc on rebuild of test files --vmargs args to pass to vm --timeout max time to run all tests ...
Tamarin Releases - Archive of obsolete content
this page tracks tamarin source code releases, past, present and future. ...
Tamarin - Archive of obsolete content
™ 3 (a superset of ecmascript edition 3) and is embedded within the adobe® flash® player versions 9 and later. tamarin's jit-compiler, nanojit, is also used in tracemonkey ergo spidermonkey, which is mozilla’s javascript engine in firefox. tamarin is available under the mpl/gpl/lgpl tri-license. releases release tracking information on current, past, and upcoming releases of tamarin. documentation adobe actionscript virtual machine 2 (avm2) overview (pdf, 400k) the instructions, architecture, and file format supported by the avm2. see also the possible errata. tamarin build documentation how to get, build, and use tamarin. tamarin build system documentation documentation on how the tamarin b...
The life of an HTML HTTP request - Archive of obsolete content
http: in this case) and locates the correct nsiprotocolhandler (in this case nshttphandler) and asks it for a nsichannel (nshttpchannel). the channel represents the connection to the server, and is the source of the html data stream. (3) when data is starting to come from the webserver the nsichannel calls the onstartrequest in the documenloader. now the channel knows the content type of the incoming data, so the documentloader can find an nsidocumentloaderfactory for the "text/html" content type (in this case an nslayoutdlf). this factory is then told to create a nsicontentviewer. the factory creates a contentviewer. in most cases (including this) it also creates a nsidocument (nshtmldocument) and binds it to the contentviewer. the contentviewer is then embed():ed into the contentviewercont...
Treehydra Manual - Archive of obsolete content
alues, and the flow semantics of gimple statements, and the library will do all of the substate tracking and fixed-point solving. the library is at unstable/esp.js. there is a sample application that checks for double-locking in a simple mutex api in test/esp_lock.js. abstract interpretation is a big topic, which is not yet fully documented here. for now, here is an explanation of some of the terminology that is often confusing: concrete value. a value in the programming language being analyzed. e.g., (int) 3. abstract value. a value used in the analysis script that represents a set of concrete values. e.g., nonzero. in esp, these are user-defined. concrete state. a memory state in the programming language being analyzed. in other words, a mapping from program variables to concrete values. ...
Uriloader - Archive of obsolete content
uriloader: responsible for the dispatch of content to content handlers as it comes in from the network. overview of a uri load up though dispatch to a content handler helper application tech talk mime type determination in mozilla overview of how downloads work ...
Venkman Introduction - Archive of obsolete content
which will execute a single line of javascript and stop, step over can be used to step over a impending function call, and return control to the debugger when the call returns. step out executes until the current function call exits. click the "pause" link again on the fishcam page to resume the demo. this starts the dhtml down the other codepath in start() and makes the fishes start swimming again. as you can see, this is a very modest introduction to the functionality of the javascript debugger and the complexity that scripts can have. but the steps described here can give you a basic feel for the debugger if you haven't already had some experience using it, and they provide the basis for the more interesting and practical examples in the articles that follow this one. the bes...
Venkman - Archive of obsolete content
a install distribution since october 2001, as well as an extension package in xpi format. 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. learning the javascript debugger venkman written by svend tofte to the javascript programmers who are not familiar with other debugging tools. venkman faq answers to common questions on venkman. venkman internals notes on venkman source code. venkman development page older news and releas...
DOM Interfaces - Archive of obsolete content
return value element - the return value of getanonymouselementbyattribute is an anonymous descendant of the given element with matching attribute name and value. getbindingparent the getbindingparent method is used to obtain the bound element with the binding attached that is responsible for the generation of the specified anonymous node. this method enables an author to determine the scope of any content node. when content at the document-level scope is passed in as an argument, the property's value is null. parameters node - the node for which the bound element responsible for generation is desired. return value element - the return value of getbindingparent is the element responsible for the given anonymous node. loadbindingdocument the lo...
Example Sticky Notes - Archive of obsolete content
ructor><![cdata[ /** * the code below will be called one time only after * the binding is successfully prepared and bound. * "this" in this context refers to the bound element. */ // your code goes here ]]></constructor> <destructor><![cdata[ /** * the code below will be called one time only before * binding is unbound. you cannot cancel this event, * but you may accomplish some last minute clean up. * "this" in this context refers to the bound element. */ // your code goes here ]]></destructor> <field name="priority"><![cdata[ /** * new "real" property for the bound element. * within this block the content is interpreted * as javascript code. the result of this code * evaluation (if any) will be used as initial value. */ "normal"; ]]></field> <property name="i...
XBL 1.0 Reference - Archive of obsolete content
element, an implementation of new methods and properties that become accessible from the bound element, and anonymous content that is inserted around the bound element. there are numerous adjustments in the current implementation in comparison of earlier xbl proposals, and not all of them are reflected yet in this document. the documentation process is still in progress: please keep it in your mind while using the provided information. xbl elements xbl 1.0 elements are in the http://www.mozilla.org/xbl namespace. 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.styl...
XML in Mozilla - Archive of obsolete content
xht xhtml xml text/html html htm html the entire document need not be xhtml. you can use xhtml elements inside an arbitrary xml document by using the xhtml namespace. see the testing and qa section for samples. the correct xhtml namespace is http://www.w3.org/1999/xhtml please note that the xhtml entities, like &auml;, work only in conforming xhtml documents that have a valid xhtml formal public identifier (or in other words, a doctype section with a public identifier). xhtml entities will not work in arbitrary xml documents, not even if the xhtml namespace is used. the public identifiers that are recognized are: -//w3c//dtd xhtml 1.0 transitional//en -//w3c//dtd xhtml 1.1//en -//w3c//dtd xhtml 1.0 strict//en -//w3c//dtd xhtml 1.0 fr...
File.macAlias - Archive of obsolete content
that is installed locally. ...
File.windowsShortcut - Archive of obsolete content
test", vi, 0); f = getfolder("windows"); g = getfolder("temporary"); addfile( "miscshortcut", "2.2.2.2", xpisrc, f, xpisrc, true); target = getfolder(f, xpisrc); shortcutpath = getfolder("program"); err = file.windowsshortcut( target, shortcutpath, "misc shortcut", g, "", target, 0); logcomment("file.windowsshortcut returns: " + err); if (0 == getlasterror()) performinstall(); else cancelinstall(); ...
Install.addFile - Archive of obsolete content
install.addfile the install object's addfile method is the standard way to queue files for installation. var xpisrc = "file.txt"; initinstall( "adding a file", "testfile", "1.0.1.7", 1); f = getfolder("program"); setpackagefolder(f); addfile(xpisrc); if (0 == getlasterror()) performinstall(); else cancelinstall(); ...
dirRename - Archive of obsolete content
dirrename renames a directory in place. method of file object syntax int dirrename( filespecobject directory, string newname ); parameters the dirrename method has the following parameters: directory a filespecobject representing the directory to be renamed. newname the new terminal (or leaf) name of the directory. returns an integer error code. for a list of possible values, see return codes. ...
diskSpaceAvailable - Archive of obsolete content
your files (see example below). you can use a string representing any file on the disk you want to check, and xpinstall will resolve the reference to the partition itself. example var diskamtneeded = 10000; f = getfolder("program"); diskspace = file.diskspaceavailable(f); g = getfolder(f, "myfile.txt"); if (diskspace > diskamtneeded) { err = addfile(..., ... g, ...); if (err == 0) performinstall(); else cancelinstall(); } else { alert("not enough disk space. no install); cancelinstall(); } ...
execute - Archive of obsolete content
cutablefile a filespecobject representing the local file already on disk to be executed. note that file names are case sensitive. aparameters an optional parameter string that is passed to the executable. (ignored on mac os) returns an integer error code. for a list of possible values, see return codes. description the specified file is not actually executed until the performinstall method is called. see performinstall for more information about queued commands during the installation process. example f = getfolder("program", "mytexteditor.exe"); err = file.execute(f, "myfile.txt"); // indicates that 'myfile.txt' will be // opened in the editor ...
rename - Archive of obsolete content
summary renames a specified file in place. method of file object syntax int rename( filespecobject file, string newname ) parameters the rename method has the following parameters: file a filespecobject representing the file to be renamed. newname the new terminal (or leaf) name of the file. returns an integer error code. for a list of possible values, see return codes. ...
windowsGetShortName - Archive of obsolete content
method of file object syntax string windowsgetshortname( object localdirspec ) parameters the windowsregisterserver method has the following parameter: localdirspec a filespecobject representing a directory obtained by getcomponentfolder or getfolder. returns a string with the windows shortname. if the path already conforms to 8.3, the return value is null. ...
init - Archive of obsolete content
init initializes an init object. method of installversion object syntax init ( int maj, int min, int rev, int bld ); init ( string version ); parameters the init method has the following parameters: maj the major version number. min minor version number. rev revision number. bld build number. version a string representing version information in the format "4.1.2.1234". when maj, min, rev, and bld are provided as parameters, all four parameters are required, but all of them can be zero. ...
addDirectory - Archive of obsolete content
optional field; reserved for future use. pass 0 as the default value. returns an integer error code. for a list of possible values, see return codes. in some situations, adddirectory may return other errors. description the adddirectory method puts the files in the specified directory in a temporary location. to move the files and all other subcomponents to their final location, call the performinstall method after you've successfully added all subcomponents. also see the note about binaries on the macintosh platform in addfile. ...
cancelInstall - Archive of obsolete content
script can, in fact, return any valid integer. ...
confirm - Archive of obsolete content
ke any assumptions on the button placement - the underlying implementation can freely decide where each of the three buttons is placed. the following examples show the result of calling confirm() with three buttons 0='a', 1='b' and 2='c'. firefox on linux mozilla application suite on win32 it is therefore recommended to only use two buttons wherever possible, and to keep in mind that button 1 has the same return value as "window closed" (see below). abutton0title custom title for button 0. abutton1title custom title for button 1. abutton2title custom title for button 2. acheckmsg a string to display as a checkbox label. acheckstate an object with a boolean value property representing the sta...
execute - Archive of obsolete content
the file to finish before it resumes. default is false. see note below. the blocking parameter is not available as part of this method in versions of netscape before 6.1/mozilla 0.9.3. returns an integer error code. for a list of possible values, see return codes. description the execute method extracts the named file from the xpi file to a temporary file name. your code must call the performinstall method to actually execute the file. you can use this method to launch an installshield installer or any install executable file stored in a xpi file. executing installed files note: if the file you wish to execute is one you are installing (as opposed to an installer executable that you plan to delete once it runs), then use the execute method on the file object instead. file.execute() ex...
getFolder - Archive of obsolete content
in desktop" "win desktop common" "win program files" "win programs" "win programs common" "win startmenu" "win startmenu common" "win startup" "win startup common" "win system" the "file:///" form is only valid when the subdirectory parameter is used. it must be in file: url format minus the "file:///" part. for example, mydir = getfolder("file:///", "c|/mysoftco/somedir"); note that forward slashes are used, regardless of the platform. the folders whose names start with "win", "mac", or "unix" are specific to those platforms. you should be careful about using one of those directories, as it makes your installation platform-specific. example to get an object representing th...
patch - Archive of obsolete content
an error without applying the patch. after patch applies a patch, it compares a checksum.of the resulting file against a checksum stored in the gdiff file. if the checksums do not match, the original version of the file is preserved, the patched version of the file is discarded, and an error code is returned. any single installation process can apply multiple patches to the same file. if performinstall indicates that a reboot is necessary to complete the installation, patch may not work in subsequent xpinstall processes until the reboot is performed. ...
Methods - Archive of obsolete content
for working with the windows registry. initinstall initializes installation for the given software and version. loadresources returns an object whose properties are localized strings loaded from the specified property file. logcomment add a comment line to the install log. patch applies a set of differences between two versions. performinstall finalizes the installation of the software. refreshplugins refreshes the list of plug-ins registered for the browser. registerchrome registers chrome with the chrome registry. reseterror resets a saved error code to zero. setpackagefolder sets the default package folder that is saved with the root node. ...
Install Object - Archive of obsolete content
file objects and passing those object refs to addfile as many times as necessary. perform installation check that the files have been added successfully (e.g., by checking the error return codes from many of the main installation methods, and go ahead with the install if everything is in order: performorcancel(); function performorcancel() { if (0 == getlasterror()) performinstall(); else cancelinstall(); } for complete script examples, see script examples. ...
writeString - Archive of obsolete content
value. returns true if successfully scheduled, otherwise, false. description the writestring method is similar to the windows api function writeprivateprofilestring. to delete an existing value, supply null as the value parameter. unlike the writeprivateprofilestring function, this method does not support using a null key to delete an entire section. values are not actually written until performinstall is called. example to set the name of the wallpaper file from the desktop section of the win.ini file, use this call: ini = getwinprofile (getfolder("windows"), "win.ini"); ini.writestring ("desktop", "wallpaper", "newpathname"); ...
WinReg Object - Archive of obsolete content
to operate with hkey_classes_root as its root key. to use a different root key, use the setrootkey method. typically values in the windows registry are strings. to manipulate such values, use the getvaluestring and setvaluestring methods. to manipulate other values, use the getvalue and setvalue methods. reading registry values is immediate. however, writing to the registry is delayed until performinstall is called. ...
XPInstall API reference - Archive of obsolete content
bjects install properties methods adddirectory addfile alert cancelinstall confirm deleteregisteredfile execute gestalt getcomponentfolder getfolder getlasterror getwinprofile getwinregistry initinstall loadresources logcomment patch performinstall refreshplugins registerchrome reseterror setpackagefolder installtrigger no properties methods compareversion enabled getversion install installchrome startsoftwareupdate installversion properties methods compareto init tostring file ...
Installer Script - Archive of obsolete content
,"classic.jar"),"skin/classic/global/"); 56. registerchrome(skin | delayed_chrome, getfolder(cf,"classic.jar"),"skin/classic/messenger/"); 57. registerchrome(skin | delayed_chrome, getfolder(cf,"classic.jar"),"skin/classic/navigator/"); 58. registerchrome(skin | delayed_chrome, getfolder(cf,"classic.jar"),"skin/classic/aim/"); 59. if (err==success) 60. { 61. err = performinstall(); 62. logcomment("performinstall() returned: " + err); 63. } 64. else 65. { 66. cancelinstall(err); 67. logcomment("cancelinstall() due to error: " + err); 68. } 69. } 70. else 71. cancelinstall(insufficient_disk_space); ...
A XUL Bestiary - Archive of obsolete content
ds-based, and yet in some way, the event handlers written once in javascript and living in the xul interface are getting very serious things done down in the application core. things like socket interfaces, editing, mail/news, security. the technologies that make this possible are perhaps the least understood of the phalanx of innovations that is mozilla. in addition to the small matter of programming these serious things in c++ and compiling them platform for platform, the architects and developers of mozilla use three "xp" technologies to link the core with the interface. xpcom is not a programming language but an approach to programming (in c++, say) that provides for a truly cross-platform component object model, whence the technology gets its name. based on com, xpcom insists that chunks...
alwaysopenpopup - Archive of obsolete content
...
checked - Archive of obsolete content
« xul reference home checked type: boolean indicates whether the element is checked or not. use hasattribute() to determine whether this attribute is set instead of getattribute(). for buttons, the type attribute must be set to checkbox or radio for this attribute to have any effect. ...
containment - Archive of obsolete content
« xul reference home containment type: uri this attribute specifies rdf properties (an rdf predicate) that indicate that a resource is a container. when generating content from a template this is used to determine which resources from the datasource are containers and thus can have child nodes and which ones are not containers. this attribute should be placed on the same element that the datasources and the ref attribute is on. it may be set to a space-separated list of rdf properties or resources. ...
firstdayofweek - Archive of obsolete content
...
flex - Archive of obsolete content
Archive › Mozilla › XUL › Attribute › flex
« xul reference home flex type: string (representing an integer) indicates the flexibility of the element, which indicates how an element's container distributes remaining empty space among its children. flexible elements grow and shrink to fit their given space. elements with larger flex values will be made larger than elements with lower flex values, at the ratio determined by the two elements. the actual value is not relevant unless there are other flexible elements within the same container. once the default sizes of elements in a box are calculated, the remaining space in the box is divided among the flexible elements, according to their flex ratios. specifying a flex value of 0 has the same effect as leaving the flex attribute out entirely. ...
height - Archive of obsolete content
the css height property may also be used. ...
image - Archive of obsolete content
« xul reference home image type: uri the uri of the image to appear on the element. if this attribute is empty or left out, no image appears. the position of the image is determined by the dir and orient attributes. example <menuitem label="foo" class="menuitem-iconic" image="something.png"/> see also image element ...
menuactive - Archive of obsolete content
...
menuitem.type - Archive of obsolete content
radio the menuitem becomes part of a radio group. ...
mousethrough - Archive of obsolete content
if this attribute is not specified, the value is inherited from the parent of the element. if no ancestor has the mousethrough attribute set, the default value is never. always mouse events are transparent to the element. this means that the element will not receive any mouse events due to either clicking or movement. child elements may override this if they specify mousethrough="never". never mouse events are passed to the element as normal. ...
noinitialfocus - Archive of obsolete content
if true, the element will not receive initial focus. ...
notification.type - Archive of obsolete content
info a notification that is of lesser importance. ...
pending - Archive of obsolete content
« xul reference home pending type: boolean this attribute is set to true if the tab is currently in the process of being restored by the session store service. once the tab is restored, this attribute is removed. you can determine if a tab is being restored by checking to see if hasattribute("pending") is true. if the user has turned on the "don't load tabs until selected" preference, the pending attribute is set on tabs until they get loaded. ...
popup.position - Archive of obsolete content
this allows you to place the popup on one side of a button. note that a context menu will never respect this attribute, always appearing relative to the mouse cursor. this value can be specified either as a single word offering pre-defined alignment positions, or as 2 words specifying exactly which part of the anchor and popup should be aligned. if specified as 2 words, the value indicates which corner or edge of the anchor (the first word) is aligned which which corner of the popup (the second word). ...
progressmeter.mode - Archive of obsolete content
« xul reference home mode type: one of the values below a determinedprogressmeter is used in cases where you know how long an operation will take. an undeterminedprogressmeter can be used when you don't and will typically be drawn as a spinning barber pole. determined the progress meter uses its value attribute to determine the amount of the bar that is filled in. undetermined the progressmeter is indeterminate. ...
sizemode - Archive of obsolete content
can have one of the following values: maximized the window is maximized, and occupies the full size of the screen. normal the window appears in a normal state at the desired size. this attribute is used to save and restore the state of a window (together with the persist attribute) and for css styles (e.g. to hide the resizer grippy on maximized windows). note: when a window is minimized, the sizemode attribute is not updated. this is done so that if a window is closed while minimized, its persisted sizemode attribute wouldn't be minimized. setting this attribute does not change the window state. use window.maximize(), window.restore(), or window.minimize() to change the window state. to get the window state from javascript code, use window.windowstate. listen to the size...
substate - Archive of obsolete content
since collapse="both" is a gecko 1.9+ feature, this will have no effect on earlier versions. ...
textbox.type - Archive of obsolete content
autocomplete. for more information about autocomplete textboxes, see the autocomplete documentation (xpfe [thunderbird/seamonkey]) (firefox) number a textbox that only allows the user to enter numbers. in addition, arrow buttons appear next to the textbox to let the user step through values. there are several attributes that allow the number textbox to be configured, including decimalplaces, min, max, increment, wraparound, hidespinbuttons, and textbox.value. password a textbox that hides what is typed, used for entering passwords. search a textbox intended for searching. the command event will fire as the user modifies the value. a listener for the command event should update search results. if the searchbutton attribute is set to true, the command event is only fired if the us...
textbox.value - Archive of obsolete content
« xul reference home value type: string the default value entered in a textbox. the attribute only holds the default value and is never modified when the user enters text. to get the updated value, use the value property. for number boxes, the default is 0 or the minimum value returned by the min property, whichever is higher. see also value ...
timepicker.increment - Archive of obsolete content
« xul reference home increment type: integer indicates the number of minutes to skip each time the arrows are pressed. this should be used in combination with setting hideseconds to true. ...
toolbarbutton.title - Archive of obsolete content
see also title ...
treecell.mode - Archive of obsolete content
« xul reference home mode type: one of the values below for columns that are progress meters, this determines the type of progress meter to use. none no progress meter is displayed. the cell text is displayed instead. normal the cell uses its value attribute to determine the amount of the bar that is filled in. undetermined the progressmeter is indeterminate. ...
userAction - Archive of obsolete content
« xul reference home useraction type: one of the values below this attribute will be set to the action the user is currently performing. possible values: none the user is not interacting with the textbox. typing the user is typing into the textbox. scrolling the user is scrolling through the textbox. ...
width - Archive of obsolete content
the css width property may also be used. in this example, the preferred width of the inner hbox will be displayed at 40 pixels. ...
Accessing Files - Archive of obsolete content
via a file object and not via string paths. this allows files to used in a portable way. because string paths are not used, references to files in a file object are made relative to some starting directory. a number of starting directories may be used, for instance, the user's home directory, the desktop, the system's temporary folder, and so forth. once one of these starting directories is determined, a file reference may be created relative to this. a common case is to write a file in the directory that holds the user's preferences. this is a convenient location where an extension might save a file it needs to use. this directory is referred to as the user's profile directory. to get a reference to a file object use nsiscriptableio.getfile(). the following example will retrieve a reference...
Working With Directories - Archive of obsolete content
each item, nsifile.isfile() is called to check if an item is a file and lastmodifiedtime (nsifile.attributes) attribute is compared with the time of the lastmod reference. if the time is higher, the lastmod variable is updated as needed. the result is that lastmod will be set to the file with the latest modification time. nsifile.isfile() is used to ensure that the modification times are only examined for files, and not subdirectories. but you could iterate over subdirectories as well. the following example returns an array of all of a directory's subdirectories: function getsubdirs() { var arr = []; var items = io.getfile("home", "").directoryentries; while (items.hasmoreelements()) { var item = items.getnext(); if (item.isdirectory()) arr.push(item); } return arr; ...
Moving, Copying and Deleting Files - Archive of obsolete content
keep its existing name, use a null string for the second argument. var file = io.newfile("home", "myfile.txt"); var destination = io.newfile("temporary", ""); file.moveto(destination, ""); the second argument to nsifile.moveto() is an empty string to indicate that the same filename should be used. specify a name for this argument to modify the filename while moving. this would be used when renaming a file within the same directory. when moving a file within the same directory, the destination argument may be null. for instance, the following example renames a file within the same directory: file.moveto(null, "hello.txt"); if the destination file already exists, nsifile.moveto() replaces the existing file. for this reason, you may wish to check if the file exists using nsifile.exists() b...
findbar - Archive of obsolete content
cess key for the "highlight" toolbar button in the findbar. matchcaseaccesskey type: string the access key for the "match case" checkbox in the findbar. properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width browser type: browser element lets you set and get the browser in which the findbar is located. findmode type: integer read only. the find mode in use. possible values are: find_normal (0): normal find find_typeahead (1): t...
International characters in XUL JavaScript - Archive of obsolete content
y any language of the world. for example, they can contain a line: var text = "ein schönes beispiel eines mehrsprachigen textes: 日本語"; this mixes german and japanese characters. earlier versions always interpreted js files loaded from xul as iso-8859-1 (latin-1), in both local and remote cases. unicode escapes, as discussed below, have always worked. how the character encoding is determined in gecko 1.8 and later when the javascript file is loaded from a chrome:// url, a byte order mark (fixme: )(bom) is used to determine the character encoding of the script. 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). by default this will use utf-8, which can represent virtually all ch...
List of commands - Archive of obsolete content
operties cmd_bm_rename cmd_bm_selectall cmd_bm_setnewbookmarkfolder cmd_bm_setnewsearchfolder cmd_bm_setpersonaltoolbarfolder cmd_bm_sortfolder cmd_bm_sortfolderbyname cmd_close cmd_closeothertabs cmd_closewindow cmd_copy cmd_copyimage cmd_copylink cmd_cut cmd_delete cmd_editpage cmd_findtypelinks cmd_findtypetext cmd_gotoline cmd_handlebackspace cmd_handleshiftbackspace cmd_minimizewindow cmd_neweditor cmd_neweditordraft cmd_neweditortemplate cmd_newnavigator cmd_newnavigatortab cmd_newtabwithtarget cmd_openhelp cmd_paste - paste a selection from the clipboard cmd_printsetup cmd_quit cmd_redo cmd_savepage cmd_scrollpagedown cmd_scrollpageup cmd_selectall cmd_switchdocumentdirection cmd_switchtextdirection cmd_textzoomenlarge cmd_textzoomreduce cmd_te...
appendNotification - Archive of obsolete content
, image , priority , buttons, eventcallback ) return type: element create a new notification and display it. if another notification is already present with a higher priority, the new notification will be added behind it. label - label to appear on the notification. this should be either a string, or, from gecko 37 onwards, you can pass a documentfragment with rich content as well. 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. value - value used to identify the notification image - url of image to appear on the notification. if "" then an icon appropriate for the priority level is used. priority - notification priority; see priority levels. buttons - array of button descriptions to appear o...
showPopup - Archive of obsolete content
used to further control where the popup appears relative to the element. the anchor argument corresponds to the popupanchor attribute on the element. the align argument corresponds to the popupalign attribute on the element. the anchor and align arguments are ignored if either x or y are not -1. 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. the popuptype should be one of the strings popup, context, or tooltip. each type of popup is intended to be displayed only temporarily; they are not expected to be displayed permanently. ...
Menus - Archive of obsolete content
event directly. <command id="cmd_open" oncommand="alert('open a file!');"/> ... <menuitem label="open" accesskey="o" command="cmd_open"/> the command attribute should be set to the id of a command element within the same document, in this case 'cmd_open'. the command event will be fired on the command element instead of the menuitem. this is useful when you wish to have several elements performing the same action, for example a menuitem on a menubar, a context menu, and a toolbar button, because you can place the code to execute only once on the command and hook each element up to the command. menuitems also support displaying shortcuts associated with the menuitem, as well as icons beside the label. for details about adding shortcut keys to menus, see adding shortcut keys to menu items.
MoveResize - Archive of obsolete content
se attributes are persisted the values will be restored when the window is displayed again. for instance, the following example will move a popup to the upper left corner of the screen: popup.moveto(0, 0); the position may be shifted so as not to cover user interface elements provided by the operating system, such as the menu bar or the task bar. resizing a popup the size of a popup is determined automatically based on the content inside the popup. for instance, the size of a menu will be large enough to fit all of the items within the menu. sometimes, a menu will be larger than the available space on the screen; in this situation, the menu may be moved such that it will fit on screen. for instance, instead of appearing below the menu label, the menu popup might appear above the label. ...
PopupEvents - Archive of obsolete content
the parent menu will receieve a popupshowing event whenever it opens, or any submenus open. for example: <menu label="file"> <menupopup onpopupshowing="if (event.target == this) adjustfilemenu(this);"> <menu label="open"> <menupopup> <menuitem label="file..."/> <menuitem label="page"/> </menupopup> </menu> </menupopup> </menu> the target of the event is examined to ensure that the event is for the desired menupopup. otherwise, the adjustfilemenu function would be called whenever the outer menupopup is opened and when the inner menupopup is opened. the bubbling of events applies to all popup events. the popupshown event the popupshown event is fired once a popup is already visible. when calling either the openpopup or openpopupatscreen methods, the popu...
Tooltips - Archive of obsolete content
upshowing event listener and adjusting the tooltip as needed. the popupshowing event will be fired on the tooltip element just before the tooltip appears. for example: <tooltip id="iconic" onpopupshowing="this.lastchild.value = document.tooltipnode.label;"/> the document.tooltipnode property of the document holds the element that the mouse is hovering over. in this example, this property is examined to retrieve the label of the element that the mouse is over. this label is then set as the value of the last child of the tooltip. in the earlier example, the last child of the tooltip is a label. the effect is that the value of the label within the tooltip will change based on the element that the mouse is moved over. tooltips in trees as the entire body of the tree is displayed using a sing...
Popup Guide - Archive of obsolete content
associated with an element. to open a popup using script use the openpopup method or the openpopupatscreen method. for detailed information about how to open a popup see opening a popup or opening a menu. closing a menu or popup for information about closing a popup, see closing a popup or closing a menu. how popups are placed to read about how the position of a popup on screen is determined, and how to align popups to other elements, see positioning popups. determining if a popup is open to determine if a popup or menu is open, see determining if a popup is open. moving a popup popups may be moved using the moveto method. see moving a popup. resizing a popup the size of a popup may be adjusted using the sizeto method. see resizing a popup. attaching menus to a b...
currentIndex - Archive of obsolete content
ee. for trees with focus, the caret's position is indicated by the focus ring, but unfocused trees won't show a focus ring, naturally. for unfocused trees, the (undrawn) caret's position can still be obtained by this property. if the caret isn't present for any row (for example, because the tree has never been focused), the value will be -1. you cannot rely on this property to change or determine a tree selection, except for trees with seltype="single". (all trees have seltype="multiple" by default.) to reliably change or determine a selection, instead use the nsitreeselection interface methods available via tree.view.selection. example // one way of retrieving the text of a cell. <script language ="javascript"> function treerowclicked(){ var tree = document.getelementbyid("...
eventNode - Archive of obsolete content
...
is24HourClock - Archive of obsolete content
...
securityUI - Archive of obsolete content
...
view - Archive of obsolete content
Archive › Mozilla › XUL › Property › view
for a complete list of view functions, see the nsitreeview interface. ...
visibleTabs - Archive of obsolete content
...
Additional Template Attributes - Archive of obsolete content
and ref attributes also differ for each usage, so it is possible to use a shared template to display the same structure multiple times but with different starting nodes in each case. the generated content is always inserted into the root node, in this example the listbox, not inside the template. declaring the container and member variables normally, the container and member variables are determined by the template builder automatically. the container or starting node variable is specified in the <content> tag inside a query, while the member variable is determined by the value of the uri attribute inside the action body. it is also possible to be explicit about the two variables by using two attributes on the <template> element. <template container="?first" member="?item"> the container...
Building Hierarchical Trees - Archive of obsolete content
resource a container (for this rdf datasource, this will usually be an rdf seq), or use the containment attribute to specify additional properties that indicate containership. if a particular photo had a value for one of the properties listed in the containment attribute, it would be accepted as a container, and the user could open the row. 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. here is an example for the streets datasource: <tree flex="1" datasources="template-guide-streets.rdf" ref="http://www.xulplanet.com/rdf/myneighbourhood" flags="dont-build-content" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> <treecols> <treecol id="address" primary="true" label=...
Introduction - Archive of obsolete content
ource rdf:local-store is always included in the composite. the local store is a datasource which is usually used to hold state information such as window sizes, which columns in a tree are showing, and which tree items are open. you can query for any data in the local store in a template though this is rarely done. sometimes, you will want to specify the datasource to be used later, possibly determined dynamically by a script. the special uri rdf:null is used to indicate that you intend no datasources, or an empty datasource. this special uri will also work even for non-rdf types, so feel free to use it when needed. it effectively means, use no datasource for this template, which will likely result in no output being generated. next » ...
Multiple Queries - Archive of obsolete content
o of the results above are actually for the same photo (canal.jpg). the template builder removes any duplicate items before generating content. it does this by only allowing the match for the earliest query. that is, the canal.jpg generated by the second query is removed, since an earlier query (the first query) already generated a match for that result. one important distinction is that the determination of duplicates is only based on the member variable, in this case the ?photo variable. it doesn't matter whether other variables are the same or not. if you look at the example again, you might notice that the canal photo that matches the first query has appeared in-between the other two photos, even though those photos are generated from the second query. the builder hasn't put all the match...
Recursive Generation - Archive of obsolete content
tem, 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. this will correspond to the id on the appropriate element in the generated content above. to begin, b is evaluated and seeded with the right value: (?start = http://www.xulplanet.com/rdf/b) the <triple> statement is then examined, however, item b doesn't have a relateditem arc out of it, so the result is rejected. since there are no potential results, the builder doesn't generate anything. a similar situation will occur for item d. however, for item c, the triple does match an item, so the data will be added to the potential result: (?start = http://www.xulplanet.com/rdf/c, ?relateditem = http://www.xulplanet.com/rdf/d)...
Simple Example - Archive of obsolete content
the builder will first fill in as many variables as it can. 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 va...
Simple Query Syntax - Archive of obsolete content
lass="box-padded" uri="rdf:*"> <image src="rdf:*"/> <label value="rdf:http://purl.org/dc/elements/1.1/title"/> </vbox> </template> there is no <query> or <action> element used. instead, the builder uses a default query, and the action is placed directly inside the <template> element. you can see that this code is much simpler than the full syntax. to understand how this works, let's examine how the builder processes a simple query. first, it evaluates the default query as above, except that no variables are used, or at least, not ones that are used externally. in reality, the builder could be considered to convert a simple query into an extended query, so that it can be processed in the same way. after the default query statements are evaluated, the data network will look something...
Template Builder Interface - Archive of obsolete content
call the builder's refresh method: tree.builder.refresh(); this will reload the datasource attached to the template. if there is more than one datasource, as above, all of them will be reloaded. due to the nature of the way templates are updated, you don't usually need to rebuild a template after a refresh call, although there may situtations where this will be necessary. if you do plan on determining the datasources dynamically, it is common to start with an empty datasource using the special uri 'rdf:null'. <tree datasources="rdf:null" ref="http://www.xulplanet.com/rdf/myphotos"> this will create a composite datasource with no datasources in it. this syntax is necessary as otherwise you wouldn't be able to specify a value for the datasources attribute, and a template builder would not be...
Things I've tried to do with XUL - Archive of obsolete content
ntheight properties (see http://www.mozilla.org/docs/dom/domr...entheight.html); no equivalent exists for xul. enn: most people would use the box object width and height properties, or do you want something else? vlad: the boxobject width/height are the actual width and height of the box, regardless of the actual visible portion of the box (clipped by the window borders, for example). this is assuming no scrolling is going on. resize event problems going with the inability to obtain the clientwidth/clientheight of xul elements, it's impossible to handle the "resize" event yourself to grow/shrink content as needed -- as you grow the content, when you shrink the window, the content will simply be clipped (because now it has a bigger size than the window). you have no way of finding out what ...
Toolbar customization events - Archive of obsolete content
is delivered when the user makes a change to a toolbar while editing the toolbars, either by dragging an item to the toolbar or by dragging an item out of it. aftercustomization this event is delivered when the user closes the toolbar customization panel. in all cases, the event.target is the toolbox being customized. you can look at the contents of that element and its children to determine what changes were made. example in this example, we watch for toolbar changes. window.addeventlistener("beforecustomization", customizestart, false); window.addeventlistener("aftercustomization", customizeend, false); window.addeventlistener("customizationchange", customizechange, false); function customizestart(e) { let thetoolbox = e.target; /* now we know the user has started customizing...
Adding Style Sheets - Archive of obsolete content
visible initially. you could still put this in a separate style sheet if you really wanted to. a class was added to the spacers so that they can be referred to. a style sheet also needs to be created. create a file findfile.css in the same directory as the xul file. (it would normally be put into a separate skin). in this file, we'll add the style declarations, as shown below: #find-text { min-width: 15em; } #progmeter { margin: 4px; } .springspace { width: 10px; } .titlespace { height: 10px; } notice how these styles are equivalent to the styles we had before. however, it is much easier for someone to change the look of the find files dialog now because they could add or modify the style declarations by either modifying the file or by changing the skin. if the user changes...
Advanced Rules - Archive of obsolete content
n the weather example above we could add the following binding: <bindings> <binding subject="?city" predicate="http://www.xulplanet.com/rdf/weather#temperature" object="?temp"/> </bindings> this binding will grab the temperature resource of each city and assign it to the 'temp' variable. this is similar to what a triple does. the difference is that a binding is not examined when attempting to check the conditions. this means that the city must have a name and prediction to be displayed, yet it does not matter if it has a temperature. however, if it does, it will be placed in the 'temp' variable so it can be used in the action. if a city does not have a temperature, the 'temp' variable will be set to an empty string. next, we'll find out how to save the state of xu...
Content Panels - Archive of obsolete content
will get the outer xul window. this would be suitable for a child xul panel that is part of your application, but this isn't what you want for a browser that loads a web page. instead, you would want to restrict the web page to only getting access to the web page content. you might note that a mozilla browser window has xul content for the toolbars and statusbar and so forth with a tabbrowser forming the main area. this inner area displays a web page, but the web page cannot access the xul around it. this is because it uses the second type of browser, specified by setting the type attribute to the value content. this prevents the content from traversing up to the xul window. an example: <browser src="http://www.mozilla.org" type="content" flex="1" /> important: you must set the type attr...
Creating a Skin - Archive of obsolete content
: bold; } #cancel-button { list-style-image: url("chrome://global/skin/icons/images/close-button.jpg"); } button:hover { color: #000066; } we add some images to the buttons and make the find button have bold text to indicate that it is the default button. the last rule applies to buttons when the mouse is hovering over them. we set the text color to dark blue in this case. finally, some minor changes to the spacing around the items, by setting margins: tabbox { margin: 4px; } toolbarbutton { margin-left: 3px; margin-right: 3px; } after those changes, the find files dialog now looks like the image. as you can see, some simple changes to the style rules has resulted in quite a different appearance to the find files dialog. we could continue by changing the menus, the grip...
Focus and Selection - Archive of obsolete content
cus()"/> or, you can use the methods advancefocus and rewindfocus on the command dispatcher. these methods move the focus to the next element in sequence or the previous element respectively. this is what happens when the user presses tab or shift+tab. for textboxes, a special attribute, focused is added whenever the element has the focus. you can check for the presence of this attribute to determine if the element has the focus, either from a script or within a style sheet. it will have the value true if the textbox has the focus and, if the textbox does not have the focus, the attribute will not be present. suppose you wanted to move the focus from where it currently is, to the next place the browser thinks it should be. a user typically does this by hitting the "tab" key. you can do this ...
Modifying a XUL Interface - Archive of obsolete content
o the end of the existing text. note that you can still enter text into the textbox. you can also retrieve the current label or value using these properties, as in the following example: example 5 : source view <button label="hello" oncommand="alert(this.label);"/> toggling a checkbox checkboxes have a checked property which may be used to check or uncheck the checkbox. it should be easy to determine how this is used. in this next example, we reverse the state of the checked property whenever the button is pressed. note that while the label and value properties are strings, the checked property is a boolean property which will be set either true or false. note: if you're creating the checkbox dynamically and it's not yet added to the dom, you must use setattribute("checked", "false") inst...
More Menu Features - Archive of obsolete content
s the use of two attributes: type to indicate the type of check, and name to group commands together. the example below creates a menu with a checked item. example 2 : source view <toolbox> <menubar id="options-menubar"> <menu id="options_menu" label="options"> <menupopup> <menuitem id="backups" label="make backups" type="checkbox"/> <menuitem id="email" label="email administrator" type="checkbox" checked="true"/> </menupopup> </menu> </menubar> </toolbox> the type attribute has been added which is used to make the menu item checkable. by setting its value to checkbox, the menu item can be checked on and off by selecting the menu item. menu with radios in addition to standard checks, you can create the radio style of checks by setting the type to a val...
More Wizards - Archive of obsolete content
t to false, the next button is disabled. you can change the property when invalid or valid data has been entered. in the following example, the user must enter a secret code into a textbox on the first page of the wizard. the function checkcode() is called whenever the first page is shown as indicated by the onpageshow attribute. it is also called whenever a key is pressed in the textbox, to determine whether the next button should be enabled again. wizard example source <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <wizard id="thewizard" title="secret code wizard" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script> function checkcode(){ document.getelementbyid('thewizard').canadvance = (document.getelementbyid('secre...
Open and Save Dialogs - Archive of obsolete content
s" ,"*.*"); fp.appendfilter("audio files (*.wav, *.mp3)","*.wav; *.mp3"); this line will add a filter for wave and mp3 audio files. the first argument is the title of the file type and the second is a semicolon-seperated list of file masks. you can add more masks or fewer masks as needed. you can call appendfilter as many times as necessary to add additional filters. the order you add them determines their priority. typically, the first one added is selected by default. getting the selected file finally, you can show the dialog by calling the show() function. it takes no arguments but returns a status code that indicates what the user selected. note that the function does not return until the user has selected a file. the function returns one of three constants: returnok - the user sel...
Popup Menus - Archive of obsolete content
t using the mouse, for example by pressing the menu key on a keyboard. tooltips a tooltip popup window will appear when the user hovers over an element with the mouse. this type of popup is usually used to provide a description of a button in more detail than can be provided on the button itself. all three types of popups differ in the way that the user invokes them. the type of popup is determined by the element that invokes the popup. declaring popup content a popup is described using the menupopup element. it has no special attributes and is a type of box. when invoked, it will display a window containing whatever you put inside the menupopup. however, you should always put an id attribute on the menupopup as it is used to associate the popup with an element. we'll see what this mean...
RDF Datasources - Archive of obsolete content
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. for example, you might use file:///windows or files:///usr/local. the files datasource is an example of a datasource that determines its resources only when necessary. we don't want every file in the filesystem to be determined before the data is displayed. instead, only the files and directories that the tree element (or other elements) will need to display at a given time will be determined. composite datasources you can specify multiple datasources in the datasources attribute by separating them with whitespace as in the ...
Skinning XUL Files by Hand - Archive of obsolete content
ization" of interface design and ofapplications development, about which we will have more to say in a later article. in short, xul provides the tools for anybody to create interfaces as complex and as attractive as any c++/mfc/visual ide/templates toolkit user's, and it does so in a way that makes these interfaces available on any platform. you don't have to know the vagueries of a "4gl" programming language or acquaint yourself with the innards of a particular platform and its native widgetry at the expense of others. xul's technologies are interoperable, consistent, cross-platform, free, and readily available. not only is the production of such interfaces democratized, in other words; the consumption and distribution of these interfaces is equally democratic. as with anything truly democ...
Stacks and Decks - Archive of obsolete content
the special property that its children are laid out all on top of each other. the first child of the stack is drawn underneath, the second child is drawn next, followed by the third and so on. any number of elements may be stacked up in a stack. the orient property has little meaning on a stack as children are laid out above each other rather than from side to side. the size of the stack is determined by its largest child, but you can use the css properties width, height, min-width and other related properties on both the stack and its children. the stack element might be used for cases where a status indicator needs to be added over an existing element. for example, a progress bar might be created using a bar and a label overlaid on top of it. shadowing with stacks one convenient use of ...
Styling a Tree - Archive of obsolete content
for the row currently being dragged over, as long as the mouse pointer is hovering over the row. dropbefore this property is set if the mouse pointer is hovering before the row currently being dragged over. dropafter this property is set if the mouse pointer is hovering after the row currently being dragged over. progressnormal this property is set for progress meter cells. progressundetermined this property is set for undeterminate progress meter cells. progressnone this property is set for non-progress meter cells. the properties are set for rows or cells in rows with the necessary state. for columns and cells, one additional property, the id of the column or column the cell is in will be set. setting properties for the rdf-built trees for rdf-built trees, you can use the sam...
The Chrome URL - Archive of obsolete content
ecessary for many applications. another advantage over other url types is that they automatically handle multiple themes and locales. 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. mozilla will take care of determining where the file is located and return the right data. this also means that it doesn't matter where the package is installed to be able to access it. the chrome urls are independent of where the files might physically be located. this makes it much easier to write applications that have lots of files since you don't have to worry about the details of locating files. the basic syntax of a chrome ...
Tree Selection - Archive of obsolete content
ed tree items each item in a tree (that corresponds to treeitem element, if using content tree view) may be selected individually. if you add the seltype attribute to the tree, set to the value single, the user may only select one row at a time. otherwise, the user may select multiple rows, which will not necessarily be contiguous. the tree provides a number of functions which can be used to determine whether an item is selected. handling the select event first, let's see how we can determine when an item is selected. the onselect() event handler may be added to the tree element. when the user selects an item from the tree, the event handler is called. the user may also change the selection by using the cursor keys. if the user holds down the cursor key to rapidly scroll through the items, th...
XBL Example - Archive of obsolete content
t that stores a deck of objects, each displayed one at a time. navigation buttons along the bottom will allow the user to cycle through the objects while a text widget between the buttons will display the current page. you could put anything within the pages, however, this widget might be useful for a set of images. we'll call this a slideshow element. content of the slideshow first, let's determine what elements need to go in the xbl content. because we want page flipping, a deck element would be the most suitable to hold the page content. the content of the pages will be specified in the xul file, not in xbl, but we'll need to add it inside the deck. the children tag will need to be used. along the bottom, we'll need a button to go the previous page, a label to display the current page nu...
XPCOM Examples - Archive of obsolete content
has a function getwindowforresource, which can be used to get the window given a resource. in the earlier example, we generated the list of windows and added it to a menu via a template. the template generates an id attribute on each menuitem element. the value of this attribute can be used as the resource. that means that in order to switch the window focus, we need to do the following: determine the element that the user clicked on. get the value of the id attribute from the element. pass this value to getwindowforresource() to get a window object. switch the focus to this window. the example below shows how we might do this: <toolbox> <menubar id="windowlist-menubar"> <menu label="window" oncommand="switchfocus(event.target);"> <menupopup id="window-menu" datasources="rdf:...
Using multiple DTDs - Archive of obsolete content
le dtds, for example to localize common widgets used in all your xul files, additionally to the ones specific to the file. single dtd to make strings in your xul file localizable, you normally add a dtd declaration at the beginning of the file like this: <!doctype window system "chrome://myextension/locale/mainwindow.dtd"> where "window" is the local name of the document (root) element. ...
Using nsIXULAppInfo - Archive of obsolete content
aling with xulrunner-based applications. in such cases, you probably want to check nsixulappinfo.version and/or nsixulappinfo.appbuildid. the latter is useful if you're trying to support nightly development builds of the application, and the former can be useful if you only support official releases, and to distinguish between branch and trunk builds. ...
Using the Editor from XUL - Archive of obsolete content
s living. it needs this to poke the ui (e.g. for command state maintenance, starting and stopping the throbber etc.). the contentwindow (another settable attribute on nsieditorshell) points to the xul element which is to become editable. note: since we already know this when we have an <editor></editor> tag, we should remove the need to call this. editorstartup() does some other minor bits of setup before finally kicking off the url load, which the most important part here. when the xul was parsed, the src attribute on the content frame was set to about:blank (our default 'blank page' url). we can't set that before xul parsing, so we have to force a load of the page we now want to edit. we get the url to load from the args element, then kick off the load: var url = doc...
XUL FAQ - Archive of obsolete content
or ask in the xul newsgroup. are there decent visual editors for laying out xul applications? there are no production-quality visual editors available for xul. the recommended way is to edit xul by hand, possibly with the help of a good text or xml editor. ted mielczarek's live xul editor (also part of extension developer's extension) often proves useful. a list of projects (dead and active) aiming to create a xul ide/editor is at wikimo:xul:ide. troubleshooting prefwindow-based options windows this ought to be on a separate page, preferences system troubleshooting. it is a faq. some things to check when you have issues with your prefwindow-based options window: does each prefpane have a unique id? are there any elements inside the <prefwindow>, before the <prefpane>s? (putting any e...
XULBrowserWindow - Archive of obsolete content
r/base/content/browser.js. method overview boolean hidechromeforlocation(in string alocation); attributes attribute type description incontentwhitelist string[] an array of url strings for which chrome is automatically hidden. defaults to about:addons but extensions can append specific urls to the array. methods hidechromeforlocation determines whether or not browser chrome should be hidden for the specified location. by default, chrome is hidden for about:addons and any other pages in the in content whitelist. you can augment the functionality of this method using chaining in order to hide chrome for other locations. see hiding browser chrome for details and an example. boolean hidechromeforlocation( in string alocation ); param...
XUL Template Primer - Bindings - Archive of obsolete content
he <bindings> element is used to create additional,optional variable bindings, in addition to those that are specified in a rule's <conditions>. this is different from the variables specified in the rule's conditions, where a value must be found for each variable for the rule to match. if a <binding> can't be matched, the rule will still fire. example to illustrate how <bindings> work, we'll examine this xul document, which builds a simple content model an rdf/xml file. <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin" type="text/css"?> <window xmlns:html="http://www.w3.org/1999/xhtml" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" align="vertical"> <vbox datasources="friends.rdf" ref="urn:root"> <template> <rule> <conditions> ...
XUL accessibility tool - Archive of obsolete content
it is designed to test (insofar as automated testing is possible) the guidelines and requirement for creating accessible xul as set forth in the xul accessibility guidelines, and to report on any problems found in tested documents. ...
XUL Coding Style Guidelines - Archive of obsolete content
-> properties files are very similar, but use the pound sign instead of <!--<var>xxxxx</var>-->: # localization note entity name : content we recognize that translation is a subset of localization even though we've consistently referred to our notes as "localization note". files not to be localized? some files live in the tree but aren't really part of the build; they're just there as programming examples or a kind of source documentation. to prevent them from being localized, you may insert a line of comment following the xml declaration as follows. <?xml version="1.0" encoding='utf-8'?> <!-- do not localize this file: [reason...] it isn't part of the build; --> when translators see this line, they won't bother to look at the rest of the file. references xul is discussed in depth in...
browser - Archive of obsolete content
entviewer this read-only property contains the nsimarkupdocumentviewer which is responsible for drawing the document. preferences type: nsiprefservice this read-only property contains an nsipref object for getting and setting user preferences. securityui type: nsisecurebrowserui the read-only property holds an object which may be used to determine the security level of the loaded document. sessionhistory type: nsishistory this read-only property contains the nsishistory object which holds the session history. webbrowserfind type: nsiwebbrowserfind this read-only property contains an nsiwebbrowserfind object which can be used to search for text in the document. webnavigation ...
caption - Archive of obsolete content
y (or the maxwidth attribute) to override this size. for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } image type: uri the uri of the image to appear on the element. if this attribute is empty or left out, no image appears. the position of the image is determined by the dir and orient attributes. label type: string the label that will appear on the element. if this is left out, no text appears. for an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. tabindex type: integer the tab order of the element. the tab order is the order in which the focus is...
checkbox - Archive of obsolete content
javascript" checked="true"/> <checkbox label="enable java" checked="false"/> attributes accesskey type: character this should be set to a character that is used as a shortcut key. this should be one of the characters that appears in the label attribute for the element. checked type: boolean indicates whether the element is checked or not. use hasattribute() to determine whether this attribute is set instead of getattribute(). for buttons, the type attribute must be set to checkbox or radio for this attribute to have any effect. command type: id set to the id of a command element that is being observed by the element. crop type: one of the values below if the label of the element is too big to fit in its given space, the tex...
content - Archive of obsolete content
tra disponible el tutorial xul. propiedades tag, uri ejemplos (no son necesarios) atributos inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width propiedades tag type: tag name this may be set to a tag name. if set, the conditions will only match if the template buil...
datepicker - Archive of obsolete content
this attribute out entirely. visible controls have a disabled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. firstdayofweek type: integer which day of the week to display as the first day in the grid. the values range from 0 to 6, where 0 is sunday and 6 is saturday. the default value is determined by the locale, so only use this attribute if you want to override it. readonly type: boolean if set to true, then the user cannot change the value of the element. however, the value may still be modified by a script. tabindex type: integer the tab order of the element. the tab order is the order in which the focus is moved when the user presses the "tab" key. elements with a h...
menuseparator - Archive of obsolete content
to enable the element, leave this attribute out entirely. visible controls have a disabled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. image type: uri the uri of the image to appear on the element. if this attribute is empty or left out, no image appears. the position of the image is determined by the dir and orient attributes. label type: string the label that will appear on the element. if this is left out, no text appears. for an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. selected type: boolean indicates whether the element is selected or not. this value is read-only. to ...
panel - Archive of obsolete content
Archive › Mozilla › XUL › panel
ned. this handler is usually used to dynamically set the contents when the user requests to display it. returning false from this event handler prevents the popup from appearing. onpopupshown type: script code this event is sent to a popup after it has been opened, much like the onload event is sent to a window when it is opened. position type: string the position attribute determines where the popup appears relative to the element the user clicked to invoke the popup. this allows you to place the popup on one side of a button. note that a context menu will never respect this attribute, always appearing relative to the mouse cursor. this value can be specified either as a single word offering pre-defined alignment positions, or as 2 words specifying exactly which part of...
param - Archive of obsolete content
Archive › Mozilla › XUL › param
integer 32 bit integer int64 64 bit integer double double-precision floating-point number string string literal, the default value properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboun...
prefpane - Archive of obsolete content
"/> ... more ui elements ... </prefpane> attributes helpuri type: uri the uri of the help page associated with a preference panel. the uri will be opened using the help viewer when the help button is pressed. image type: uri the uri of the image to appear on the element. if this attribute is empty or left out, no image appears. the position of the image is determined by the dir and orient attributes. label type: string the label that will appear on the element. if this is left out, no text appears. for an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. onpaneload type: script code code defined here is called when the pane has been loaded...
radio - Archive of obsolete content
Archive › Mozilla › XUL › radio
buttons with type="radio" and the same value for their group attribute are put into the same group. only one button from each group can be checked at a time. if the user selects one the buttons, the others in the group are unchecked. image type: uri the uri of the image to appear on the element. if this attribute is empty or left out, no image appears. the position of the image is determined by the dir and orient attributes. label type: string the label that will appear on the element. if this is left out, no text appears. for an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. selected type: boolean indicates whether the element is selected or not. this value is read-only. to ...
tabbox - Archive of obsolete content
he previous tab will be displayed. if this attribute is set to false, these keys do not navigate between tabs. properties accessibletype type: integer a value indicating the type of accessibility object for the element. eventnode type: eventtarget indicates the node where keyboard navigation events listener is set up. the initial value for this property is determined by the value of the eventnode attribute. handlectrlpageupdown type: boolean gets and sets the value of the handlectrlpageupdown attribute. handlectrltab type: boolean gets and sets the value of the handlectrltab attibute. selectedindex type: integer returns the index of the currently selected item. you may select an item by assigning its index to this prope...
tabpanels - Archive of obsolete content
ex type: integer gets and sets the index of the currently selected panel. the first item is at index 0. inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties accessible type: nsiaccessible returns the accessibility object for the element. ...
Building XULRunner - Archive of obsolete content
ith javaxpcom support; the build system must be able to find an appropriate jdk on the system; see the instructions on building javaxpcom for more details. if you do not want to build javaxpcom support, specify --disable-javaxpcom in your configuration. on mac, xulrunner requires mac os x 10.3 or higher and xcode 1.5 or higher to build properly. the runtime requirement is mac os x 10.2. ...
CommandLine - Archive of obsolete content
</window> original document information author: georges-etienne legendre last updated date: august 21st, 2007 ...
Custom app bundles for Mac OS X - Archive of obsolete content
mac os x applications are typically packaged as application bundles which are then distributed in .dmg (disk image) files. this tutorial will show you how to package your xulrunner-based application in a way which is consistent with the expectations of mac os x users. application bundle layout application bundles are essentially just directory structures that conform to a standard layout and naming convention. a xul application for mac os x should follow something similar to this basic directory structure: example.app/ contents/ info.plist (application bundle properties are specified in this xml file.) pkginfo (this is a simple text file and is created along with the info.plist file) macos/ (the macos folder will contain your xulrunner executable) ...
Deploying XULRunner - Archive of obsolete content
at are releasing standalone xul applications. this document explains how deployment should be managed for self contained portable applications built on xulrunner. note: to actually install a xulrunner application, a compatible version of xulrunner must be registered on the system and the app must be deployed per the instructions at xul application packaging. if your installer is capable of determining whether or not xulrunner has been registered on the system you could perform the check and register the appropriate version if necessary. after that, the app could be installed to the registered xulrunner and appear in start menus, lists of installed programs, etc. (bonus points for checking the operating system and downloading the right xulrunner on the fly, or bundling them into your install...
Dialogs in XULRunner - Archive of obsolete content
frequently used common dialogs are for opening and saving files. for instance, windows has supported built-in file open and file save dialogs for many years, and the macintosh has always had them. it makes creating an application easier for developers; in addition, the consistent user experience also makes applications easier to use. xul supports native implementations of filepickers (mozilla terminology for file open and save dialogs). 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;...
Specifying Startup Chrome Window - Archive of obsolete content
main chrome window in order to specify the main chrome window of your xulrunner application, you'll need to add a preferences file to your application directory structure and add a preference named toolkit.defaultchromeuri to that file. let's look at the xulmine xulrunner application. it's directory structure is as follows: xulmine ├───chrome ├───components └───defaults └───preferences in defaults/preferences, there is a file named xulmine.js. its contents are: pref("toolkit.defaultchromeuri", "chrome://xulmine/content/xulmine.xul"); the toolkit.defaultchromeuri preference specifies that the xul window at chrome://xulmine/content/xulmine.xul is the main application window. specifying a single instance main window by default, each time the ...
What XULRunner Provides - Archive of obsolete content
activestate uses pyxpcom in their products. what's out xulrunner will not supply: bookmarks or history ui (must be managed by the application/embedder) xforms (xforms will be available ...
Windows and menus in XULRunner - Archive of obsolete content
n dialogs controls or widgets windows each window or dialog should be created in its own xul file. the xul file may also contain other top-level declarations for css and dtd, which i will discuss in a moment. <window> is the basic windowing element in xul. it has attributes to set the title/caption as well as to control its width and height. although i have not seen it mentioned yet, i am assuming that you can only have one <window> element per xul file. here is an example: <?xml version="1.0"?> <?xml-stylesheet href="chrome://basicapp/skin/main.css" type="text/css"?> <!doctype window system "chrome://basicapp/locale/main.dtd"> <window id="main" title="&title;" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script src="main.js"/> ... </window> notic...
XUL Application Packaging - Archive of obsolete content
testapplication@example.tld vendor specifies the application vendor optional example: vendor=grinch productions profile specifies the path to use for the application's profile, based within the user's application data directory optional example: profile=myappdata the [gecko] section the gecko section specifies what version of xulrunner is required by the application. minversion specifies the minimum xulrunner version needed by this application. if there are binary components, minversion must equal the version of the libxul sdk which is used to build the application. required example: minversion=1.8 maxversion specify the maximum xulrunner version needed by this application. optional - default value is any xulrunner less than xulrunner 2 exampl...
calICalendarViewController - Archive of obsolete content
ndar of the calicalendarview. the calidatetime parameters are optional, but aendtime cannot be included without astarttime. if astarttime is specified, then the calievent is meant to be created 'silently', that is, without a more detailed dialog appearing. the calievent should have its enddate set to aendtime, if this parameter is specified. otherwise, it should be set to a default value, as determined by the application. the other values of the calievent (title, summary, alarm, etc) should likewise be set to defaults. if no astarttime is specified, then an event-creation dialog should be displayed. modifyoccurrence void modifyoccurrence (in caliitemoccurrence aoccurrence, in calidatetime anewstarttime, in calidatetime anewendtime); the modifyoccurrence method is used to c...
calIFileType - Archive of obsolete content
status: unfrozen. defined in calendar/base/public/caliimportexport.idl interface code [scriptable, uuid(efef8333-e995-4f45-bdf7-bfcabbd9793e)] interface califiletype : nsisupports { readonly attribute astring defaultextension; readonly attribute astring extensionfilter; readonly attribute astring description; }; attributes defaultextension the default extension that should be associated with files of this type. ...
mozilla.dev.platform FAQ - Archive of obsolete content
on, illegal instruction/operand. 0x00016b50 in xre_createappdata () a: when you <tt>--disable-libxul</tt>, the xpcom glue doesn't have information about how to load all the dependent libraries like <tt>libgfx.dylib</tt>. in order to use xr successfully in <tt>--disable-libxul</tt> mode, you have to setup dyld_library_path to include <tt>/library/frameworks/xul.framework/versions/1.9a1</tt> - benjamin smedberg, fri, oct 20 2006 9:12 am q: when i try to build a completely standalone xul app on os x (10.4.8). 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. it wo...
Mozprocess - Archive of obsolete content
this documentation is no longer maintained. for more information about mozprocess as part of the mozbase project, please see the mozbase project page. mozprocess provides python process management via an operating system and platform transparent interface to mozilla platforms of interest. mozprocess aims to provide the ability to robustly terminate a process (by timeout or otherwise), along with any child processes, on windows, os x, and linux. mozprocess utilizes and extends subprocess.popen to these ends. api mozprocess.processhandler:processhandler is the central exposed api for mozprocess. processhandler utilizes a contained subclass of subprocess.popen, process, which does the brunt of the process management. basic usage: process = processhandler(['command', '-line', 'argume...
Mozprofile - Archive of obsolete content
ll addons and set preferences. mozprofile can be utilized from the command line or as an api. command line usage mozprofile may be used to create profiles, set preferences in profiles, or install addons into profiles. the profile to be operated on may be specified with the --profile switch. if a profile is not specified, one will be created in a temporary directory which will be echoed to the terminal: (mozmill)> mozprofile /tmp/tmp4q1ieu.mozrunner (mozmill)> ls /tmp/tmp4q1ieu.mozrunner user.js to run mozprofile from the command line enter: mozprofile --help for a list of options. api usage to use mozprofile as an api you can import mozprofile.profile and/or the addonmanager. mozprofile.profile features a generic profile class. in addition, subclasses firefoxprofile and thundebirdprofile ar...
Mozilla.dev.apps.firefox-2006-09-29 - Archive of obsolete content
c1 - update for rc1 listed in update history as 'install pending' right-click "copy email address" - bug 353102 a proposed bug fix to the 'copy email address' bug how to use the rss feeds discovery & parsing tool in another open source project? a user looking to be pointed in the right direction of how to use the rss feeds discovery & parsing tool. meetings none this week. authors sara minchella (sara) dave manley (senemanley) back to summary list ...
Mozilla.dev.apps.firefox-2006-10-06 - Archive of obsolete content
ng places (a new system for storing bookmarks, histroy and other page info) in firefox 3. ...
2006-09-29 - Archive of obsolete content
c1 - update for rc1 listed in update history as 'install pending' right-click "copy email address" - bug 353102 a proposed bug fix to the 'copy email address' bug how to use the rss feeds discovery & parsing tool in another open source project? a user looking to be pointed in the right direction of how to use the rss feeds discovery & parsing tool. meetings none this week. authors sara minchella (sara) dave manley (senemanley) back to summary list ...
2006-10-06 - Archive of obsolete content
ng places (a new system for storing bookmarks, histroy and other page info) in firefox 3. ...
2006-11-03 - Archive of obsolete content
ey think is a bug, but the developers say it's proper browser behaviour. ...
2006-11-04 - Archive of obsolete content
to what they think is a bug, but the developers say it's propwer browser behaviour. ...
2006-11-10 - Archive of obsolete content
fox 2 rc3 didn't get a prompt for updating to firefox 2 after the release date. ...
2006-11-17 - Archive of obsolete content
but not in firefox 2.0 balloon help user inquires if anyone can explain how to disable the balloon help in firefox 2.0. 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. meetings none this week. authors sara minchella (sara) dave manley (senemanley) back to summary list ...
2006-11-24 - Archive of obsolete content
update = broken? ...
2006-12-01 - Archive of obsolete content
2.0 not responding to button or link clicks until the button or link is clicked a second time. ...
2006-10-13 - Archive of obsolete content
summary: mozilla.dev.apps.thunderbird - october 7-13, 2006 announcements updated: thunderbird developer documentation eric shepherd has put together a checklist for the upcoming thunderbird developer documentation and is looking for feedback as well as contributors. discussions shared training.dat & message filters jon-mikel is looking for suggestions on sharing spam filter data and message filters between machines easily. currently, the only recommendation is to use a server-side solution. meetings none for this week. ...
2006-10-06 - Archive of obsolete content
octorber 4th ludwig hügelschäfer responded to his original post with the solution to his own problem. he found out that a broken host_xpidl was the source of the problem. in order to fix this he deleted the tree part where host_xpidl was located. he then was able to successfully build thunderbird. ludwig hügelschäfer response to the posting. announcements new svg build dependency coming on october 2nd t rowley announced that: soon svg on the trunk will be switching to use thebes directly (instead of the current choice of direct cairo or punching a hole through thebes to cairo). once completed you will need to build cairo gfx in order to build svg. https://bugzilla.mozilla.org/show_bug.cgi?id=354866 taking moz180-linux-tbox down temporarily oct 6th early afternoon (pdt) ...
2006-10-13 - Archive of obsolete content
summary: mozilla.dev.builds - october 7th to october 13th 2006 cannot build ff 1.5.0.7 on linux x86_64 werner flamme cannot build firefox 1.5.0.7 on his suse linux 10.0 x86_64 box. he gets an error in the middle of his build. he has disabled xft and has tried looking at related postings by benjamin smedberg gcc-40-workarounds and gcc-and-visibility-one-step-forward-hit-a-brick-wall announcements please help us test the new tinderbox and bonsai server installations paul reed announced that they are setting up a new installation of the tinderbox and bonsai servers onto new, supported hardware. some testing and validation has been done, but they would like other people to look at the installations and complete the setup before they switch over. new tinderbox installation new b...
2006-10-27 - Archive of obsolete content
on october 23rd: nick responded to gavin and tony's posting. nick stated that the build engineers knew that there was a problem with the tinderbox and that they would be solving the problem by adding a hard disk, and moving all or part of the concerned filesystem there. he also mentioned that the tinderbox is just a virtual machine, so you can easily allocate more space to it as need, assuming the host has some available. firefox 2 wont build under solaris 10 x86 october 26: alex was trying to build firefox 2 source on a solaris 10 x86 machine but was not successful with the build. he has already built firefox 1.5.0.7 on the same machine with no problems. the following is his configuration script that he used to build firefox 2 on solaris. ./configure --prefix=/export/home/alex/...
2006-11-24 - Archive of obsolete content
however he has been unsuccessful and a bunch of errors. to view the joe's error please check the posting. 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". joe is asking for help on a possible solution to fix his problem. ...
2006-10-13 - Archive of obsolete content
summary: mozilla.dev.l10n - october 13, 2006 announcements seamonkey 1.0.5 he-il seamonkey 1.0.5 in hebrew was released a while ago firefox 2 rc2 is out firefox 2 rc2 is out, to download click here sunbird_0_3_release tag being created sunbird_0_3_release tag being created seamonkey 1.1 localization freeze and beta upcoming there are no open blockers left. l10n freeze on seamonkey 1.1 code is imminent in the next days, as well as beta release. do early testing using code from this link. discussions mozillatranslator 5.13 rfes mozillatranslator 5.13 is ready to be released in a few weeks. author is declaring rfe (request for enhancement). a few bugs have been listed. meetings none for this week. authors paul yanchun gu (gpaul) aditya nanda kuswanto(vip...
2006-11-10 - Archive of obsolete content
n pellcheck dictionary for ff2.0 newest openoffice dictionary files for ff 2.0 spell-checker is available. trunk / 1_8 for kurdish firefox the firefox translations of the kurdish are only in trunk translating the firefox privacy policy the final and approved en-us version of privacy policy is available here and ready for localization team to translate. seamonkey 1.0.6 and 1.1 beta upcoming seamonkey 1.0.6 and 1.1 beta are both available here. discussions help about firefox 3 a discussion on how to syncronise mozilla_1_8_branch with the trunk, which tag should be used to check-in files on trunk, and when files will be pulled from trunk to create another branch (mozilla_1_9_branch?) for firefox 3. meetings none for this week. authors paul yanchun gu (gpaul) aditya na...
2006-11-3 - Archive of obsolete content
thread for complete details. mozillatranslator 5.13 released mozillatranslator 5.13 is available here. opening l10n repository on mozilla_1_8_branch for approved check-ins mozilla_1_8_branch is opened for approved check-ins. check-ins are limited to bug fixes filed in bugzilla and should mention their bug, describe the change, and who approved the change. seamonkey 1.0.6 and 1.1 beta upcoming the seamonkey projet is planning a security release of the stable 1.0 series as well as a beta for the 1.1 version, all possibly in the next days or week. community is advised to perform tests on both builds to ensure they work flawlessly. 1.0.6 build is located here, and 1.1 beta build is located here. discussions last check-ins on sun-calendar-event-dialog.* files last check-ins on sun...
2006-10-13 - Archive of obsolete content
release date for rc3 is october 17 new tinderbox and bonsai servers the build team would like help testing out the new tinderbox and bonsai servers. sunbird and lighting 0.3 sunbird and lighting 0.3 were released on october 11 discussions release process discussion discussion from last week regarding speeding up and automation of the release process continued. firefox feature brainstorming you can help suggest features for firefox 3 here meetings project meeting a project meeting was held on oct. 9. (meeting notes) bon echo status meeting a bon echo status meeting was held on oct. 10 (meeting notes) gecko 1.9/gran paradiso status meeting a gecko 1.9/gran paradiso status meeting was held on oct. 11 (notes) ...
2006-10-20 - Archive of obsolete content
ing key testing activities for ff2 rc3 are done. discussions sparky and comet going away on friday preed wants to get rid of sparky and comet (both older desktop class linux boxes). robert kaiser gave some background on the boxes. decommissioning sparky on friday preed wants to get rid of sparky (a linux build box) and wants to know if there are reasons wy not to do it. feature brainstorming + firefox 3 dria posted a link to the firefox feature brainstorming list (open to everyone). discussion of what is the best format for the list and how to use it best. meetings bon echo status meeting bon echo status meeting: october 17th, 2006 **at noon pdt**. meeting notes gecko status meeting october 19 (*thursday*) gecko 1.9 status meeting. agenda project status meeting project me...
2006-10-27 - Archive of obsolete content
he suggests that some prioritizing be done. ...
2006-11-10 - Archive of obsolete content
announcments mike connor announced new 'driving' bugs "we have added a pair of drivers-only flags...o track bugs that are not strictly blockers, but are wanted as soon as possible" benjamin smedberg announced new rules for patches to toolkit from now on unit test must be provided with all patches. other important notes are contained in the link above firefox and thunderbird 1.5.0.8 were released firefox and thunderbird 1.5.0.8 were released on november 7, 2006 blocker nomination and code freeze for 1.5.0.9/2.0.0.1 blocker nomination is due on november 10. code freeze for these versions is on november 26 version numbering changes paul reed announced changes to the way version numbers are done for pre-releases. discussion version numbering changes some discussion about pau...
2006-09-29 - Archive of obsolete content
te 1 is now available for download announcing that firefox 2 rc 1 is available for download discussions xulrunner fails without feedback on osx intel 10.4.7 will morton is trying to port a xul application to osx. when he runs xulrunner from the command line, it fails silently without any errors. this happens with all his xulrunner ports, with xulrunner 1.8.0.1, 1.8.0.4 and nightly 1.8. benjamin smedberg was able to point out one possible flaw. instead of using /path/to/xulrunner-bin.ini (which will was doing) applications on a mac must be in an application bundle (foo.app). then use xulrunner -install-app to "unpack" the xul app into the mac structure. meetings no meetings this week ...
2006-11-17 - Archive of obsolete content
meetings no meetings this week ...
2006-10-20 - Archive of obsolete content
friday october 13, 2006. help required designing new home for quality.mozilla.org - talented web designers and/or artists interested in helping the design for quality.mozilla.org please read this posting. if your theme is chosen you will be placed on the hall of fame and will receive a gift from mozilla. posted by jay patel on october 18th, 2006. discussions none for this week meetings upcoming firefox test day - testing will be emphasized on ajax/web 2.0, dhtml, and plugin heavy sites! meet in irc chat room #testday on friday october 20, 2006 7am-5pm pacific time. posted by jay patel on october 18th, 2006. authors mark d'souza (mdsouza) mohamed attar (mojo) ...
2006-11-03 - Archive of obsolete content
the event will be held on the irc server irc.mozilla.org in the channel #javascript. here is brendan's mozilla 2 roadmap. ...
2006-11-10 - Archive of obsolete content
...
2006-12-01 - Archive of obsolete content
http://www.whitebeam.org is an example of open source server side javascript. ...
JS-Engine FAQ - Archive of obsolete content
s, jsdb, jsni coding spidermonkey in c check out this tutorial how to compile tamarin on linux/x86 there is a patch that allows you to compile it. rhino what is the performance between rhino js and native java rhino js is significantly slower in run-time than native java. even when rhino is pre-compiled with high optimization, it still is no match for a compiled java program. how to determine rhino version programatically? you can call getimplementationversion() on a context instance and it gives you a string, e.g. <tt>rhino 1.6 release 2 2005 09 19</tt>. how to compile javascript into java invoking compiler: java org.mozilla.javascript.tools.jsc.main [options] file1.js [file2.js...] this results in a class file. compiler options can be vied here. non-js-engine questions can i...
2006-10-27 - Archive of obsolete content
r 27, 2006 announcements none this week. discussions removal of the nn4.6 table border color quirk discussion on removing the nn 4.6 table boarder color quirk, which currently causes a specific markup to produce a green boarder instead of a gray one. help for getting html element width info discussion on retrieving width information on html elements when using the gecko engine. it was determined that the offsetwidth property can be used to get this value. multiple presshells discussion on why current interfaces allow for multiple presshells and how the relationships work for the following objects: docshell, presshell, prescontext, document, domwindow, widget, docshell and contentviewer. boris zbarsky explains in detail the relationships between these objects. the presshells are curren...
2006-11-10 - Archive of obsolete content
using window.innerheight and window.scrollmaxy should resolve this issue. block images discussion on how where to change source code so that images could be blocked in mozilla. this can be defined within the nsicontentpolicy. ...
2006-11-17 - Archive of obsolete content
cesskey conflicts discussion about the complexity of access keys and how to detect conflicts there in the l10n community. bug #360589 describes this ongoing issue. site not loading with seamonkey a user built seamonkey in debug mode and is currently receiving a "bad request" error on some websites. reflow branch testing wanted l. david baron would like users to test the reflow branch as it is coming close to being merged with the trunk. nightly builds, instructions and the current list of known regressions on the branch can be found at: http://wiki.mozilla.org/gecko:reflow...ng#quick_links. users are asked to file bugs on encountered problems that are not present on the current trunk builds. if bugs are filed, "[reflow branch]" should be placed at the beginning of the summary. parsing html...
2006-09-30 - Archive of obsolete content
summary: mozilla.dev.tech.xpcom - sept 30- oct 5, 2006 announcements build a xpcom component on mac os x benjamin smedberg confirmed that this tutorial http://www.iosart.com/firefox/xpcom/ is misleading as it uses the standalone glue (-dxpcom_glue) for components, which is not recommended. developers should use this sample instead: http://developer.mozilla.org/en/docs/xpcom_glue discussions dynamic load overlay a short discussion about the possibilities of loading and unloading xul overlay runtime reading binary data from file discusses about the code to read binary data from file how to build xpcom component on mac os x discusses about the make file code used to build xpcom components on mac os x successfully meetings none during this week. ...
2006-12-01 - Archive of obsolete content
discussions cancellable async requests discussions about a bug of calicalendar's async methods. lightning, broken accessibility discussions refering several accessibility issues regarding interface of the sunbird client and the lightning plug-in for thunderbird. tasks in sunbird & lightning discussion about how to accessing the tasks in view in sunbird and lightning. universal binary or mac intel version of sb/lightning? discussions about universal binaries for sunbird. ...
NPClass - Archive of obsolete content
eobject() when an object's reference count reaches zero. if this field is null, free() is called isntead. invalidate called on live objects that belong to a plugin instance that is being destroyed. this call is always followed by a call to the deallocate function, or free(). any attempt to use an invalidated object will result in undefined behavior. hasmethod called by npn_hasmethod() to determine whether or not a specified method exists on a given npobject. returns true if the method exists, otherwise returns false. invoke called by npn_invoke() to invoke a specific method on a given npobject. returns true if invocation succeeded or false if an error occurred. invokedefault called by npn_invokedefault() to invoke the default method (if available) on a given npobject. returns true if ...
NPN_DestroyStream - Archive of obsolete content
instance pointer to current plug-in instance. stream pointer to current stream, initiated by either the browser or the plug-in. reason reason the stream was stopped so the application can give the user appropriate feedback. values: npres_done (most common): stream completed normally; all data was sent by the plug-in to the browser. npres_user_break: plug-in is terminating the stream due to a user request. npres_network_err: stream failed due to network problems. returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. description the plug-in calls the npn_destroystream() function to close and delete a stream. this stream can...
NPN_GetAuthenticationInfo - Archive of obsolete content
name (uri scheme) host host name port port number scheme http authentication scheme name realm http authentication realm username out parameter. the browser passes back the http username. if the function succeeds, the result buffer will be allocated with npn_memalloc; the plugin is responsible for freeing the buffer. note: the username may have internal null bytes and may not be null-terminated. ulen out parameter. the length of the returned username buffer. password out parameter. the browser passes back the http password. if the function succeed, the result buffer will be allocated with npn_memalloc; the plugin is responsible for freeing the buffer. note: the password may have internal null bytes and may not be null-terminated. plen out parameter. the length of the returned ...
NPN_GetURL - Archive of obsolete content
ed window. safest target, even though, when used with a mailto or news url, this creates an extra blank the browser instance. _self or _current: load the link into the same window the plug-in instance occupies. not recommended; if target refers to the window or frame containing the instance, the instance is destroyed and the plug-in may be unloaded. use with npn_geturl() only if you want to terminate the plug-in. _parent: load the link into the immediate <frameset> parent of the plug-in instance's document. if the plug-in instance's document has no parent, the default is _self. _top: load the link into the plug-in instance window. the default is _self, if the plug-in instance's document is already at the top. use for breaking out of a deep frame nesting. if the target is null, ...
NPN_GetValueForURL - Archive of obsolete content
selects the type of information to be retrieved (npnurlvcookie or npnurlvproxy) url the url for which to fetch information. value out parameter. the browser passes back the requested information. if the function succeeds, the result buffer will be allocated with npn_memalloc; the plugin is responsible for freeing the buffer. note: the value may have internal null bytes and may not be null-terminated. when multiple cookies are returned for a given url, the format of the return value is: cookie1=value1;cookie2=value2;cookie3=value3 len out parameter. the length of the returned value buffer. returns if successful, the function returns nperr_no_error. if unsuccessful, the function returns an error code. for possible values, see error codes. description this entry point is designed ...
NPN_HasMethod - Archive of obsolete content
syntax #include <npruntime.h> bool npn_hasmethod(npp npp, npobject *npobj, npidentifier methodname); parameters the function has the following parameters: npp the npp indicating which plugin instance is making the request. npobj the object on which to look for the method. methodname a string identifier indicating the name of the method to look for. ...
NPN_HasProperty - Archive of obsolete content
syntax #include <npruntime.h> bool npn_hasproperty(npp npp, npobject *npobj, npidentifier propertyname); parameters the function has the following parameters: <tt>npp</tt> the npp indicating which plugin instance is making the request. <tt>npobj</tt> the object on which to look for the property. <tt>propertyname</tt> a string identifier indicating the name of the property to look for. ...
NPN_IdentifierIsString - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary determines whether or not an identifier is a string. syntax #include <npruntime.h> bool npn_identifierisstring(npidentifier identifier); parameters the function has the following parameter: <tt>identifier</tt> the identifier whose type is to be examined. returns true if the identifier is a string identifier, or false otherwise. ...
NPN NewStream - Archive of obsolete content
is the mime type of the plug-in to create. a plug-in can create another instance of itself by specifying its own mime type and a new target name in a call to npn_newstream. the stream is returned in the stream parameter. the plug-in can use this object in subsequent calls to npn_write to write data into the stream. when the plug-in has written all of its data into the stream, npn_destroystream terminates the stream and deallocates the npstream object. the target parameter is the name of the target window or frame, or one of several special target names. for parameter values and information about how to use them, see npn_geturl. if the new stream has the target of _self, this function should return an invalid_param np error. see also npp_newstream, npp_write, npp_destroystream, npstream, npp ...
NPN_PluginThreadAsyncCall - Archive of obsolete content
he application's responsibility to perform any synchronization between the thread calling npn_pluginthreadasynccall() and the thread on which the call is eventually executed. in particular, the user must ensure that the function pointer remains callable and the user data is not deallocated until the browser executes the call. there are inherent race conditions between calling this function and termination of the plug-in instance. the browser might not execute calls successfully registered with this api call during plug-in termination. plug-ins should perform appropriate synchronization with the code in their npp_destroy() routine to ensure correct execution and avoid memory leaks. calling npn_pluginthreadasynccall() on the "browser main thread" or the "plug-in thread" is legal; the call to np...
NPN_SetValueForURL - Archive of obsolete content
uint32_t len); parameters this function has the following parameters: instance pointer to the current plug-in instance. variable selects the type of information to be changed. the only supported type is npnurlvcookie. url the url for which to change information. value the new associated information for the url. note: the value may have internal null bytes and may not be null-terminated. len the length of the value buffer. returns if successful, the function returns nperr_no_error. if unsuccessful, the function returns an error code. for possible values, see error codes. description this entry point is designed to allow plugins to affect the cookies sent by the browser back to the server. see also npn_getvalueforurl, npn_getauthenticationinfo ...
NPN_Write - Archive of obsolete content
if successful, the function returns a positive integer representing the number of bytes written (consumed by the browser). this number depends on the size of the browser's memory buffers, the number of active streams, and other factors. if unsuccessful, the plug-in returns a negative integer. this indicates that the browser encountered an error while processing the data, so the plug-in should terminate the stream by calling npn_destroystream(). description npn_write() delivers a buffer from the stream to the instance. a plug-in can call this function multiple times after creating a stream with npn_newstream(). the browser makes a copy of the buffer if necessary, so the plug-in can free the buffer as the method returns, if desired. see "example of sending a stream" for an example that includ...
NPP_DestroyStream - Archive of obsolete content
ms with network, disk i/o, lack of memory, or other problems. returns if successful, the plug-in should return nperr_no_error. if unsuccessful, the plug-in should return an error code. for possible values, see error codes. description the browser calls the npp_destroystream function when a data stream sent to the plug-in is finished, either because it has completed successfully or terminated abnormally. after this, the browser deletes the npstream object. you should delete any private data allocated in stream->pdata at this time, and should not make any further references to the stream object. see also npp_newstream, npstream ...
NPP_New - Archive of obsolete content
the plug-in and the browser. this data is stored in instance->pdata. mode display mode of plug-in. values: np_embed: (1) instance was created by an embed tag and shares the browser window with other content. np_full: (2) instance was created by a separate file and is the primary content in the window. argc number of html arguments in the embed tag for an embedded plug-in; determines the number of attributes in the argn and argv arrays. argn[] array of attribute names passed to the plug-in from the embed tag. argv[] array of attribute values passed to the plug-in from the embed tag. saved pointer to data saved by npp_destroy for a previous instance of this plug-in at the same url. if non-null, the browser passes ownership of the npsaveddata object back to the...
NPP_Print - Archive of obsolete content
tion has the following parameters: instance pointer to the current plug-in instance. must be embedded or full-screen. printinfo pointer to npprint structure. description npp_print is called when the user requests printing for a web page that contains a visible plug-in (either embedded or full-page). it uses the print mode set in the npprint structure in its printinfo parameter to determine whether the plug-in should print as an embedded plug-in or as a full-page plug-in. an embedded plug-in shares printing with the browser; the plug-in prints the part of the page it occupies, and the browser handles everything else, including displaying print dialog boxes, getting the printer device context, and any other tasks involved in printing, as well as printing the rest of the page. for...
NPPrint - Archive of obsolete content
api summary contains information the plug-in needs to print itself in full-page or embedded mode. syntax typedef struct _npprint { uint16 mode; /* np_full or np_embed */ union { npfullprint fullprint; /* if mode is np_full */ npembedprint embedprint; /* if mode is np_embed */ } print; } npprint; fields the data structure has the following fields: mode determines whether plug-in prints in full-page or embedded mode. values: np_full: pointer to npfullprint structure. plug-in can optionally print in full-page mode. the fullprint field of the union is valid. see npfullprint and npp_print. np_embed: pointer to npembedprint structure. plug-in should print in embedded mode. the embedprint field of the union is valid. see npembedprint. description the npp_...
NPStream - Archive of obsolete content
is null. headers the response headers from the host. this field is only available if the np version is greater than or equal to npvers_has_response_headers. this field is used only for http and is null for other types of streams. the plug-in should copy this data before making use of it. the headers include the http status line and all headers, verbatim as received from the server. lines are terminated by newline characters ("\n"), and the headers are terminated by a newline followed by null ("\n\0"). description the browser allocates and initializes the npstream object and passes it to the plug-in in as a parameter to npp_newstream or npn_newstream. the browser cannot delete the object until after it calls npp_destroystream or the plug-in calls npn_destroystream. streams produced by the b...
Supporting private browsing in plugins - Archive of obsolete content
plugins should be updated to monitor the state of private browsing mode and only save private information when private browsing is disabled. potentially private information may include (but is not necessarily limited to) history information for downloaded data. ...
XEmbed Extension for Mozilla Plugins - Archive of obsolete content
s have been using since the netscape 3.x days. the use of the xt mainloop has been a problem for modern plugin development because very few modern applications that want to take advantage of the capabilities of newer toolkits use xt. also, when included with builds of mozilla that are based on gtk 1.2 or gtk 2.x, the xt code that hosts the plugins is at best hacky and has been the source for many minor problems including inconsistent focus behavior as well as occasional crashes. it's recommended that you have a look at the gecko plugin api reference since this document will include information that assumes that you are already familiar with the way that plugins are currently hosted as well as the apis. key differences all of the interfaces that you would normally expect to exist in the plugin...
Why RSS Slash is Popular - Counting Your Comments - Archive of obsolete content
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. people can (potentially) post new comments to an item at any given time. and (spam) comments could get deleted. and thus the comments count that the <slash:comments> element provides is only a snapshot; it was only the comment count at a moment in time. one of the shortcomings of the <slash:comments> element is that does not tell you what that moment in time was. one could assume that the comment count was acurate at the moment in time specified in the <channel>'s <lastbuilddate> element, but that is a risky assumption given that no where is that mandated. and that rss feeds that are aggregations of other rss feeds will not be able to assert this. ...
0.90 - Archive of obsolete content
Archive › RSS › Version › 0.90
blic, and was replaced by netscape's rss 0.91 (revision 1). it was created by netscape to be a metadata format providing a summary of a website. (and not only a syndication format, as it is today.) rss 0.90 is an rdf-based format. when rss 0.90 was created, the rss initialization stood for rich site summary and not really simple syndication. (see rss - what is in a name for more info on rss's naming history.) note: rss 0.90 has been deprecated. producers of rssshould not be creating rss 0.90 feeds, andshould instead use a newer non-deprecated rss format. (see the rss versions list for a list of non-deprecated rss formats.) consumers of rssshould still be able to accept rss 0.90 feeds though. examples rss 0.90 looked something like this: <?xml version="1.0"?> <rdf:rdf ...
Confidentiality, Integrity, and Availability - Archive of obsolete content
have access has managed to get it, through intentional behavior or by accident. such a failure of confidentiality, commonly known as a breach, typically cannot be remedied. once the secret has been revealed, there's no way to un-reveal it. if your bank records are posted on a public website, everyone can know your bank account number, balance, etc., and that information can't be erased from their minds, papers, computers, and other places. nearly all the major security incidents reported in the media today involve major losses of confidentiality. so, in summary, a breach of confidentiality means that someone gains access to information who shouldn't have access to it. integrity integrity refers to ensuring the authenticity of information—that information is not altered, and that the sour...
Security Controls - Archive of obsolete content
e layer fails or otherwise cannot counteract a certain threat, other layers might prevent the threat from successfully breaching the system. a combination of network-based and host-based controls is generally most effective at providing consistent protection. original document information author(s): u.s. department of commerce title: federal information processing standard publication 200, minimum security requirements for federal information and information systems last updated date: march 2006 copyright information: this document is not subject to copyright. original document information author(s): karen scarfone, wayne jansen, and miles tracy title: nist special publication 800-123, guide to general server security last updated date: july 2008 copyright information: this...
NSPR Release Engineering Guide - Archive of obsolete content
nspr generally follows the iplanet product lifecycle. ...
SSL and TLS - Archive of obsolete content
on, 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. clients and servers may support different cipher suites, or sets of ciphers. among other functions, the ssl handshake determines how the server and client negotiate which cipher suite they will use to authenticate each other, to transmit certificates, and to establish session keys. key-exchange algorithms like rsa and elliptic curve cryptography (ecc) govern the way the server and client determine the symmetric keys to use during an ssl session. the most common ssl cipher suites use rsa key exchange, while tls supports ...
Vulnerabilities - Archive of obsolete content
design of the html content rendering feature was that users would not receive malicious hyperlinks and click on them. software feature misuse vulnerabilities are introduced during the design of the software or a component of the software (e.g., a protocol that the software implements). trust assumptions may have been explicit—for example, a designer being aware of a security weakness and determining that a separate security control would compensate for it. however, trust assumptions are often implicit, such as creating a feature without first evaluating the risks it would introduce. threats may also change over the lifetime of software or a protocol used in software. for example, the address resolution protocol (arp) trusts that an arp reply contains the correct mapping between media ac...
install.rdf - Archive of obsolete content
paste it into a text file, then save that file as "install.rdf": <?xml version="1.0"?> <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest"> <em:id>{themes_uuid}</em:id> <em:version>themes_version</em:version> <!-- target application this extension can install into, with minimum and maximum supported versions. --> <em:targetapplication> <description> <!-- firefox's uuid --> <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> <em:minversion>min_ff_version</em:minversion> <em:maxversion>max_ff_version</em:maxversion> </description> </em:targetapplication> <!-- front end metadata --> <!-- my_theme --> <em:name>my_theme</em:nam...
Making sure your theme works with RTL locales - Archive of obsolete content
borders, and margins. instead, you should use the following start/end rules instead to ensure rtl compatibility: -moz-padding-start -moz-padding-end -moz-margin-start -moz-margin-end -moz-border-start -moz-border-start-color -moz-border-start-style -moz-border-start-width -moz-border-end -moz-border-end-color -moz-border-end-style -moz-border-end-width #urlbar-search-splitter { min-width: 8px; -moz-margin-start: -4px; border: none; background: transparent; } testing your theme testing your theme for rtl compatibility is easy, and you do not even have to go through the hassle of downloading a rtl locale. the force rtl extension enables you to switch the interface of firefox from ltr to rtl and the other way around dynamically by toggling a menu item. ...
Theme changes in Firefox 2 - Archive of obsolete content
this article covers the changes that need to be made to update a firefox theme to work properly in firefox 2. note: we could use an article called updating themes for firefox 2 that would serve as a how-to guide for updating themes. if anyone with theming experience would like to write one, please do! browser changes requiring theme updates there are a number of changed and deleted files in the browser that may require you to make changes to your theme. the table lists both the changed xul file and the theme's corresponding css file that you might need to update. filename css file details browser/base/searchdialog.xul browser/base/content/searchdialog.css removed from firefox 2. feeds/addfeedreader.xul feeds/addfeedreader.css new file that ...
Theme changes in Firefox 3.5 - Archive of obsolete content
04. for the windows and linux native default themes, the gripper is now drawn as a part of the background of the scrollbar thumb widget. third-party themes can still draw a gripper for the scrollbar thumb button by applying a centered background image to the scrollbar's thumb button. global/checkbox.css, global/radio.css since bug 394892, radio buttons and checkboxes no longer have a minimum size on mac os x. if your theme uses native checkboxes or radiobuttons (-moz-appearance: radio / checkbox), this can result in distorted controls. you might have to set the width and height of .checkbox-check and .radio-check to 16px to avoid that problem. look at the patch to see what was changed for pinstripe. bug 450944 changed the way window shadow is handled on mac os x. be...
Theme changes in Firefox 3 - Archive of obsolete content
this article covers the changes that need to be made to update a firefox theme to work properly in firefox 3. note: we could use an article called updating themes for firefox 3 that would serve as a how-to guide for updating themes. if anyone with theming experience would like to write one, please do! browser changes requiring theme updates there are a number of changed and deleted files in the browser that may require you to make changes to your theme. the table lists both the changed xul file and the theme's corresponding css file that you might need to update. filename css file details changes to the default theme the table below lists changes made in the default theme for firefox 3; you can use this information as a starting point for f...
Using Firebug and jQuery (Screencast) - Archive of obsolete content
is originally from: http://ejohn.org/blog/hacking-digg-w...ug-and-jquery/ this is an adaptation of a presentation that i gave while at mashup camp boston. we're going to take an introductory look at the firebug firefox extension and the jquery javascript library - combining the two to build a reusable bookmarklet that can manipulate digg posts and comments. click the video link to begin (14:39 minutes long, 59mb): http://developer.mozilla.org/presentations/screencasts/jresig-digg-firebug-jquery.mp4 download: right-click this link and select save as... in order to download a copy of your own. (59mb) bookmarklets: in the presentation, i refer to a bookmarklet that you can use to introduce jquery into a web page. drag these bookmarklets found on this page into the bookmarks toolbar of ...
Using IO Timeout And Interrupt On NT - Archive of obsolete content
lio()</tt> function would be ideal for this purpose. unfortunately, <tt>cancelio()</tt> is not available on nt 3.51. so we can't go this route as long as we are supporting nt 3.51. the only reliable way to cancel outstanding overlapped io request that works on both nt 3.51 and 4.0 is to close the file descriptor, hence the rule of thumb stated at the beginning of this memo. limitations this seemingly harsh way to force the completion of outstanding overlapped io request has the following limitations: it is difficult for threads to shared a file descriptor. for example, suppose thread a and thread b call <tt>pr_accept()</tt> on the same socket, and they time out at the same time. following the rule of thumb, both threads would close the socket. the first <tt>pr_close()</tt> would succeed,...
Using SSH to connect to CVS - Archive of obsolete content
hostname of your proxy server, andport with the numeric tcp port on which the http tunnel is running. the usual cvs commands should now work. avoiding passphrase requests you can avoid repeated passphrase requests by using ssh-agent. if you don't already run ssh-agent on your computer, it's probably easiest to start it up whenever you set up your environment to checkout and build mozilla. assuming you use a shell script or batch file to set things up, just add the commands below to the end of your file. posix shell eval `ssh-agent -s` ssh-add ~/.ssh/id_dsa $shell ssh-agent -k exit x windows in "~/.xinitrc" add "ssh-add". this will bring up a graphic box just after login, and before the desktop loads, asking for your passphrase. the passphrase will be held for the length of the x sess...
Developing cross-browser and cross-platform pages - Archive of obsolete content
as a web author, you understandably want to avoid script errors and page layout problems and you may want to ensure your scripts reach as wide an audience as possible. there are 2 known approaches for such goals: the browser identification approach (also known as useragent string detection and often referred as "browser sniffing") and the object/feature support detection approach. ...
-moz-border-bottom-colors - Archive of obsolete content
ors: #f0f0f0; /* multiple <color> values */ -moz-border-bottom-colors: #f0f0f0 #a0a0a0 #505050 #000000; /* global values */ -moz-border-bottom-colors: inherit; -moz-border-bottom-colors: initial; -moz-border-bottom-colors: unset; when an element has a border that is larger than a single css pixel, each line of pixels uses the next color specified in this property, from the outside in. this eliminates the need for nested boxes. if the border is wider than the number of specified colors, the remaining part of the border is the innermost color specified. initial valuenoneapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete it does not apply if border-style is dashed or dotted. to tables with border-collapse: collapse. syntax values accepts a white-space...
-moz-border-left-colors - Archive of obsolete content
left-colors: #f0f0f0; /* multiple <color> values */ -moz-border-left-colors: #f0f0f0 #a0a0a0 #505050 #000000; /* global values */ -moz-border-left-colors: inherit; -moz-border-left-colors: initial; -moz-border-left-colors: unset; when an element has a border that is larger than a single css pixel, each line of pixels uses the next color specified in this property, from the outside in. this eliminates the need for nested boxes. if the border is wider than the number of specified colors, the remaining part of the border is the innermost color specified. initial valuenoneapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete it does not apply if border-style is dashed or dotted. to tables with border-collapse: collapse. syntax values accepts a white-space...
-moz-border-right-colors - Archive of obsolete content
-colors: #f0f0f0; /* multiple <color> values */ -moz-border-right-colors: #f0f0f0 #a0a0a0 #505050 #000000; /* global values */ -moz-border-right-colors: inherit; -moz-border-right-colors: initial; -moz-border-right-colors: unset; when an element has a border that is larger than a single css pixel, each line of pixels uses the next color specified in this property, from the outside in. this eliminates the need for nested boxes. if the border is wider than the number of specified colors, the remaining part of the border is the innermost color specified. initial valuenoneapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete it does not apply if border-style is dashed or dotted. to tables with border-collapse: collapse. syntax values accepts a white-space...
-moz-border-top-colors - Archive of obsolete content
rder-top-colors: #f0f0f0; /* multiple <color> values */ -moz-border-top-colors: #f0f0f0 #a0a0a0 #505050 #000000; /* global values */ -moz-border-top-colors: inherit; -moz-border-top-colors: initial; -moz-border-top-colors: unset; when an element has a border that is larger than a single css pixel, each line of pixels uses the next color specified in this property, from the outside in. this eliminates the need for nested boxes. if the border is wider than the number of specified colors, the remaining part of the border is the innermost color specified. initial valuenoneapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete it does not apply if border-style is dashed or dotted. to tables with border-collapse: collapse. syntax values accepts a white-space...
-ms-content-zoom-chaining - Archive of obsolete content
hen a user hits the zoom limit during page manipulation. initial valuenoneapplies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas specifiedanimation typediscrete syntax values none the initial value. a bounce effect is shown when the user hits a zoom limit during page manipulation. chained the nearest zoomable parent element begins zooming when the user hits a zoom limit during page manipulation. no bounce effect is shown. formal syntax none | chained specifications not part of any specification. remarks this property has no effect on non-zoomable elements. for information on zoomable elements, see -ms-content-zooming. starting with windows 8.1, this property is also supported for touchpad interaction. this property re...
-ms-content-zoom-snap - Archive of obsolete content
by spaces. values -ms-content-zoom-snap-type value of the -ms-content-zoom-snap-type property. -ms-content-zoom-snap-points value of the -ms-content-zoom-snap-points property. formal syntax <'-ms-content-zoom-snap-type'> | <'-ms-content-zoom-snap-points'> specifications not part of any specification. remarks this property has no effect on non-zoomable elements. see -ms-content-zooming for details on zoomable elements. starting with windows 8.1, this property is also supported for touchpad interaction. this property requires windows 8 or later. ...
-ms-ime-align - Archive of obsolete content
the -ms-ime-align css property is a microsoft extension aligning the input method editor (ime) candidate window box relative to the element on which the ime composition is active. the extension is implemented in microsoft edge and internet explorer 11. ime candidate lists are positioned on the screen with sufficient size to allow basic text input. in some cases, the ime may enforce a reasonable minimum size. 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. initial valueautoapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete syntax /* keyword values...
-ms-wrap-flow - Archive of obsolete content
...
-ms-wrap-through - Archive of obsolete content
element and another to intersect the same exclusion element. the wrapping context of a box is a collection of exclusion areas contributed by its associated exclusion boxes. the inline flow content of a box is placed in the area that corresponds to the subtraction of its wrapping context from its own content area. for more information about exclusion elements' impact on content flow, see the terminology section of the css exclusions module level 1 specification. ...
-moz-windows-compositor - Archive of obsolete content
note: since firefox 58, this media feature is no longer available to web content — it is only available internally (e.g. to xul / chrome code). see bug 1396066 for more details. syntax <integer> if the user is using windows with the dwm compositor, this is 1. otherwise it's 0. media: media/visual accepts min/max prefixes: no ...
:-moz-system-metric() - Archive of obsolete content
this page was auto-generated because a user created a sub-page to this page. note: since firefox 58, this pseudo-class is no longer available to web content — it is only available internally (e.g. to xul / chrome code). see bug 1396066 for more details. ...
::-ms-fill - Archive of obsolete content
the ::-ms-fill css pseudo-element is a microsoft extension that represents a progress bar displayed by <progress>. this pseudo-element is available only in internet explorer 10, internet explorer 11, and microsoft edge. all allowable properties except animation-name apply to a determinate progress bar. only animation-name applies to an indeterminate one. (a progress bar is determinate if it has a value attribute set; otherwise it is indeterminate. an indeterminate progress bar can be selected with the :indeterminate pseudo-class.) by default, internet explorer and edge display a moving dots animation for an indeterminate progress bar. by setting animation-name on ::-ms-fill, you can change the animation, as shown in this table: value description none turn...
-moz-mac-graphite-theme - Archive of obsolete content
details. ...
-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. media: media/visual accepts min/max prefixes: no ...
-moz-os-version - Archive of obsolete content
e user's version of microsoft windows. ...
-moz-scrollbar-end-backward - Archive of obsolete content
note: since firefox 58, this media feature is no longer available to web content — it is only available internally (e.g. to xul / chrome code). see bug 1396066 for more details. syntax <integer> if the device's user interface displays a backward arrow button at the end of scrollbars, this is 1. otherwise it's 0. media: media/visual accepts min/max prefixes: no ...
-moz-scrollbar-end-forward - Archive of obsolete content
note: since firefox 58, this media feature is no longer available to web content — it is only available internally (e.g. to xul / chrome code). see bug 1396066 for more details. syntax <integer> if the device's user interface displays a forward arrow button at the end of scrollbars, this is 1. otherwise it's 0. media: media/visual accepts min/max prefixes: no ...
-moz-scrollbar-start-backward - Archive of obsolete content
note: since firefox 58, this media feature is no longer available to web content — it is only available internally (e.g. to xul / chrome code). see bug 1396066 for more details. syntax <integer> if the device's user interface displays a backward arrow button at the beginning of scrollbars, this is 1. otherwise it's 0. media: media/visual accepts min/max prefixes: no ...
-moz-scrollbar-start-forward - Archive of obsolete content
note: since firefox 58, this media feature is no longer available to web content — it is only available internally (e.g. to xul / chrome code). see bug 1396066 for more details. syntax <integer> if the device's user interface displays a forward arrow button at the beginning of scrollbars, this is 1. otherwise it's 0. media: media/visual accepts min/max prefixes: no ...
-moz-scrollbar-thumb-proportional - Archive of obsolete content
fox 58, this media feature is no longer available to web content — it is only available internally (e.g. to xul / chrome code). see bug 1396066 for more details. syntax <integer> if the device's user interface displays the thumb of scrollbars proportionally (that is, sized based on the percentage of the document that is visible), this is 1. otherwise it's 0. media: media/visual accepts min/max prefixes: no ...
-moz-touch-enabled - Archive of obsolete content
as of firefox 73, this feature is no longer supported. use pointer: coarse instead. syntax <integer> if the device supports touch events (for a touch screen), this is 1. otherwise it's 0. media: media/visual accepts min/max prefixes: no example you might use this feature to render your buttons slightly larger if the user is on a touch-screen device, to make them more finger-friendly. button { padding: .5em; } @media (-moz-touch-enabled) { button { padding: 1em; } } ...
-moz-windows-accent-color-in-titlebar - Archive of obsolete content
ul / chrome code). see bug 1396066 for more details. ...
-moz-windows-classic - Archive of obsolete content
note: since firefox 58, this media feature is no longer available to web content — it is only available internally (e.g. to xul / chrome code). see bug 1396066 for more details. syntax <integer> if the user is using windows unthemed (in classic mode instead of using uxtheme), this is 1. otherwise it's 0. media: media/visual accepts min/max prefixes: no ...
-moz-windows-default-theme - Archive of obsolete content
since firefox 58, this media feature is no longer available to web content — it is only available internally (e.g. to xul / chrome code). see bug 1396066 for more details. 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. otherwise it's 0. media: media/visual accepts min/max prefixes: no ...
-moz-windows-glass - Archive of obsolete content
note: since firefox 58, this media feature is no longer available to web content — it is only available internally (e.g. to xul / chrome code). see bug 1396066 for more details. syntax <integer> if the user is using windows glass theme, this is 1; otherwise it's 0. note that this only exists for windows 7 and earlier. media: media/visual accepts min/max prefixes: no ...
-moz-windows-theme - Archive of obsolete content
the -moz-windows-theme gecko-only css media feature is useful for customizing application skins and other chrome code to work well with the user's windows theme. syntax the -moz-windows-theme feature is specified as a keyword value that indicates which windows theme is currently being used. values aero luna-blue luna-olive luna-silver royale generic zune media: media/visual accepts min/max prefixes: no ...
E4X - Archive of obsolete content
Archive › Web › E4X
l work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. warning: e4x is obsolete. it has been disabled by default for webpages (content) in firefox 17, disabled by default for chrome in firefox 20, and has been removed in firefox 21. use domparser/domserializer or a non-native jxon algorithm instead. ecmascript for xml (e4x) is a programming language extension that adds native xml support to javascript. it does this by providing access to the xml document in a form that feels natural for ecmascript programmers. the goal is to provide an alternative, simpler syntax for accessing xml documents than via dom interfaces. a valid alternative to e4x is a non-native jxon algorithm. e4x is standardized by ecma international in ecma-357 stan...
Accessing XML children - Archive of obsolete content
</red>; elem1.bar = elem2; replaces the <bar/> element with all of the content in elem2, giving: <foo> <red> <blue/> </red> <foo> xml lists many times, however, a single element will have two or more children of the same type. in this case, accessing foo.bar will return an xml list object, of all child elements of the type "bar". important it is your responsibility to determine whether you have an xml list or a single element when using the . operator. e4x behaves no differently when returning these properties. the xml list behaves much like an array. var element = <foo> <bar baz="1">red</bar> <bar baz="2">blue</bar> </foo>; var list = element.bar; list.length(); // returns 2 list[0]; // the first bar element list[1]; // th...
E4X Tutorial - Archive of obsolete content
e4x is deprecated. it will be disabled by default for content in firefox 16, disabled by default for chrome in firefox 17, and removed in firefox 18. use domparser/domserializer or a non-native jxon algorithm instead. this tutorial walks you through the basic syntax of e4x (ecmascript for xml). with e4x, programmers can manipulate an xml document with a syntax more familiar to javascript programming. subjects introduction accessing xml children descendants and filters namespaces the global xml object see also e4x processing xml with e4x next » ...
Debug.debuggerEnabled - Archive of obsolete content
debugging may be enabled or disabled whether or not a debugger is attached. syntax var dbgenabled = debug.debuggerenabled; requirements supported in the following document modes: internet explorer 10 standards and internet explorer 11 standards. also supported in store apps (windows 8 and windows phone 8.1). ...
Debug.setNonUserCodeExceptions - Archive of obsolete content
exceptions can be classified as thrown, user-unhandled or unhandled. syntax debug.setnonusercodeexceptions [= bool]; remarks if this property is set to true within a given scope, the debugger can then choose whether to take some specified action on exceptions thrown inside that scope: for instance, if the developer wishes to break on user-unhandled exceptions. setting this property to false is the same as never having set the property. for more information on debugging, see the active script debugging overview. example the following code shows how to set this property. ...
Debug - Archive of obsolete content
ync operation status codes contant description value debug.ms_async_op_status_success the asynchronous operation was successful. 1 debug.ms_async_op_status_canceled the asynchronous operation was canceled. 2 debug.ms_async_op_status_error the asynchronous operation resulted in an error. 3 properties debug.debuggerenabled determines whether debugging is enabled for the script context. debugging may be enabled or disabled whether or not a debugger is attached. debug.setnonusercodeexceptions determines whether any try-catch blocks in this scope are to be treated by the debugger as user-unhandled. functions debug.mstraceasynccallbackcompleted indicates that the callback stack associated with a previously specified asy...
Enumerator.atEnd - Archive of obsolete content
ean value indicating if the enumerator is at the end of the collection. syntax myenum.atend() remarks the required myenum reference is any enumerator object. the atend method returns true if the current item is the last one in the collection, the collection is empty, or the current item is undefined. otherwise, it returns false. ...
Error.number - Archive of obsolete content
ty returns or sets the numeric value associated with a specific error. the error object's default property is number. syntax object .number [= errornumber] parameters object any instance of the error object. errornumber an integer representing an error. remarks an error number is a 32-bit value. the upper 16-bit word is the facility code, and the lower word is the error code. to determine the error code, use the & (bitwise and) operator to combine the number property with the hexadecimal number 0xffff. example the following example causes an exception to be thrown and displays the error code that is derived from the error number. try { // cause an error. var x = y; } catch(e) { document.write ("error code: "); document.write (e.number & 0xffff) ...
GetObject - Archive of obsolete content
to create this string, see the documentation for the application that created the object. for example, in a drawing application you might have multiple layers to a drawing stored in a file. you could use the following code to activate a layer within a drawing called schema.cad: var layerobject = getobject("c:\\cad\\schema.cad!layer3"); if you do not specify the object's class, automation determines which application to start and which object to activate, based on the file name you provide. some files, however, may support more than one class of object. for example, a drawing might support three different types of objects: an application object, a drawing object, and a toolbar object, all of which are part of the same file. to specify which object in a file you want to activate, use the op...
ScriptEngineBuildVersion - Archive of obsolete content
version> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards, internet explorer 11 standards. also supported in store apps (windows 8 and windows phone 8.1). scriptengine function scriptenginemajorversion function scriptengineminorversion function ...
VBArray.dimensions - Archive of obsolete content
hod returns the number of dimensions in a vbarray. syntax array.dimensions( ) remarks the required array is a vbarray object. example the dimensions method provides a way to retrieve the number of dimensions in a specified vbarray. the following example consists of three parts. the first part is vbscript code to create a visual basic safe array. the second part is javascript code that determines the number of dimensions in the safe array and the upper bound of each dimension. both of these parts go into the <head> section of an html page. the third part is the javascript code that goes in the <body> section to run the other two parts. <head> <script type="text/vbscript"> <!-- function createvbarray() dim i, j, k dim a(2, 2) k = 1 for i = 0 to 2 for j = 0 to 2 ...
VBArray.lbound - Archive of obsolete content
"subscript out of range" error. parameters safearray a vbarray object. dimension optional optional. the dimension of the vbarray for which the lower bound index is wanted. if omitted, lbound behaves as if a 1 was passed. example the following example consists of three parts. the first part is vbscript code to create a visual basic safe array. the second part is javascript code that determines the number of dimensions in the safe array and the lower bound of each dimension. since the safe array is created in vbscript rather than visual basic, the lower bound will always be zero. both of these parts go into the <head> section of an html page. the third part is the javascript code that goes in the <body> section to run the other two parts. <head> <script type="text/vbscript"> <!-- fun...
VBArray.ubound - Archive of obsolete content
s if a 1 was passed. remarks if the vbarray is empty, the ubound method returns undefined. if dim is greater than the number of dimensions in the vbarray, or is negative, the method generates a "subscript out of range" error. example the following example consists of three parts. the first part is vbscript code to create a visual basic safe array. the second part is javascript code that determines the number of dimensions in the safe array and the upper bound of each dimension. both of these parts go into the <head> section of an html page. the third part is the javascript code that goes in the <body> section to run the other two parts. <head> <script type="text/vbscript"> <!-- function createvbarray() dim i, j, k dim a(2, 2) k = 1 for i = 0 to 2 for j = 0 to 2 ...
@cc_on - Archive of obsolete content
er versions. the @cc_on statement activates conditional compilation support within comments in a script. syntax @cc_on remarks the @cc_on statement activates conditional compilation within comments in a script. 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. when you write a script for a web page, always put conditional compilation code in comments. this enables hosts that do not support conditional compilation to ignore it. it is strongly recommended that you use the @cc_on statement in a comment, so that browsers that do not support conditional compilation will accept your script as valid syntax: an @if or @set statemen...
@if - Archive of obsolete content
t2 optional text to be parsed if condition1 is false and condition2 is true. text3 optional text to be parsed if both condition1 and condition2 are false. remarks when you write an @if statement, you do not have to place each clause on a separate line. you can use multiple @elif clauses. however, all @elif clauses must come before an @elseclause. the @if statement is typically used to determine which text among several options should be used for text output. it is not common to use conditional compilation variables in scripts written for asp or asp.net pages or command-line programs. this is because the capabilities of the compilers can be determined by using other methods. when you write a script for a web page, always add conditional compilation code in comments. this enables hosts...
Microsoft JavaScript extensions - Archive of obsolete content
in microsoft applications, and are not on a standards track. ...
New in JavaScript 1.1 - Archive of obsolete content
he browser with javascript support. javascript versions netscape navigator 3.0 also introduced javascript language versions. <script language="javascript"> <!-- javascript for navigator 2.0. --> <script language="javascript1.1"> <!-- javascript for navigator 3.0. --> new features in javascript 1.1 new objects array boolean function number new properties number.max_value number.min_value nan number.negative_infinity number.positive_infinity new methods array.prototype.join() array.prototype.reverse() array.prototype.sort() array.prototype.split() new operators typeof void other new features <noscript> liveconnect. communication between java and javascript. changed functionality in javascript 1.1 "object deletion". you can remove an object by sett...
ECMAScript 2015 support in Mozilla - Archive of obsolete content
.cosh(), math.sinh(), math.tanh(), math.acosh(), math.asinh(), math.atanh(), math.hypot(), math.trunc(), math.sign(), math.cbrt() (firefox 25) additions to the number object number.isnan() (firefox 16) number.isfinite() (firefox 16) number.isinteger() (firefox 16) number.parseint() (firefox 25) number.parsefloat() (firefox 25) number.epsilon (firefox 25) number.max_safe_integer, number.min_safe_integer (firefox 31) number.issafeinteger() (firefox 32) additions to the object object object.prototype.__proto__ has been standardized object.is() (firefox 22) object.setprototypeof() (firefox 31) object.assign() (firefox 34) object.getownpropertysymbols() (firefox 33) additions to the date object date.prototype is an ordinary object (firefox 41) generic date.prototype.tost...
Object.observe() - Archive of obsolete content
ame + '!'; } updategreeting(); object.observe(user, function(changes) { changes.foreach(function(change) { // any time name or title change, update the greeting if (change.name === 'name' || change.name === 'title') { updategreeting(); } }); }); custom change type // a point on a 2d plane var point = {x: 0, y: 0, distance: 0}; function setposition(pt, x, y) { // performing a custom change object.getnotifier(pt).performchange('reposition', function() { var olddistance = pt.distance; pt.x = x; pt.y = y; pt.distance = math.sqrt(x * x + y * y); return {olddistance: olddistance}; }); } object.observe(point, function(changes) { console.log('distance change: ' + (point.distance - changes[0].olddistance)); }, ['reposition']); setposition(point,...
Archived JavaScript Reference - Archive of obsolete content
zillaexpression closuresexpression closures are a shorthand function syntax for writing simple functions.for each...inthe for each...in statement iterates a specified variable over all values of object's properties. for each distinct property, a specified statement is executed.function.aritynot part of any standard.function.prototype.isgenerator()the non-standard isgenerator() method used to determine whether or not a function is a generator. it has been removed from firefox starting with version 58.generator comprehensionsthe generator comprehension syntax was a javascript expression which allowed you to quickly assemble a new generator function based on an existing iterable object. however, it has been removed from the standard and the firefox implementation. do not use it!handler.enumerate...
JSException - Archive of obsolete content
code being evaluated. tokenindex the index into the source string where the error occurred. getwrappedexception instance method getwrappedexception. declaration public object getwrappedexception() description getwrappedexception() returns an object that represents the value that the javascript actually threw. javascript can throw any type of value. use getwrappedexception() to determine what kind of value the object return type represents. getwrappedexceptiontype instance method getwrappedexceptiontype. declaration public int getwrappedexceptiontype() description getwrappedexceptiontype() returns an int that matches one of the following static ints declared by the jsexception class: exception_type_empty exception_type_void exception_type_object exception_type_funct...
LiveConnect - Archive of obsolete content
* package hierarchy, or using a new "packages" object for classes outside this hierarchy). old liveconnect documents, broken links: java method overloading and liveconnect 3 the technique that liveconnect uses to invoke overloaded java methods from javascript. liveconnect exceptions how do java and javascript catch exceptions generated by the other party? liveconnect testcases determine that applets within different html tags work properly. note: liveconnect blocked under some conditions liveconnect calls from javascript to java api are blocked when the java control panel security slider is set to very high level, or when the slider is at the default high level and the jre has either expired or is below the security baseline. ...
RDF: Resource Description Framework for metadata - Archive of obsolete content
Archive › Web › RDF
resource description framework (rdf) is a family of specifications for a metadata model that is often implemented as an application of xml. the rdf family of specifications is maintained by the world wide web consortium (w3c). the rdf metadata model is based upon the idea of making statements about resources in the form of a subject-predicate-object expression, called a triple in rdf terminology. the subject is the resource, the "thing" being described. the predicate is a trait or aspect about that resource, and often expresses a relationship between the subject and the object. the object is the object of the relationship or value of that trait. documentation directions of the mozilla rdf engine this presentation shows new developments in the mozilla rdf engine. these include plans t...
Sharp variables in JavaScript - Archive of obsolete content
:undefined }; a.bar = a.foo; a.foo.push("hello"); a.bar.push("there!"); alert(a.foo[1]); // "there!" cyclic references sharp variables can be used to create a circularly linked list in one line of code. 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. var a = {val:1, next:{val:2, next:undefined} }; a.next.next = a; a.val; // 1 a.next.val; // 2 a.next.next.val; // 1 a.next.next == a; // true multiple sharp variables var a = #1 = { val:#2=[], next:{val:[], next:{val:#02#, next:#1#}} }; // leading 0s don't matter a...
Styling the Amazing Netscape Fish Cam Page - Archive of obsolete content
out being knocked over by the waves. i was privileged enough to have that chance recently: i was asked to redesign the amazing netscape fish cam page for a new millennium. to put that in perspective, i remember when the fish cam page first appeared and word of it circulated around the internet. you could see the actual fish in the mythical netscape headquarters, any time of the day or night! (assuming the lights were on.) it was cool, it was funny, it was pretty amazing. it's also a weird feeling when someone asks you to work on something that has near-legendary status in your mind. it's like a scuba enthusiast getting to join jacques cousteau on a dive, even down to the required time travel. i dove right in and decided to have some fun with with the redesign, which is why i rather like the ...
RFE to the Custom Controls Interfaces - Archive of obsolete content
lue/state is changed our current mechanism that allows authors to build custom controls assumes that the controls will be bound to instance nodes of simple content type. this means that the bound node is not allowed to contain element nodes. if you need to have a custom control that works with complext content or you find our interfaces too limiting to create the type of control that you have in mind, then this is the right place to pass along your requirements and any usecase that you are trying to solve. rfe put your requirements here. ...
Requests For Enhancement - Archive of obsolete content
Archive › Web › XForms › RFE
a new bug in the 'xforms' component of the 'core' product. an additional way to attract the xforms team's attention to an enhancement request you are promoting is to vote for the bug that is related with the feature request (if there is no bug yet then please feel free to file it). then you can give a vote by clicking on the 'vote' link on the bug page. the xforms team looks at votes to help determine which bug is more important for our xforms users. rfe categories xforms api this section contains rfe to the xforms api. custom controls i think that xforms is a great way to show that 14 year old html hacks can build really powerful web apps and reduce the need for javascript by 90%. now we need to start teaching xforms to web newcomers before they are brainwashed into believing that th...
XForms Styling - Archive of obsolete content
processors such as chiba create "old-style" html forms from xforms documents, and must be styled accordingly. ...
XForms Range Element - Archive of obsolete content
possible values, i.e. values can't be less than the value of this attribute. if this attribute is omitted, then it is assumed to be 0. end specifies the upper bound of possible values, i.e. values can't be greater than the value of this attribute. if this attribute is omitted, then it is assumed to be the value of start + 20. step specifies the step of incrementing/decrementing values. this determines how much the value of the range will be changed upon user interaction. if this attribute is omitted, then it is assumed to be the value of end - start / 20. type restrictions the range element can be bound to a node of type xsd:duration, xsd:date, xsd:time, xsd:datetime, xsd:gyearmonth, xsd:gyear, xsd:gmonthday, xsd:gday, xsd:gmonth, xsd:float, xsd:decimal or xsd:double or any type derived f...
XForms Secret Element - Archive of obsolete content
the xforms secret element is represented by a password field. the password field is a text field, the value of which is hidden by asterisks (xhtml/xul). characteristics analogous widgets are <xhtml:input type="password"/> and <xul:textbox type="password"/> if the incremental attribute is present and has the value true, then the bound instance node is updated on every user input. please keep in mind that the instance data will hold exactly what the user gave as input. any other xform control bound to that data will show that data 'as is'. ...
XForms Switch Module - Archive of obsolete content
ement doesn't have a visual representation. case element this element (see the spec) encloses markup to be conditionally rendered. the content elements (e.g. form controls, groups, switches, repeats and host language elements) within a non-selected case are not rendered. correspondingly, content elements in a case that becomes selected are visible. attributes special selected - determines the initial selected state of the case. if multiple cases within a switch are marked as selected="true", the first selected case will appear and all others will not be visible. if no case is initially selected, the first case inside the switch becomes selected and visible. representations the case element doesn't have a visual representation. toggle element the element (see the spec) s...
Window: devicelight event - Archive of obsolete content
bled by default in firefox 62, behind the device.sensors.ambientlight.enabled preference (bug 1462308). bubbles no cancelable no interface sensorcallback target defaultview (window) other properties property type description value read only double (float) the sensor data for ambient light in lux. min read only double (float) the minimum value in the range the sensor detects (if available, 0 otherwise). max read only double (float) the maximum value in the range the sensor detects (if available, 0 otherwise). examples window.addeventlistener('devicelight', function(event) { console.log(event.value); }); specifications specification status comme...
Displaying a graphic with audio samples - Archive of obsolete content
ramebufferlength; fft = new fft(framebufferlength / channels, rate); } function audioavailable(event) { var fb = event.framebuffer, t = event.time, /* unused, but it's there */ signal = new float32array(fb.length / channels), magnitude; for (var i = 0, fbl = framebufferlength / 2; i < fbl; i++ ) { // assuming interlaced stereo channels, // need to split and merge into a stero-mix mono signal signal[i] = (fb[2*i] + fb[2*i+1]) / 2; } // clear the canvas before drawing spectrum ctx.fillstyle = "rgb(0,0,0)"; ctx.fillrect (0,0, canvas.width, canvas.height); ctx.fillstyle = "rgb(255,255,255)"; for (var i = 0; i < signal.length; i++ ) {...
Parsing microformats in JavaScript - Archive of obsolete content
this api is primarily intended to be used when implementing new microformats. methods datetimegetter() specifically retrieves a date from a microformat node. after getting the text, it is normalized into an iso 8601 date. normalizeddate = microformats.parser.datetimegetter(propnode, parentnode); parameters propnode the dom node to check. parentnode the property's parent node. if it is a subproperty, this is the parent property node. otherwise this is the microformat node. ...
XUL Parser in Python - Archive of obsolete content
keys: for item in elements: w.write('<tr><td class="head">' + item + '</td></tr>\n') for a in el_list[item].values(): w.write('<tr><td class="at">' + a + '</td>') with these modifications, the script creates an output more like a periodic table of xul elements. until i spruce it up a little, this is just a very basic demonstration of using python's xml parser with xul. but mozilla's upcoming support for languages like perl and python will really open up the mozilla platform to tools and approaches of this kind--and make now a good time to start thinking about how these various technologies will be put together. the first level of support for python in mozilla will apparently be for python modules made available as xpcom objects. extending on the approach in this script, then, you co...
Using the DOM File API in chrome code - Extensions
ing 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 "/"). in the xul/mozilla platform there isn't sadly an equivalent to java file.pathseparator (the system-dependent path-separator character). so the good practice is to avoid trying to determine and to use the path separator at all. instead, use the nsifile::append() method as explained in the next section. accessing files in a special directory you can also use the directory service to obtain and build the path to a file to access. for example, let's say your add-on needs to access a file in the user's profile. you can do so like this: var dsfile = components.classes["@mozilla.org/f...
Examples - Game development
hopper around the disaster area and save the stranded victims (ga.me.) polycraft a shipwreck 'n survive game. explore the island and defeat the monsters. hexgl a fast-paced, futuristic racing game. dead trigger 2 classic zombie splatter action, made with unity3d. angry bots a futuristic aliens-esque isometric 3rd person shooter demo, made with unity3d. nutmeg cute retro scrolling platforming action. back to candyland a match-3 (candy crush) style game. biolab disaster side-scrolling platform shooter. x-type vertically scrolling space shooter demo. xibalba retro (doom-style) first person shooter. gorescript another retro style first person shooter. the wizard a turn-based, dungeon puzzle game. hextris tetris-like hexagonal puzzle game. 2048 a sliding number tiles puzz...
Publishing games - Game development
about your great new game. promoting the game helps a lot in monetizing it later on too, so it's important to do it effectively. game monetization when you spend your time building, publishing and promoting your game, you will at some point consider earning money out of it. game monetization is essential to anyone who considers their game development work a serious endeavour on the path to becoming an independent game developer able to make a living, so read on and see what your options are. the technology is mature enough; it's just a matter of chosing the right approach. ...
Building up a basic demo with A-Frame - Game development
ory for latest stable a dev builds). open the a-frame documentation in a separate tab — it is useful to refer to. html structure the first step is to create an html document — inside your project directory, create a new index.html file, and save the follow html inside it: <!doctype html> <html> <head> <meta charset="utf-8"> <title>mdn games: a-frame demo</title> <script src="aframe.min.js"></script> </head> <body> <!-- html goes here --> </body> </html> this contains some basic information like the document charset and <title>. the <script> element includes the a-frame framework in the page; we will write our example code inside the <body> element. initializing the scene a scene is the place where everything happens. when creating new objects in the demo, we will be adding...
Building up a basic demo with PlayCanvas editor - Game development
aycanvas editor is free — all you have to do to begin with is register your account and login: when you first sign up, you are taken straight into the editor and given a simple starter tutorial involving editing a 3d rolling ball game. you can finish this before you continue our tutorial if you like. when you are ready to continue with our tutorial, go to your canvas homepage — for example mine is https://playcanvas.com/end3r. here's what the page looks like — you can create projects and manage them, change their settings etc. creating a new project start a brand new project by clicking on the new button: the resulting dialog box will show a few different options. there are starter kits available, but we don't want to load models or start a platform game. we want to start sma...
WebVR — Virtual Reality for the Web - Game development
the concept of virtual reality in itself isn't new, but now we have the technology to have it working as it should be, and a javascript api to make use of it in web applications. this article introduced webvr from the perspective of its use in games. vr devices with the popularity of oculus rift and a lot of other devices in production coming soon to the market, the future looks bright — we already have sufficient technology to make the vr experience "good enough" for playing games. there are many devices to chose from: desktop ones like oculus rift or htc vive, through consoles with playstation vr (which admittedly doesn't support webvr at this time), to mobile experiences like gear vr or google cardboard. note: for more information, read our webvr concepts article. the web...
Desktop gamepad controls - Game development
ike before. summary that's it! we have successfully implemented gamepad controls in our game — try connecting any popular controller like the xbox 360 one and see for yourself how fun it is to avoid the asteroids and shoot the aliens with a gamepad. now we can move on and explore new, even more unconventional ways to control the html5 game like waving your hand in front of the laptop or screaming into your microphone. previous overview: control mechanisms next ...
Mobile touch controls - Game development
in this tutorial, we will see how easy it is to implement mobile controls in an html5 game, and enjoy playing on a mobile touch-enabled device. note: the game captain rogers: battle at andromeda is built with phaser and managing the controls is phaser-based, but it could also be done in pure javascript. ...
Efficient animation for web games - Game development
hing that would overlap its container’s bounds, you may want to set overflow: hidden on that container for the duration of the animation. use requestanimationframe when you are animating <canvas> content, or when your dom animations absolutely must synchronise with canvas content animations, do make sure to use window.requestanimationframe, and not older methods such as window.settimeout. assuming you are running in an arbitrary browsing session, you can never really know how long the browser will take to draw a particular frame. requestanimationframe causes the browser to redraw and call your function before that frame gets to the screen. the downside of using this vs. settimeout is that your animations must be time-based instead of frame-based, i.e. you must keep track of time and set y...
Square tilemaps implementation: Scrolling maps - Game development
by the player (such as in strategy games) or follow an object (such as the main character in platform games.) regardless of the type of camera, we would always need information regarding its current position, viewport size, etc. in the demo provided along with this article, these are the parameters the camera has: x and y: the current position of the camera. in this implementation, we are assuming that (x,y) points to the top left corner of visible portion of the map. width and height: the size of the camera's viewport. maxx and maxy: the limit for the camera's position — the lower limit will nearly always be (0,0), and in this case the upper limit is equal to the size of the world minus the size of the camera's viewport. rendering the map there are two main differences between ren...
asm.js - Game development
run fast if they adhere to asm.js patterns. emscripten, a c/c++ to javascript compiler, emits asm.js code to make it run with near native performance on several browsers. additionally, if an engine chooses to specially recognize asm.js code, there even more optimizations that can be made. firefox is the only browser to do this right now. asm.js language summary asm.js is an intermediate programming language. asm.js has a very predictable perfomance rate because it is limited to an extremely restricted subset of javascript that provides only strictly-typed integers, floats, arithmetic, function calls, and heap accesses. the performance characteristics are closer to native code than that of standard javascript. using a subset of javascript asm.js is already supported by major web browsers...
Tools for game development - Game development
erformance than your typical javascript performance. this is, of course, great for games. emscripten an llvm to javascript compiler; with emscripten, you can compile c++ and other languages that can compile to llvm bytecode into high-performance javascript. this is a great tool for porting applications to the web! there is a useful emscripten tutorial available on the wiki. note that we are aiming to cover emscripten in its own section of mdn. gecko profiler the gecko profiler extension lets you profile your code to help figure out where your performance issues are so that you can make your game run at top speed. shumway shumway is a renderer for adobe flash built entirely in javascript, webgl, etc., bridging the gap between flash and web standards. this article shows how to make us...
Move the ball - Game development
y frame to make the impression of movement — just like how movement works with the movies. defining a drawing loop to keep constantly updating the canvas drawing on each frame, we need to define a drawing function that will run over and over again, with a different set of variable values each time to change sprite positions, etc. you can run a function over and over again using a javascript timing function such as setinterval() or requestanimationframe(). delete all the javascript you currently have inside your html file except for the first two lines, and add the following below them. the draw() function will be executed within setinterval every 10 miliseconds: function draw() { // drawing code } setinterval(draw, 10); thanks to the infinite nature of setinterval the draw() functi...
Animations and tweens - Game development
ill load the spritesheet — put the following line at the bottom of your preload() function: game.load.spritesheet('ball', 'img/wobble.png', 20, 20); instead of loading a single image of the ball we can load the whole spritesheet — a collection of different images. we will show the sprites sequentially to create the illusion of animation. the spritesheet() method's two extra paremeters determine the width and height of each single frame in the given spritesheet file, indicating to the program how to chop it up to get the individual frames. loading the animation next up, go into your create() function, find the line that loads the ball sprite, and below it put the call to animations.add() seen below: ball = game.add.sprite(50, 250, 'ball'); ball.animations.add('wobble', [0,1,0,2,0,1,0...
Randomizing gameplay - Game development
lines of the below. add this new line to your code now, and try it out. function ballhitpaddle(ball, paddle) { ball.animations.play('wobble'); ball.body.velocity.x = -1*5*(paddle.x-ball.x); } it's a little bit of magic — the new velocity is higher, the larger the distance between the center of the paddle and the place where the ball hits it. also, the direction (left or right) is determined by that value — if the ball hits the left side of the paddle it will bounce left, whereas hitting the right side will bounce it to the right. it ended up that way because of a little bit of experimentation with the given values, you can do your own experimentation and see what happens. it's not completely random of course, but it does make the gameplay a bit more unpredictable and therefore m...
2D maze game with device orientation - Game development
y — this will be taken care of by the framework. let’s set it up: our starting point is the index.html file with the following content. ...
Game development
new technologies are constantly arriving to make it possible to develop better and more powerful games that can be run in any standards-compliant web browser. develop web games welcome to the mdn game development center! in this area of the site, we provide resources for web developers wanting to develop games. you will find many useful tutorials and technique articles in the main menu on the left, so feel free to explore. we've also included a reference section so you can easily find information about all the most common apis used in game development. note: creating games on the web draws on a number of core web technologies such as html, css, and javascript. ...
Ajax - MDN Web Docs Glossary: Definitions of Web-related terms
ajax allows you to update parts of the dom of an html page instead without the need for a full page refresh. ajax also lets you work asynchronously, meaning your code continues to run while the targeted part of your web page is trying to reload (compared to synchronously, which blocks your code from running until that part of your page is done reloading). ...
API - MDN Web Docs Glossary: Definitions of Web-related terms
the api can be seen as a simple contract (the interface) between the application offering it and other items, such as third party software or hardware. in web development, an api is generally a set of code features (e.g. methods, properties, events, and urls) that a developer can use in their apps for interacting with components of a user's web browser, or other software/hardware on the user's computer, or third party websites and services. ...
Abstraction - MDN Web Docs Glossary: Definitions of Web-related terms
it hides the technical complexity of systems behind simpler apis. advantages of data abstraction helps the user to avoid writing low level code. avoids code duplication and increases reusability. can change internal implementation of class independently without affecting the user. helps to increase security of an application or program as only important details are provided to the user. ...
Accessibility - MDN Web Docs Glossary: Definitions of Web-related terms
ibility (a11y) refers to best practices for keeping a website usable despite physical and technical restrictions. ...
Adobe Flash - MDN Web Docs Glossary: Definitions of Web-related terms
adobe flash can run from supporting web browsers via a browser plug-in. ...
Algorithm - MDN Web Docs Glossary: Definitions of Web-related terms
a function. in other words, an algorithm is a means of describing a way to solve a problem so that it can be solved repeatedly, by humans or machines. computer scientists compare the efficiency of algorithms through the concept of "algorithmic complexity" or "big o" notation. for example: a cooking recipe is a simple algorithm for humans. a sorting algorithm is often used in computer programming to explain a machine how to sort data. common algorithms are pathfinding algorithms such as the traveling salesman problem, tree traversal algorithms and so on. there are also machine learning algorithms such as linear regression, logistic regression, decision tree, random forest, support vector machine, recurrent neural network (rnn), long short term memory (lstm) neural network, convolution...
Arpanet - MDN Web Docs Glossary: Definitions of Web-related terms
arpanet was closed in early 1990. learn more general knowledge arpanet on wikipedia ...
BigInt - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, bigint is a numeric data type that can represent integers in the arbitrary precision format. in other programming languages different numeric types can exist, for examples: integers, floats, doubles, or bignums. learn more general knowledge numeric types on wikipedia technical reference the javascript data structure: bigint the javascript global object bigint ...
Block cipher mode of operation - MDN Web Docs Glossary: Definitions of Web-related terms
a block cipher mode of operation, usually just called a "mode" in context, specifies how a block cipher should be used to encrypt or decrypt messages that are longer than the block size. most symmetric-key algorithms currently in use are block ciphers: this means that they encrypt data a block at a time. the size of each block is fixed and determined by the algorithm: for example aes uses 16-byte blocks. block ciphers are always used with a mode, which specifies how to securely encrypt messages that are longer than the block size. for example, aes is a cipher, while ctr, cbc, and gcm are all modes. using an inappropriate mode, or using a mode incorrectly, can completely undermine the security provided by the underlying cipher. ...
CORS - MDN Web Docs Glossary: Definitions of Web-related terms
the same-origin security policy forbids cross-origin access to resources. but cors gives web servers the ability to say they want to opt into allowing cross-origin access to their resources. learn more general knowledge cross-origin resource sharing (cors) on mdn cross-origin resource sharing on wikipedia cors headers access-control-allow-origin indicates whether the response can be shared. ...
CSS - MDN Web Docs Glossary: Definitions of Web-related terms
css is one of the three core web technologies, along with html and javascript. css usually styles html elements, but can be also used with other markup languages like svg or xml. ...
Client hints - MDN Web Docs Glossary: Definitions of Web-related terms
, the server gives the browser the hints by setting the accept-ch meta tag. basically, with the client hints header, the developer or application can tell the browser to advertise information about itself to the server, such as the device pixel ratio, the viewport width, and the display width. the client can then give the server information about the client's environment, and the server can determine which resources to send based on that information. varying client hints to convey to caches that different client hints may affect the response, the vary http header must be used. example varying response: vary: accept, dpr, width, viewport-width, downlink see also client hints headers vary http header ...
Compile - MDN Web Docs Glossary: Definitions of Web-related terms
a compiler is a software to execute this task. sometimes, this task is also referred to as "assembling" or "build", which typically indiciates more than just compilation is done, e.g. packaging it in a binary format. usually, a compiler transforms a higher-level language such as c or java, which humans understand, into a machine language, such as assembly, that the cpu can understand. some compilers which translate between similar level languages are called transpilers or cross-compilers, for instance to compile from typescript to javascript. those are considered productivity tools. ...
Cryptographic hash function - MDN Web Docs Glossary: Definitions of Web-related terms
cryptographic hash functions are used for authentication, digital signatures, and message authentication codes. ...
DNS - MDN Web Docs Glossary: Definitions of Web-related terms
dns (domain name system) is a hierarchical and decentralized naming system for internet connected resources. dns maintains a list of domain names along with the resources, such as ip addresses, that are associated with them. the most prominent function of dns is the translation of human-friendly domain names (such as mozilla.org) to a numeric ip address (such as 151.106.5.172); this process of mapping a domain name to the appropriate ip address is known as a dns lookup. by contrast, a reverse dns lookup (rdns) is used to determine the domain name associated with an ip address. learn more general knowledge understanding domain names domain name system on wikipedia ...
ECMA - MDN Web Docs Glossary: Definitions of Web-related terms
on the web it is famous for being the organization which maintain the ecma-262 specification (aka. ...
Effective connection type - MDN Web Docs Glossary: Definitions of Web-related terms
effective connection type (ect) refers to the measured network performance, returning a cellular connection type, like 3g, even if the actual connection is tethered broadband or wifi, based on the time between the browser requesting a page and effective type of the connection. the values of 'slow-2g', '2g', '3g', and '4g' are determined using observed round-trip times and downlink values. table of effective connection types ect minimum rtt maximum downlink explanation slow-2g 2000ms 50 kbps the network is suited for small transfers only such as text-only pages. 2g 1400ms 70 kbps the network is suited for transfers of small images. 3g 270ms 700 kbps the network is suited for transfers of large assets such as...
First CPU idle - MDN Web Docs Glossary: Definitions of Web-related terms
it is a non-standard google web performance metric. generally, it occurs when most, but not necessarily all visible ui elements are interactive, and the user interface responds, on average, to most user input within 50ms. ...
First contentful paint - MDN Web Docs Glossary: Definitions of Web-related terms
...
First interactive - MDN Web Docs Glossary: Definitions of Web-related terms
first interactive, also known as first cpu idle, is a non-standard web performance metric that measures when the user's window is quiet enough to handle user input, or what is termed as minimally interactive. minimally interactive is defined as when some, but not necessarily all, ui elements on the page have loaded and are interactive, and, on average, respond to user input in a reasonable amount of time. more information first interactive is a variation of time to interactive, which is split into first interactive and consistently interactive. these metrics have been proposed by the web incubator community group and are already being used in various tools. this metric has been called first cpu idle since lighthouse 3.0 ...
First paint - MDN Web Docs Glossary: Definitions of Web-related terms
first paint, part of the paint timing api, is the time between navigation and when the browser renders the first pixels to the screen, rendering anything that is visually different from what was on the screen prior to navigation. it answers the question "is it happening?" ...
Garbage collection - MDN Web Docs Glossary: Definitions of Web-related terms
in other words, garbage collection is the process of removing any objects which are not being used by any other objects. often abbreviated "gc," garbage collection is a fundamental component of the memory management system used by javascript. learn more general knowledge memory management on wikipedia garbage collection on wikipedia technical reference garbage collection in the mdn javascript guide. ...
Global scope - MDN Web Docs Glossary: Definitions of Web-related terms
in client-side javascript, the global scope is generally the web page inside which all the code is being executed. ...
HTTP/2 - MDN Web Docs Glossary: Definitions of Web-related terms
http/2 is a major revision of the http network protocol. the primary goals for http/2 are to reduce latency by enabling full request and response multiplexing, minimize protocol overhead via efficient compression of http header fields, and add support for request prioritization and server push. http/2 does not modify the application semantics of http in any way. all the core concepts found in http 1.1, such as http methods, status codes, uris, and header fields, remain in place. instead, http/2 modifies how the data is formatted (framed) and transported between the client and server, both of which manage the entire process, and hides application complexity within the new framing layer. as a result, all existing applications can be delivered without modification. ...
HTTP/3 - MDN Web Docs Glossary: Definitions of Web-related terms
http/3 is the upcoming major revision of the http network protocol, succeeding http/2. the major point of http/3 is that it using a new udp protocol named quic, instead of tcp. ...
IDL - MDN Web Docs Glossary: Definitions of Web-related terms
content versus idl attributes in html, most attributes have two faces: the content attribute and the idl (interface definition language) attribute. the content attribute is the attribute as you set it from the content (the html code) and you can set it or get it via element.setattribute() or element.getattribute(). the content attribute is always a string even when the expected value should be an integer. ...
ITU - MDN Web Docs Glossary: Definitions of Web-related terms
on, including telegraph, radio, telephony and the internet. from defining rules for ensuring transmissions get to where they need to go to and creating the "sos" alert signal used in morse code, the itu has long played a key role in how we use technology to exchange information and ideas. in the internet age, the itu's role of establishing standards for video and audio data formats used for streaming, teleconferencing, and other purposes. for example, the itu and the moving picture experts group (mpeg) worked together to develop and publish, as well as to maintain, the various mpeg specifications, such as mpeg-2 (itu h.262), avc (itu h.264), and hevc (itu h.265). learn more general knowledge itu web site learn about it itu history portal ...
Inheritance - MDN Web Docs Glossary: Definitions of Web-related terms
data abstraction can be carried up several levels, that is, classes can have superclasses and subclasses. as an app developer, you can choose which of the superclass's attributes and methods to keep and add your own, making class definition very flexible. some languages let a class inherit from more than one parent (multiple inheritance). ...
JSON - MDN Web Docs Glossary: Definitions of Web-related terms
json can represent numbers, booleans, strings, null, arrays (ordered sequences of values), and objects (string-value mappings) made up of these values (or of other arrays and objects). json does not natively represent more complex data types like functions, regular expressions, dates, and so on. ...
Java - MDN Web Docs Glossary: Definitions of Web-related terms
java is statically typed and features a similar syntax to c. it comes with a large library of readily usable functions, the java software development kit (sdk). programs are compiled only once ahead of time into a proprietary byte code and package format that runs inside the java virtual machine (jvm). the jvm is available across many platforms, which allows java programs to run almost everywhere without the need to be compiled or packaged again. this makes it a preferred language in many large enterprises with heterogenous landscapes, but may be perceived "heavy". ...
MIME type - MDN Web Docs Glossary: Definitions of Web-related terms
purpose as filename extensions traditionally do on windows. ...
Method - MDN Web Docs Glossary: Definitions of Web-related terms
perty of an object. ...
Mozilla Firefox - MDN Web Docs Glossary: Definitions of Web-related terms
mozilla firefox is a free open-source browser whose development is overseen by the mozilla corporation. firefox runs on windows, os x, linux, and android. first released in november 2004, firefox is completely customizable with themes, plug-ins, and add-ons. firefox uses gecko to render webpages, and implements both current and upcoming web standards. learn more general knowledge mozilla firefox official website technical reference firefox developer documentations on mdn ...
NAT - MDN Web Docs Glossary: Definitions of Web-related terms
nat (network address translation) is a technique for letting multiple computers share an ip address. nat assigns unique addresses to each computer on the local network and adjusts incoming/outgoing network traffic to send data to the right place. learn more general knowledge webrtc protocols nat on wikipedia ...
Netscape Navigator - MDN Web Docs Glossary: Definitions of Web-related terms
ndreessen, a programmer who also wrote code for mosaic. netscape helped make the web graphical rather than a text-only experience. many browsing features became standard after netscape introduced them. netscape could display a webpage while loading, used javascript for forms and interactive content, and stored session information in cookies. despite netscape's technical advantages and initial dominance, by the late 1990s internet explorer swiftly overtook netscape in market share. learn more general knowledge netscape navigator on wikipedia ...
Null - MDN Web Docs Glossary: Definitions of Web-related terms
in computer science, a null value represents a reference that points, generally intentionally, to a nonexistent or invalid object or address. the meaning of a null reference varies among language implementations. in javascript, null is marked as one of the primitive values, because its behaviour is seemingly primitive. but in certain cases, null is not as "primitive" as it first seems! every object is derived from null value, and therefore typeof operator returns object for it: typeof null === 'object' // true ...
Number - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, number is a numeric data type in the double-precision 64-bit floating point format (ieee 754). in other programming languages different numeric types exist; for example, integers, floats, doubles, or bignums. learn more general knowledge numeric types on wikipedia technical reference the javascript data structure: number the javascript global object number ...
OTA - MDN Web Docs Glossary: Definitions of Web-related terms
over the air (ota) refers to automatic updating of software on connected devices from a central server. all device owners receiving a given set of updates are on the same "channel", and each device often can access several channels (e.g. for production or engineering builds). learn more general knowledge over-the-air programming on wikipedia creating and applying firefox os update packages ...
OpenGL - MDN Web Docs Glossary: Definitions of Web-related terms
opengl (open graphics library) is a cross-language, multi-platform application programming interface (api) for rendering 2d and 3d vector graphics. the api is typically used to interact with a graphics processing unit (gpu), to achieve hardware-accelerated rendering. learn more general knowledge opengl on wikipedia ...
Operator - MDN Web Docs Glossary: Definitions of Web-related terms
reserved syntax consisting of punctuation or alphanumeric characters that carries out built-in functionality. for example, in javascript the addition operator ("+") adds numbers together and concatenates strings, whereas the "not" operator ("!") negates an expression — for example making a true statement return false. learn more general knowledge operator (computer programming) on wikipedia technical reference javascript operators ...
PAC - MDN Web Docs Glossary: Definitions of Web-related terms
function findproxyforurl(url, host) { /* ... */ } ret = findproxyforurl(url, host) see proxy auto-configuration (pac) file for details about how these are used and how to create new ones. ...
Page load time - MDN Web Docs Glossary: Definitions of Web-related terms
load times can vary greatly between users depending on device capabilities, network conditions, and, to a lesser extent, distance from the server. ...
Parameter - MDN Web Docs Glossary: Definitions of Web-related terms
nto functions. note the difference between parameters and arguments: function parameters are the names listed in the function's definition. function arguments are the real values passed to the function. parameters are initialized to the values of the arguments supplied. two kinds of parameters: input parameters the most common kind; they pass values into functions. depending on programming language, input parameters can be passed several ways (e.g., call-by-value, call-by-address, call-by-reference). output/return parameters primarily return multiple values from a function, but not recommended since they cause confusion learn more general knowledge difference between parameter and argument on wikipedia technical reference function declaration function expression ...
Placeholder names - MDN Web Docs Glossary: Definitions of Web-related terms
placeholder names are commonly used in cryptography to indicate the participants in a conversation, without resorting to terminology such as "party a," "eavesdropper," and "malicious attacker." the most commonly used names are: alice and bob, two parties who want to send messages to each other, occasionally joined by carol, a third participant eve, a passive attacker who is eavesdropping on alice and bob's conversation mallory, an active attacker ("man-in-the-middle") who is able to modify their conversation and replay old messages ...
Prefetch - MDN Web Docs Glossary: Definitions of Web-related terms
there are a plethora of links to external websites that may be clicked on, like search engine results, dns prefetching resolves domain names in advance thereby speeding up load times by reducing the time associated with domain lookup at request time. <link rel="dns-prefetch" href="https://example.com/"> link prefetching link prefetching is a performance optimization technique that works by assuming which links the user is likely to click, then downloading the content of those links. if the user decides to click on one of the links, then the page will be rendered instantly as the content has already been downloaded. the prefetch hints are sent in http headers: link: ; rel=dns-prefetch, ; as=script; rel=preload, ; rel=prerender, ; as=style; rel=preload prefetch attribute...
Primitive - MDN Web Docs Glossary: Definitions of Web-related terms
most of the time, a primitive value is represented directly at the lowest level of the language implementation. all primitives are immutable, i.e., they cannot be altered. ...
Progressive Enhancement - MDN Web Docs Glossary: Definitions of Web-related terms
progressive enhancement is a design philosophy that provides a baseline of essential content and functionality to as many users as possible, while delivering the best possible experience only to users of the most modern browsers that can run all the required code. feature detection is generally used to determine whether browsers can handle more modern functionality, while polyfills are often used to add missing features with javascript. special notice should be taken of accessibility. acceptable alternatives should be provided where possible. progressive enhancement is a useful technique that allows web developers to focus on developing the best possible websites while making those websites work on multiple unknown user agents. graceful degradation is related but is not the same th...
Python - MDN Web Docs Glossary: Definitions of Web-related terms
python is a high level general-purpose programming language. it uses a multi-paradigm approach, meaning it supports procedural, object-oriented, and some functional programming constructs. it was created by guido van rossum as a successor to another language (called abc) between 1985 and 1990, and is currently used on a large array of domains like web development, desktop applications, data science, devops, and automation/productivity. python is developed under an osi-approved open source license, making it freely usable and distributable, even for commercial use. python's license is administered by the python software foundation. ...
RAIL - MDN Web Docs Glossary: Definitions of Web-related terms
user; the end goal isn't to make your site perform fast on any specific device, it's to make users happy." there are 4 stages of interaction: page load, idle, response to input, and scrolling and animation. in acronym order, the main tenets are: response respond to users immediately, acknowledging any user input in 100ms or less. animation when animating, render each frame in under 16ms, aiming for consistency and avoiding jank. idle when using the main javascript thread, work in chunks for less than 50ms to free up the thread for user interactions. load deliver interactive content in less than 1 second. ...
RGB - MDN Web Docs Glossary: Definitions of Web-related terms
red green blue (rgb) is a color model that represents colors as mixtures of three underlying components (or channels), namely, red, green, and blue. each color is described by a sequence of three numbers (typically between 0.0 and 1.0, or between 0 and 255) that represent the different intensities (or contributions) of red, green, and blue, in determining the final color. there are many ways to describe the rgb components of a color. in css they can be represented as a single 24-bit integer in hexadecimal notation (for example, #add8e6 is light blue), or in functional notation as three separate 8-bit integers (for example, rgb(46, 139, 87) is sea green). in opengl, webgl, and glsl the red-green-blue components are fractions (floating-point numbers between 0.0 and 1.0), although in ...
Random Number Generator - MDN Web Docs Glossary: Definitions of Web-related terms
truly random numbers (say, from a radioactive source) are utterly unpredictable, whereas all algorithms are predictable, and a prng returns the same numbers when passed the same starting parameters or seed. prngs can be used for a variety of applications, such as games. a cryptographically secure prng is a prng with certain extra properties making it suitable for use in cryptography. ...
Reflow - MDN Web Docs Glossary: Definitions of Web-related terms
reflow happens when a browser must process and draw part or all of a webpage again, such as after an update on an interactive site. learn more google article "minimizing browser reflow" ...
Robots.txt - MDN Web Docs Glossary: Definitions of Web-related terms
robots.txt is a file which is usually placed in the root of any website. it decides whether crawlers are permitted or forbidden access to the web site. for example, the site admin can forbid crawlers to visit a certain folder (and all the files therein contained) or to crawl a specific file, usually to prevent those files being indexed by other search engines. learn more general knowledge robots.txt on wikipedia https://developers.google.com/search/reference/robots_txt standard specification draft: https://tools.ietf.org/html/draft-rep-wg-topic https://www.robotstxt.org/ ...
Ruby - MDN Web Docs Glossary: Definitions of Web-related terms
in a web context, ruby is often used server-side with the ruby on rails (ror) framework to produce websites/apps. ruby is also a method for annotating east asian text in html documents to provide pronunciation information; see the <ruby> element. ...
SCTP - MDN Web Docs Glossary: Definitions of Web-related terms
sctp (stream control transmission protocol) is an ietf standard for a transport protocol which enables the reliable, in-order transmission of messages while offering congestion control, multi-homing, and other features to improve reliability and stability of the connection. it's used for sending traditional telephone calls over the internet, but is also used for webrtc data. learn more general knowledge rfc 4960: stream control transmission protocol stream control transmission protocol on wikipedia ...
SDP - MDN Web Docs Glossary: Definitions of Web-related terms
here is a typical sdp message: v=0 o=alice 2890844526 2890844526 in ip4 host.anywhere.com s= c=in ip4 host.anywhere.com t=0 0 m=audio 49170 rtp/avp 0 a=rtpmap:0 pcmu/8000 m=video 51372 rtp/avp 31 a=rtpmap:31 h261/90000 m=video 53000 rtp/avp 32 a=rtpmap:32 mpv/90000 sdp is never used alone, but by protocols like rtp and rtsp. ...
Server - MDN Web Docs Glossary: Definitions of Web-related terms
e provided generally over local area networks or wide area networks such as the internet. ...
Signature (functions) - MDN Web Docs Glossary: Definitions of Web-related terms
ypes a return value and type exceptions that might be thrown or passed back information about the availability of the method in an object-oriented program (such as the keywords public, static, or prototype). in depth signatures in javascript javascript is a loosely typed or a dynamic language. that means you don't have to declare the type of a variable ahead of time. the type will get determined automatically while the program is being processed. a signature in javascript can still give you some information about the method: myobject.prototype.myfunction(value) the method is installed on an object called myobject. the method is installed on the prototype of myobject (thus it is an instance method) as opposed to being a static method. the name of the method is myfunction. the met...
Site - MDN Web Docs Glossary: Definitions of Web-related terms
this is computed by consulting a public suffix list to find the portion of the host which is counted as the public suffix (e.g. com, org or co.uk). the concept of a site is used in samesite cookies, as well as a web application's cross-origin resource policy. ...
Statement - MDN Web Docs Glossary: Definitions of Web-related terms
every program consists of a sequence of statements. ...
String - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, a string is one of the primitive values and the string object is a wrapper around a string primitive. ...
Style origin - MDN Web Docs Glossary: Definitions of Web-related terms
d. 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. author origin the author origin is the style origin which contains all of the styles which are part of the document, whether embedded within the html or loaded from an external stylesheet file. 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. learn more technical information css cascading and inheritance: cascading origins ...
Symmetric-key cryptography - MDN Web Docs Glossary: Definitions of Web-related terms
key can only be reversed using the other key. symmetric-key algorithms should be secure when used properly and are highly efficient, so they can be used to encrypt large amounts of data without having a negative effect on performance. most symmetric-key algorithms currently in use are block ciphers: this means that they encrypt data one block at a time. the size of each block is fixed and determined by the algorithm: for example aes uses 16-byte blocks. block ciphers are always used with a mode, which specifies how to securely encrypt messages that are longer than the block size. for example, aes is a cipher, while ctr, cbc, and gcm are all modes. using an inappropriate mode, or using a mode incorrectly, can completely undermine the security provided by the underlying cipher. ...
Synchronous - MDN Web Docs Glossary: Definitions of Web-related terms
synchronous refers to real-time communication where each party receives (and if necessary, processes and replies to) messages instantly (or as near to instantly as possible). a human example is the telephone — during a telephone call you tend to respond to another person immediately. many programming commands are also synchronous — for example when you type in a calculation, the environment will return the result to you instantly, unless you program it not to. learn more technical reference asynchronous synchronous and asynchronous requests using the xmlhttprequest() api ...
TCP handshake - MDN Web Docs Glossary: Definitions of Web-related terms
owser, sends a tcp synchronize packet to the server. the server receives the syn and sends back a synchronize-acknowledgement. the host receives the server's syn-ack and sends an acknowledge. the server receives ack and the tcp socket connection is established. this handshake step happens after a dns lookup and before the tls handshake, when creating a secure connection. the connection can be terminated independently by each side of the connection via a four-way handshake. ...
TLD - MDN Web Docs Glossary: Definitions of Web-related terms
a tld (top-level domain) is the most generic domain in the internet's hierarchical dns (domain name system). a tld is the final component of a domain name, for example, "org" in developer.mozilla.org. icann (internet corporation for assigned names and numbers) designates organizations to manage each tld. depending on how strict an administrating organization might be, tld often serves as a clue to the purpose, ownership, or nationality of a website. consider an example internet address: https://developer.mozilla.org here org is the tld; mozilla.org is the second-level domain name; and developer is a subdomain name. all together, these constitute a fully-qualified domain name; the addition of https:// makes this a complete url. iana today distinguishes the following groups of top-l...
Transport Layer Security (TLS) - MDN Web Docs Glossary: Definitions of Web-related terms
ther protocols. 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. all modern browsers support the tls protocol, requiring the server to provide a valid digital certificate confirming its identity in order to establish a secure connection. it is possible for both the client and server to mutually authenticate each other, if both parties provide their own individual digital certificates. note: tls 1.0 and 1.1 support will be removed from all major browsers in early 2020; you'll need to make sure your web server supports tls 1.2 or 1.3 going forward. from version 74 onwards, ...
TOFU - MDN Web Docs Glossary: Definitions of Web-related terms
trust on first use (tofu) is a security model in which a client needs to create a trust relationship with an unknown server. to do that, clients will look for identifiers (for example public keys) stored locally. if an identifier is found, the client can establish the connection. if no identifier is found, the client can prompt the user to determine if the client should trust the identifier. tofu is used in the ssh protocol, in http public key pinning (hpkp) where the browsers will accept the first public key returned by the server, and in strict-transport-security (hsts) where a browser will obey the redirection rule. learn more http public key pinning (hpkp) public-key-pins wikipedia: tofu ...
Thread - MDN Web Docs Glossary: Definitions of Web-related terms
ven when the user isn't currently using that site. this is used to create sites capable of notifying the user when things happen while they're not actively engaged with a site. such as notifying a user they have received new email even though they're not currently logged into their mail service. overall it can be observed these threads within our operating system are extremely helpful. they help minimise the context switching time, enables more efficient communication and allows further use of the multiprocessor architecture. ...
UDP (User Datagram Protocol) - MDN Web Docs Glossary: Definitions of Web-related terms
udp provides checksums for data integrity, and port numbers for addressing different functions at the source and destination of the datagram. ...
Variable - MDN Web Docs Glossary: Definitions of Web-related terms
a variable is a named reference to a value. that way an unpredictable value can be accessed through a predetermined name. learn more general knowledge variable (computer science) on wikipedia technical reference declaring variables in javascript var statement in javascript ...
WebAssembly - MDN Web Docs Glossary: Definitions of Web-related terms
webassembly (abbr. wasm) is an open binary programming format that can be run in modern web browsers in order to gain performance and/or provide new features for web pages. ...
WebIDL - MDN Web Docs Glossary: Definitions of Web-related terms
webidl is the interface description language used to describe the data types, interfaces, methods, properties, and other components which make up a web application programming interface (api). it uses a somewhat stylized syntax which is independent of any specific programming language, so that the underlying code which is used to build each api can be written in whatever language is most appropriate, while still being possible to map the api's components to javascript-compatible constructs. webidl is used in nearly every api specification for the web, and due to its standard format and syntax, the programmers who create web browsers can more easily ensure that their browsers are compatible with one another, regardless of how they choose to write the code to implement the api. learn ...
Web standards - MDN Web Docs Glossary: Definitions of Web-related terms
tes and network systems must conform to: ietf (internet engineering task force): internet standards (std), which among other things govern set-up and use of uris, http, and mime w3c: specifications for markup language (e.g., html), style definitions (i.e., css), dom, accessibility iana (internet assigned numbers authority): name and number registries ecma intl.: scripting standards, most prominently for javascript iso (international organization for standardization): standards governing a diverse array of aspects, including character encodings, website management, and user-interface design learn more general knowledge web standards on wikipedia ...
Wrapper - MDN Web Docs Glossary: Definitions of Web-related terms
for example, sdk libraries for aws are examples of wrappers. ...
XLink - MDN Web Docs Glossary: Definitions of Web-related terms
simple xlinks are "supported" in firefox (at least in svg and mathml), though they do not work as links if one loads a plain xml document with xlinks and attempts to click on the relevant points in the xml tree. for those who may have found xlink 1.0 cumbersome for regular links, xlink 1.1 drops the need to specify xlink:type="simple" for simple links. xlink is used in svg, mathml, and other important standards. ...
firewall - MDN Web Docs Glossary: Definitions of Web-related terms
a firewall is a system that filters network traffic. it can either let it pass or block it, according to some specified rules. for example, it can block incoming connections aimed at a certain port or outgoing connections to a certain ip address. firewalls can be as simple as a single piece of software, or more complex, like a dedicated machine whose only function is to act as a firewall. learn more general knowledge firewall (computing) on wikipedia ...
HTTPS - MDN Web Docs Glossary: Definitions of Web-related terms
...
JPEG - MDN Web Docs Glossary: Definitions of Web-related terms
jpeg (joint photographic experts group) is a commonly used method of lossy compression for digital images. jpeg compression is composed of three compression techniques applied in successive layers, including chrominance subsampling, discrete cosine transformation and quantization, and run-length delta & huffman encoding. chroma subsampling involves implementing less resolution for chroma information than for luma information, taking advantage of the human visual system's lower acuity for color differences than for luminance. a discrete cosine transform expresses a finite sequence of data points in terms of a sum of cosine functions oscillating at different frequencies. learn more general knowledge jpeg on wikipedia ...
Loop - MDN Web Docs Glossary: Definitions of Web-related terms
an example would be the process of getting an item of data and changing it, and then making sure some condition is checked such as, if a counter has reached a prescribed number. examples for loop syntax: for (statement 1; statement 2; statement 3){ execute code block } statement 1 is executed once before the code block is run. statement 2 defines the condition needed to execute the code block. statement 3 is executed every time the code block is run. ...
Property (JavaScript) - MDN Web Docs Glossary: Definitions of Web-related terms
l object instances. ...
Speculative parsing - MDN Web Docs Glossary: Definitions of Web-related terms
ox since firefox 4, support speculative parsing off of the main thread. it parses ahead while scripts are being downloaded and executed. the html parser starts speculative loads for scripts, style sheets and images it finds ahead in the stream and runs the html tree construction algorithm speculatively. the upside is that when a speculation succeeds, there's no need to reparse the part of the incoming file that was already scanned for scripts, style sheets and images. the downside is that there's more work lost when the speculation fails. this document helps you avoid the kind of things that make speculation fail and slow down the loading of your page. to make speculative loads of linked scripts, style sheets and images successful, avoid document.write. if you use a <base> element to overri...
Assessment: Accessibility troubleshooting - Learn web development
ree to put them in appropriate <style> / <script> elements. the finished assessment site should look like so: you will see some differences/issues with the display of the starting state of the assessment — this is mainly due to the differences in the markup, which in turn cause some styling issues as the css is not applied properly. don't worry — you'll be fixing these problems in the upcoming sections! note: if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. project brief for this project, you are presented with a fictional nature site displaying a "factual" article about bears. as it stands, it has a number of accessibility issues — your task is to explore the existing site and fix them to the best of your abiliti...
HTML: A good basis for accessibility - Learn web development
default, purple and underlined if visited, and with a focus-ring when they receive keyboard focus. color should not be used as the sole method of distinguishing links from non-linking content. link text color, like all text, has to be significantly different from the background color (a 4.5:1 contrast). in addition, links should visually be significantly different from non-linking text. with a minimum contrast requirement of 3:1 between link text and surrounding text and between default, visited, and focus/active states and a 4:5 contrast between all those state colors and the background color. onclick events anchor tags are often abused with the onclick event to create pseudo-buttons by setting href to "#" or "javascript:void(0)" to prevent the page from refreshing. these values cause ...
HTML: A good basis for accessibility - Learn web development
default, purple and underlined if visited, and with a focus-ring when they receive keyboard focus. color should not be used as the sole method of distinguishing links from non-linking content. link text color, like all text, has to be significantly different from the background color (a 4.5:1 contrast). in addition, links should visually be significantly different from non-linking text. with a minimum contrast requirement of 3:1 between link text and surrounding text and between default, visited, and focus/active states and a 4:5 contrast between all those state colors and the background color. onclick events anchor tags are often abused with the onclick event to create pseudo-buttons by setting href to "#" or "javascript:void(0)" to prevent the page from refreshing. these values cause ...
Test your skills: WAI-ARIA - Learn web development
ive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. wai-aria 1 in our first aria task, we present you with a section of non-semantic markup, which is obviously meant to be a list. assuming you are not able to change the elements used, how can you allow screenreader users to recognize this as a list? try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. wai-aria 2 in our second wai-aria task, we present a simple search form, and we want you to add in a couple of wai-ari...
WAI-ARIA basics - Learn web development
d="age" aria-required="true"> if you save the example now and test it with a screenreader, you should hear something like "enter your name star, required, edit text". it might also be useful if we give screenreader users and sighted users an idea of what the age value should be. this is often presented as a tooltip, or placeholder inside the form field perhaps. wai-aria does include aria-valuemin and aria-valuemax properties to specify min and max values, but these currently don't seem very well supported; a better supported feature is the html5 placeholder attribute, which can contain a message that is shown in the input when no value is entered, and is read out by a number of screenreaders. update your number input like this: <input type="number" name="age" id="age" placeholder="enter...
Advanced styling effects - Learn web development
...
Fundamental CSS comprehension - Learn web development
he footer's content box. recall from earlier that the content box height should be 30px — this gives you all the numbers you need to calculate the line height. as a last little touch, give the paragraph inside the <article> an appropriate padding value so that its left edge lines up with the <h2> and footer paragraph, and set its color to be fairly light so it is easy to read. note: bear in mind that the second ruleset sets font-size: 10px; on the <html> element — this means that for any descendants of <html>, an em will be equal to 10px rather than 16px as it is by default. (this is of course, provided the descendants in question don't have any ancestors sitting in between them and <html> in the hierarchy that have a different font-size set on them. this could affect the values you n...
Images, media, and form elements - Learn web development
rt of the grid area or flex container. you can see this happening in the example below where we have a two column, two row grid container, which has four items in it. all of the <div> elements have a background color and stretch to fill the row and column. the image, however, does not stretch. if you are following these lessons in order then you may not have looked at layout yet. just keep in mind that replaced elements, when they become part of a grid or flex layout, have different default behaviors, essentially to avoid them being stretched strangely by the layout. to force the image to stretch to fill the grid cell it is in, you'd have to do something like following: img { width: 100%; height: 100%; } this would however stretch the image, so probably isn't what you'd want to do.
Test your skills: Images and Form elements - Learn web development
helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. task one in this task, you have an image that is overflowing the box. we want the image to scale down to fit inside the box without any extra white space, but we do not mind if some part of the image is cropped. in the example below see if you can match the image above. for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. task two in this task, you have a simple form. your task is to make the following changes to the way this form looks: use attribute selectors to target th...
Pseudo-classes and pseudo-elements - Learn web development
matches when an element has focus. :focus-visible matches when an element has focus and the focus should be visible to the user. :focus-within matches an element with focus plus an element with a descendent that has focus. :future matches the elements after the current element. :hover matches when the user hovers over an element. :indeterminate matches ui elements whose value is in an indeterminate state, usually checkboxes. :in-range matches an element with a range when its value is in-range. :invalid matches an element, such as an <input>, in an invalid state. :lang matches an element based on language (value of the html lang attribute). :last-child matches an element which is last...
Introduction to CSS layout - Learn web development
ome flex items. we can see this in a simple example. the html markup below gives us a containing element, with a class of wrapper, inside which are three <div> elements. by default these would display as block elements, below one another, in our english language document. however, if we add display: flex to the parent, the three items now arrange themselves into columns. this is due to them becoming flex items and being affected by some initial values that flexbox sets on the flex container. they are displayed in a row, because the initial value of flex-direction set on their parent is row. they all appear to stretch to the height of the tallest item, because the initial value of the align-items property set on their parent is stretch. this means that the items stretch to the height of the ...
Test your skills: Multicol - Learn web development
urther help section at the bottom of this page. multicol one in this task you need to create three columns, with a 50px gap between each column. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. multicol two create columns which have a minimum width of 200px. then, add a 5px, grey rule between each column, ensuring there is 10px of space between the edge of the rule and the column content. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. multicol three cause the element c...
Practical positioning examples - Learn web development
e the separate tabs as separate webpages, and just have the tabs clicking through to the separate pages to create the effect?" this code would be simpler, yes, but then each separate "page" view would actually be a newly-loaded webpage, which would make it harder to save information across views, and integrate this feature into a larger ui design. in addition, so-called "single page apps" are becoming very popular — especially for mobile web uis — because having everything served as a single file cuts down on the number of http requests required to view all the content, thereby improving performance. 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 xml...
Test your skills: Media Queries and Responsive Design - Learn web development
oint. open this in your browser and you will find a wireframed site which will load in a mobile device in a readable manner. you can drag your window smaller or use the responsive design view in firefox devtools to view this as if on a phone. your task is to create a desktop version of this layout which displays when there is enough screen width to accomodate it. you can see the layout you are aiming for in the screenshot below. there are a number of ways that you could create the desktop layout, enjoy experimenting. you could also add a second breakpoint perhaps creating a layout that would work well on a tablet in portrait mode. assessment or further help you can practice these examples in the interactive editors mentioned above. if you would like your work assessed, or are stuck and...
How CSS works - Learn web development
n to html.) objective: to understand the basics of how css and html are parsed by the browser, and what happens when a browser encounters css it does not understand. how does css actually work? when a browser displays a document, it must combine the document's content with its style information. it processes the document in a number of stages, which we've listed below. bear in mind that this is a very simplified version of what happens when a browser loads a webpage, and that different browsers will handle the process in different ways. but this is roughly what happens. the browser loads the html (e.g. receives it from the network). it converts the html into a dom (document object model). the dom represents the document in the computer's memory. the dom is explained in...
CSS first steps - Learn web development
looks like, and how you can start using it to add styling to html. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites before starting this module, you should have: basic familiarity with using computers, and using the web passively (i.e. looking at it, consuming the content.) a basic work environment set up as detailed in installing basic software, and an understanding of how to create and manage files, as detailed in dealing with files. basic familiarity with html, as discussed in the introduction to html module. note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out ...
create fancy boxes - Learn web development
l snippet (which provide us an opportunity to see how to also handle design localization): <blockquote>people who think they know everything are a great annoyance to those of us who do. <i>isaac asimov</i></blockquote> <blockquote lang="fr">l'intelligence, c'est comme les parachutes, quand on n'en a pas, on s'écrase. ...
Fundamental text and font styling - Learn web development
e: font styles: properties that affect the font that is applied to the text, affecting what font is applied, how big it is, whether it is bold, italic, etc. text layout styles: properties that affect the spacing and other layout features of the text, allowing manipulation of, for example, the space between lines and letters, and how the text is aligned within the content box. note: bear in mind that the text inside an element is all affected as one single entity. you can't select and style subsections of text unless you wrap them in an appropriate element (such as a <span> or <strong>), or use a text-specific pseudo-element like ::first-letter (selects the first letter of an element's text), ::first-line (selects the first line of an element's text), or ::selection (selects the text cu...
What do common web layouts contain? - Learn web development
stem. main content the biggest region, containing content unique to the current page. stuff on the side 1) information complementing the main content; 2) information shared among a subset of pages; 3) alternative navigation system. in fact, everything not absolutely required by the page's main content. footer visible at the bottom of every page on the site. like the header, contains less prominent global information like legal notices or contact info. these elements are quite common in all form factors, but they can be laid out different ways. here are some examples (1 represents header, 2 footer; a main content; b1, b2 things on the side): 1-column layout. especially important for mobile browsers so you don't clutter the small screen up. 2-column layout. often used to target tabl...
How does the Internet work? - Learn web development
to a public infrastructure in the 1980s with the support of many public universities and private companies. the various technologies that support the internet have evolved over time, but the way it works hasn't changed that much: internet is a way to connect computers all together and ensure that, whatever happens, they find a way to stay connected. active learning how the internet works in 5 minutes: a 5 minute video to understand the very basics of internet by aaron titus. how does the internet work? detailed well visualized 8 minute video. deeper dive a simple network when two computers need to communicate, you have to link them, either physically (usually with an ethernet cable) or wirelessly (for example with wifi or bluetooth systems). all modern computers can sustain any of th...
How do you upload your files to a web server? - Learn web development
omething like this: now press connect to connect to the sftp server. note: make sure your hosting provider offers sftp (secure ftp) connection to your hosting space. ftp is inherently insecure, and you shouldn't use it. here and there: local and remote view once connected, your screen should look something like this (we've connected to an example of our own to give you an idea): let's examine what you're seeing: on the center left pane, you see your local files. navigate into the directory where you store your website (e.g. mdn). on the center right pane, you see remote files. we are logged into our distant ftp root (in this case, users/demozilla) you can ignore the bottom and top panes for now. respectively, these are a log of messages showing the connection status between your...
What is a URL? - Learn web development
h 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. other technologies, such as css or javascript, use urls extensively, and these are really the heart of the web. absolute urls vs relative urls what we saw above is called an absolute url, but there is also something called a relative url. let's examine what that distinction means in more detail. the required parts of a url depend to a great extent on the context in which the url is used. in your browser's address bar, a url doesn't have any context, so you must provide a full (or absolute) url, like the ones we saw above. you don't need to include the protocol (the browser uses http by default) or the port (which is only required when the tar...
What software do I need to build a website? - Learn web development
or public viewing, you'll have to upload your webpages to your web server. you can buy space on a server from various providers (see how much does it cost to do something on the web?). once you settle on which provider to use, the provider will email you the access information, usually in the form of an sftp url, username, password, and other information needed to connect to their server. bear in mind that (s)ftp is now somewhat old-fashioned, and other uploading systems are starting to become popular, such as rsync and git/github. note: ftp is inherently insecure. you should make sure your hosting provider allows use of a secure connection, e.g. sftp or rsync over ssh. uploading files to a web server is a very important step while creating a website, so we cover it in detail in a separat...
How do you set up a local testing server? - Learn web development
nder the download section, click the link for python "3.xxx". at the bottom of the page, choose the windows x86 executable installer and download it. when it has downloaded, run it. on the first installer page, make sure you check the "add python 3.xxx to path" checkbox. click install, then click close when the installation has finished. open your command prompt (windows)/ terminal (macos/ linux). to check python is installed, enter the following command: python -v # or you might have the py command available, # in which case try py -v this should return a version number. if this is ok, navigate to the directory that your example is inside, using the cd command. # include the directory name to enter it, for example cd desktop # use two dots to jump up one dir...
Basic native form controls - Learn web development
. we'll cover those in the next article, the html5 input types. password field one of the original input types was the password text field type: <input type="password" id="pwd" name="pwd"> the password value doesn't add any special constraints to the entered text, but it does obscure the value entered into the field (e.g. with dots or asterisks) so it can't be easily read by others. keep in mind this is just a user interface feature; unless you submit your form securely, it will get sent in plain text, which is bad for security — a malicious party could intercept your data and steal passwords, credit card details, or whatever else you've submitted. the best way to protect users from this is to host any pages involving forms over a secure connection (i.e. at an https:// ... address), s...
Example 2 - Learn web development
t : .2em solid #000; border-radius: 0 .1em .1em 0; background-color : #000; color : #fff; } .select .optlist { z-index : 2; list-style: none; margin : 0; padding: 0; background: #f0f0f0; border: .2em solid #000; border-top-width : .1em; border-radius: 0 0 .4em .4em; box-shadow: 0 .2em .4em rgba(0,0,0,.4); -moz-box-sizing : border-box; box-sizing : border-box; min-width : 100%; max-height: 10em; /* 100px */ overflow-y: auto; overflow-x: hidden; } .select .option { padding: .2em .3em; } .select .highlight { background: #000; color: #ffffff; } javascript content window.addeventlistener("load", function () { var form = document.queryselector('form'); form.classlist.remove("no-widget"); form.classlist.add("widget"); }); result for js no j...
Example 3 - Learn web development
t : .2em solid #000; border-radius: 0 .1em .1em 0; background-color : #000; color : #fff; } .select .optlist { z-index : 2; list-style: none; margin : 0; padding: 0; background: #f0f0f0; border: .2em solid #000; border-top-width : .1em; border-radius: 0 0 .4em .4em; box-shadow: 0 .2em .4em rgba(0,0,0,.4); -moz-box-sizing : border-box; box-sizing : border-box; min-width : 100%; max-height: 10em; /* 100px */ overflow-y: auto; overflow-x: hidden; } .select .option { padding: .2em .3em; } .select .highlight { background: #000; color: #ffffff; } javascript content // ------- // // helpers // // ------- // nodelist.prototype.foreach = function (callback) { array.prototype.foreach.call(this, callback); } // -------------------- // // function...
Example 4 - Learn web development
t : .2em solid #000; border-radius: 0 .1em .1em 0; background-color : #000; color : #fff; } .select .optlist { z-index : 2; list-style: none; margin : 0; padding: 0; background: #f0f0f0; border: .2em solid #000; border-top-width : .1em; border-radius: 0 0 .4em .4em; box-shadow: 0 .2em .4em rgba(0,0,0,.4); -moz-box-sizing : border-box; box-sizing : border-box; min-width : 100%; max-height: 10em; /* 100px */ overflow-y: auto; overflow-x: hidden; } .select .option { padding: .2em .3em; } .select .highlight { background: #000; color: #ffffff; } javascript content // ------- // // helpers // // ------- // nodelist.prototype.foreach = function (callback) { array.prototype.foreach.call(this, callback); } // -------------------- // // function...
Example 5 - Learn web development
t : .2em solid #000; border-radius: 0 .1em .1em 0; background-color : #000; color : #fff; } .select .optlist { z-index : 2; list-style: none; margin : 0; padding: 0; background: #f0f0f0; border: .2em solid #000; border-top-width : .1em; border-radius: 0 0 .4em .4em; box-shadow: 0 .2em .4em rgba(0,0,0,.4); -moz-box-sizing : border-box; box-sizing : border-box; min-width : 100%; max-height: 10em; /* 100px */ overflow-y: auto; overflow-x: hidden; } .select .option { padding: .2em .3em; } .select .highlight { background: #000; color: #ffffff; } javascript content // ------- // // helpers // // ------- // nodelist.prototype.foreach = function (callback) { array.prototype.foreach.call(this, callback); } // -------------------- // // function...
How to structure a web form - Learn web development
are usable and accessible. 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. the <form> element the <form> element formally defines a form and attributes that determine the form's behavior. each time you want to create an html form, you must start it by using this element, nesting all the contents inside. many assistive technologies and browser plugins can discover <form> elements and implement special hooks to make them easier to use. we already met this in the previous article. warning: it's strictly forbidden to nest a form inside another form. nesting can...
Sending forms through JavaScript - Learn web development
a ); } btn.addeventlistener( 'click', function() { senddata( {test:'ok'} ); } ) here's the live result: note: this use of xmlhttprequest is subject to the same-origin policy if you want to send data to a third party web site. for cross-origin requests, you'll need cors and http access control. using xmlhttprequest and the formdata object building an http request by hand can be overwhelming. fortunately, the xmlhttprequest specification provides a newer, simpler way to handle form data requests with the formdata object. the formdata object can be used to build form data for transmission, or to get the data within a form element to manage how it's sent. note that formdata objects are "write only", which means you can change them, but not retrieve their contents. using this object ...
Test your skills: Form validation - Learn web development
editor or in an online editor. form validation 3 in our final task for this set, we are providing you with a similar example to what you saw in the accompanying article — a simple email address entry input. we would like you to use the constraint validation api, plus some form validation attributes, to program some custom error messages. make the input mandatory to fill in, and give it a minimum length of 10 characters. add an event listener that checks whether the inputted value is an email address, and whether it is long enough. if it doesn't look like an email address or is too short, provide the user with appropriate custom error messages. download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practic...
Test your skills: HTML5 controls - Learn web development
try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. html5 controls 2 next, we want you to implement a slider control to allow the user to choose a maximum number of people to invite to their party. implement a basic slider control to go along with the provided label. give it a minimum value of 1, maximum value of 30, and initial value of 10. create a corresponding output element to put the current value of the slider into. give it a class of invite-output, and semantically associate it with the input. if you do this correctly, the javascript included on the page will automatically update the output value when the slider is moved. try updating the live code below to recr...
Front-end web developer - Learn web development
earning pathway getting started time to complete: 1.5–2 hours prerequisites nothing except basic computer literacy. how will i know i'm ready to move on? there are no assessments in this part of the course. but make sure you don't skip. it is important to get you set up and ready to do work for exercises later on in the course. guides installing basic software — basic tool setup (15 min read) background on the web and web standards (45 min read) learning and getting help (45 min read) semantics and structure with html time to complete: 35–50 hours prerequisites nothing except basic computer literacy, and a basic web development environment. how will i know i'm ready to move on? the assessments in each module are designed to test your knowledge of the subject matter. ...
Dealing with files - Learn web development
at throughout this article, we ask you to name folders and files completely in lowercase with no spaces. this is because: many computers, particularly web servers, are case-sensitive. so for example, if you put an image on your website at, test-site/myimage.jpg and then in a different file you try to invoke the image as test-site/myimage.jpg, it may not work. browsers, web servers, and programming languages do not handle spaces consistently. for example, if you use spaces in your filename, some systems may treat the filename as two filenames. some servers will replace the areas in your filenames with "%20" (the character code for spaces in uris), resulting in all your links being broken. it's better to separate words with dashes, rather than underscores: my-file.html vs. my_file.html. t...
Using data attributes - Learn web development
data-* attributes allow us to store extra information on standard, semantic html elements without other hacks such as non-standard attributes, extra properties on dom, or node.setuserdata(). html syntax the syntax is simple. any attribute on any element whose attribute name starts with data- is a data attribute. say you have an article and you want to store some extra information that doesn’t have any visual representation. just use data attributes for that: <article id="electric-cars" data-columns="3" data-index-number="12314" data-parent="cars"> ... ...
What’s in the head? Metadata in HTML - Learn web development
link — these are called sitelinks, and are configurable in google's webmaster tools — a way to make your site's search results better in the google search engine. note: many <meta> features just aren't used any more. for example, the keyword <meta> element (<meta name="keywords" content="fill, in, your, keywords, here">) — which is supposed to provide keywords for search engines to determine relevance of that page for different search terms — is ignored by search engines, because spammers were just filling the keyword list with hundreds of keywords, biasing results. other types of metadata as you travel around the web, you'll find other types of metadata, too. a lot of the features you'll see on websites are proprietary creations, designed to provide certain sites (such as soci...
Introduction to HTML - Learn web development
d html. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. 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). you should have a basic work environment set up (as detailed in installing basic software), and understand how to create and manage files (as detailed in dealing with files). both are parts of our getting started with the web complete beginner's module. note: if you are working on a computer/tablet/other devices that doesn't let you create your own files, you can try out (most of) th...
Assessment: Structuring planet data - Learn web development
e data on the planets in our solar system, and get you to structure it into an html table. prerequisites: before attempting this assessment you should have already worked through all the articles in this module. objective: to test comprehension of html tables and associated features. starting point to start the assessment, make local copies of blank-template.html, minimal-table.css, and planets-data.txt in a new directory in your local computer. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. note: alternatively, you could use a site like jsbin or glitch to do your assessment. you could paste the html, css and javascript into one of these online editors. if the online editor you are using doe...
HTML Tables - Learn web development
Learn › HTML › Tables
this module takes you through all you need to know about structuring tabular data using html. ...
Structuring the web with HTML - Learn web development
available elements or even a new element that you define. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites before starting this topic, you should have at least basic familiarity with using computers and using the web passively (i.e. just looking at it, consuming the content). you should have a basic work environment set up as detailed in installing basic software, and understand how to create and manage files, as detailed in dealing with files — both are parts of our getting started with the web complete beginner's module. it is recommended that you work through getting started with the web before attempting this topic, however, it isn't absolutely n...
Image gallery - Learn web development
put the section of code below the "looping through images" comment inside a loop that loops through all 5 images — you just need to loop through five numbers, one representing each image. in each loop iteration, replace the xxx placeholder value with a string that will equal the path to the image in each case. we are setting the value of the src attribute to this value in each case. bear in mind that in each case, the image is inside the images directory and its name is pic1.jpg, pic2.jpg, etc. adding an onclick handler to each thumbnail image in each loop iteration, you need to add an onclick handler to the current newimage — this handler should find the value of the src attribute of the current image. set the src attribute value of the displayed-img <img> to the src value passed ...
Function return values - Learn web development
a function related tips: look at another example of writing error handling into functions. it is generally a good idea to check that any necessary parameters are validated, and that any optional parameters have some kind of default value provided. this way, your program will be less likely to throw errors. think about the idea of creating a function library. as you go further into your programming career, you'll start doing the same kinds of things over and over again. it is a good idea to create your own library of utility functions to do these sorts of things. you can copy them over to new code, or even just apply it to html pages wherever you need it. test your skills! you've reached the end of this article, but can you remember the most important information? you can find some furt...
Client-side storage - Learn web development
ady in the database are displayed as soon as the page loads. you'll see this defined later on. finally for this section, we'll add probably the most important event handler for setting up the database: request.onupgradeneeded. this handler runs if the database has not already been set up, or if the database is opened with a bigger version number than the existing stored database (when performing an upgrade). add the following code, below your previous handler: // setup the database tables if this has not already been done request.onupgradeneeded = function(e) { // grab a reference to the opened database let db = e.target.result; // create an objectstore to store our notes in (basically like a single table) // including a auto-incrementing key let objectstore = db.createobj...
Third-party APIs - Learn web development
rn; } fetchresults(e); }; the first function is simple — we increment the pagenumber variable, then run the fetchresults() function again to display the next page's results. the second function works nearly exactly the same way in reverse, but we also have to take the extra step of checking that pagenumber is not already zero before decrementing it — if the fetch request runs with a minus page url parameter, it could cause errors. if the pagenumber is already 0, we simply return out of the function, to avoid wasting processing power (if we are already at the first page, we don't need to load the same results again). note: you can find our finished nytimes api example code on github (also see it running live here). youtube example we also built another example for you to ...
JavaScript First Steps - Learn web development
building blocks of javascript — variables. basic math in javascript — numbers and operators at this point in the course we discuss maths in javascript — how we can combine operators and other features to successfully manipulate numbers to do our bidding. handling text — strings in javascript next we'll turn our attention to strings — this is what pieces of text are called in programming. in this article we'll look at all the common things that you really ought to know about strings when learning javascript, such as creating strings, escaping quotes in string, and joining them together. useful string methods now we've looked at the very basics of strings, let's move up a gear and start thinking about what useful operations we can do on strings with built-in methods, such as fi...
Solve common problems in your JavaScript code - Learn web development
anonymous function? how do you specify parameters (or arguments) when invoking a function? what is function scope? what are return values, and how do you use them? objects how do you create an object? what is dot notation? what is bracket notation? how do you get and set the methods and properties of an object? what is this, in the context of an object? what is object-oriented programming? what are constructors and instances, and how do you create them? what different ways are there to create objects in javascript? json how do you structure json data, and read it from javascript? how can you load a json file into a page? how do you convert a json object to a text string, and back again? events what are event handlers and how do you use them? what are inline event...
Introducing JavaScript objects - Learn web development
javascript object syntax, and revisit some javascript features we've already looked at earlier on in the course, reiterating the fact that many of the features you've already dealt with are in fact objects. object-oriented javascript for beginners with the basics out of the way, we'll now focus on object-oriented javascript (oojs) — this article presents a basic view of object-oriented programming (oop) theory, then explores how javascript emulates object classes via constructor functions, and how to create object instances. object prototypes prototypes are the mechanism by which javascript objects inherit features from one another, and they work differently to inheritance mechanisms in classical object-oriented programming languages. in this article, we explore that difference, explain...
CSS performance optimization - Learn web development
king, unless the browser knows the css is not currently needed. the browser can paint the page once it has downloaded the css and built the css object model. browsers follow a specific rendering path: paint only occurs after layout, which occurs after the render tree is created, which in turn requires both the dom and the cssom trees. to optimize the cssom construction, remove unnecessary styles, minify, compress and cache it, and split css not required at page load into additional files to reduce css render blocking. optimizing for render blocking css can scope styles to particular conditions with media queries. media queries are important for a responsive web design and help us optimize a critical rendering path. the browser blocks rendering until it parses all of these styles but will no...
The business case for web performance - Learn web development
ng how cumulative experiences impact conversion and retention rates. performance budgets setting a web performance budget can help you make sure the team stays on track in keeping the site and help prevent regressions. a performance budget is a set of limits that are set to specify limits, such as maximum number of http requests allowed, the maximum total size of all the assets combined, the minimum allowable fps on a specific device, etc, that must be maintained. the budget can be applied to a single file, a file type, all files loaded on a page, a specific metric, or a threshold over a period of time.the budget reflects reachable goals; whehter they are time, quantity, or rule based. definining and promoting a budget helps performance proponent advocates for good user experience agai...
React resources - Learn web development
objective: to provide further resources for learning more about react. ...
Using Vue computed properties - Learn web development
ous 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. these work similarly to methods, but only re-run when one of their dependencies changes. prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. vue components are written as a combination of javascript objects that manage the app's data and an html-based template syntax that maps to the underlying dom structure. for installation, and to use some of the more advanced features of vue (like single file components or render functions), you'll need a terminal with node + npm installed. objective: to learn ...
Adding a new todo form: Vue events, methods, and models - Learn web development
r users to enter their own todo items into the app, and for that we'll need a text <input>, an event to fire when the data is submitted, a method to fire upon submission to add the data and rerender the list, and a model to control the data. this is what we'll cover in this article. prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. vue components are written as a combination of javascript objects that manage the app's data and an html-based template syntax that maps to the underlying dom structure. for installation, and to use some of the more advanced features of vue (like single file components or render functions), you'll need a terminal with node + npm installed. objective: to learn ...
Rendering a list of Vue components - Learn web development
've got a fully working component; we're now ready to add multiple todoitem components to our app. 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. prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. vue components are written as a combination of javascript objects that manage the app's data and an html-based template syntax that maps to the underlying dom structure. for installation, and to use some of the more advanced features of vue (like single file components or render functions), you'll need a terminal with node + npm installed. objective: to learn ...
Cross browser testing - Learn web development
rovide a working experience rather than crashing/erroring in some browsers. this article details how to write your own simple feature detection, how to use a library to speed up implementation, and native features for feature detection such as @supports. introduction to automated testing manually running tests on several browsers and devices, several times per day, can get tedious and time-consuming. to handle this efficiently, you should become familiar with automation tools. in this article, we look at what is available, how to use task runners, and the basics of how to use commercial browser test automation apps such as sauce labs and browser stack. setting up your own test automation environment in this article, we will teach you how to install your own automation environment and run ...
Understanding client-side web development tools - Learn web development
your goal. get started guides 1. client-side tooling overview in this article we provide an overview of modern web tooling, what kinds of tools are available and where you’ll meet them in the lifecycle of web app development, and how to find help with individual tools. 2. command line crash course in your development process you'll undoubtedly be required to run some command in the terminal (or on the "command line" — these are effectively the same thing). this article provides an introduction to the terminal, the essential commands you'll need to enter into it, how to chain commands together, and how to add your own command line interface (cli) tools. 3. package management basics in this article we'll look at package managers in some detail to understand how we can use them i...
ChromeWorkers and the Chrome worker loader
n in the "this page" menu. once you've saved your new page, come back to this one and force-refresh this page. that will regenerate the table of contents below for all readers. chrome worker modulesthe preferred way to define and load modules for chrome workers is to use the chrome worker module loader. this module loader should not surprise developers familiar with commonjs, as it implements a minimal commonjs require(). ...
Links and Resources
well as open source accessibility. guidelines & standards information and resources on section 508 - legal policy for us government purchases requiring software accessibility. wai - web accessibility initiative web content accessibility guidelines (wcag) 1.0 the first set of official guidelines from the w3c web accessibility initiative (wai). the european union is looking to base their upcoming accessibility regulations on these guidelines. wai interest group - discussion list for standards in web accessibility. web accessibility checklist from ibm. ibm's java accessibility checklist - guidelines to making java accessibility. accessibility information resource center for developers at adobe - flash mx accessibility, pdf document accessibility and actionscript accessibility. on...
Index
blishing an add-on. if you just want to get started, head to the submit a new add-on page on amo. 683 source code submission add-ons, extensions, review policy, distribution to complete the review process at addons.mozilla.org (amo), reviewers must be able to read the code in your extension. some build processes render extension code difficult to read. these processes include minifying your code, as well as the use of module bundlers or similar tools, such as webpack. in this case, when you upload your extension to amo, you will need to provide your source code and instructions for building that source code, where build processes render your extension’s code hard to read. 684 themes add-ons, look & feel, themes themes allow you to change the look an...
Adding phishing protection data providers
e phishing protection service. browser.safebrowsing.provider.idnum.reporterrorurl an url to which the user is directed in order to report a safe page that is incorrectly being reported as a phishing site. browser.safebrowsing.provider.idnum.reportphishurl an url to which the user is directed in order to report a phishing site that isn't detected by the phishing protection system. determining the currently-selected data provider if you need to determine the id number of the currently selected anti-phishing data provider, you can look at the current value of the preference browser.safebrowsing.dataprovider. ...
Bugzilla
documentation about b.m.o. what to do and what not to do in bugzilla tips for how to use bugzilla, as well as things you should avoid. bugzilla etiquette a guide to etiquette; this guide will help you understand how best to conduct yourself on b.m.o. and how using proper manners and civility will help ensure your problem gets solved sooner rather than later. ...
Building Mozilla
in this article, we list documents that will guide you in building firefox or other projects based upon mozilla code. 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 ...
Chrome registration
ormat is no longer supported at all starting with gecko 1.9.2; add-ons already installed using this format will continue to work but can no longer be installed. be sure to remove your add-on and reinstall it to ensure that it installs correctly after updating it to use a plaintext manifest. official references for toolkit api official references. do not add to this list without contacting benjamin smedberg. note that this page is included from the pages listed below. so: don't add breadcrumbs! structure of an installable bundle: describes the common structure of installable bundles, including extensions, themes, and xulrunner applications extension packaging: specific information about how to package extensions theme packaging: specific information about how to package themes multiple...
Debugging JavaScript
to about:config and set the following two prefs: devtools.chrome.enabled: true devtools.debugger.remote-enabled: true after you restart the browser, you can access the browser debugger through tools > web developer > browser toolbox. (note that before firefox 28, this was labeled "browser debugger" and only the debugger was available, not the whole toolbox.) note that you must accept the incoming connection : (you may disable the pop-up above with the devtools.debugger.prompt-connection set to false in about:config. this can be a security risk, especially if you also set the devtools.debugger.force-local preference to false.) then, the browser toolbox displays the available tools for debugging. (note that before firefox 28, only the script debugger was available.) the use of these to...
Debugging update problems
that url might look something like: https://aus3.mozilla.org/update/3/firefox/12.0a1/20120106040225/darwin_x86_64-gcc3-u-i386-x86_64-shark/nightly-profiling/darwin%2010.8.0/default/default/update.xml?force=1 you can then request this url manually to see what's inside. ...
Debugging on Windows
e, to print curent javascript stack to stdout, evaluate this in quickwatch window: {,,xul}dumpjsstack() note: visual c++ will show you something in the quick watch window, but not the stack, you have to look in the os console for the output. also this magical command only works when the vc++ stack is in certain states. it works when you have js_interpret() in the newest stackframe debugging minidumps see debugging a minidump. debugging tinderbox builds see running windows debug builds problems loading debug symbols if both your application and visual c++ hang shortly after launching the application under the debugger, you may be hitting a known deadlock in the way visual studio downloads debug symbols for the system libraries; see https://connect.microsoft.com/visualstudio/feedback...
Debugging
d answers) about debugging mozilla on os x. debugging mozilla with gdb gdb is our primary debugger on mac and linux. debugging mozilla with lldb lldb is the new debugger on mac. advanced debugging techniques understanding crash reports how to read crash reports, which are full of information yet often not easy to interpret and act on. debugging a minidump windows crash reports include a minidump, which contains a lot of information about the application when it crashed. debugging mozilla with valgrind valgrind is a memory debugger for mac and linux. it is slow, but good for tracking down difficult memory safety bugs. replay debugging firefox with vmware workstation how to setup record and replay debugging on firefox, ...
Gmake vs. Pymake
y to switch from gmake to pymake or pymake to gmake the build will fail unless you did a relative configure. a relative configure produces paths that look like "../../foo" which can be understood by gmake and pymake. to configure relatively, invoke configure or client.mk from your objdir. 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. note that typing "python build/pymake/make.py -f client.mk" does not trigger a relative configure. the working directory must be your objdir when you invoke configure to get paths that will work in gmake and pymake. you should also make sure that the object directory path specified in your mozconfig matches the director...
Installing headers using EXPORTS
hould set exports to the list of headers to be exported. they will be copied to <tt>dist/include/$(module)</tt>. for xpidl-generated headers, you should set xpidlsrcs to the list of idl files to export. these idl files will be copied to <tt>dist/idl</tt>, and the generated headers will be copied to <tt>dist/include/$(module)</tt>. for xpidl-generated headers, you may also set xpidl_module to determine which typelib file is produced from the idl files. the distinction between xpidl_module and module is that each directory with idl files must have a unique typelib file, but several directories may export headers to the same location. here is an example <tt>makefile.in</tt> which has both c++ and idl headers: module = content xpidl_module = content_base exports = \ nsicontent.h \ nsido...
Simple SeaMonkey build
you can build a bleeding-edge, development version of seamonkey using the commands below. for complete information, see the build documentation. build prerequisites hardware requirements: the seamonkey build process is both i/o- and cpu-intensive, and can take a long time to build even on modern hardware. minimum and recommended hardware requirements for mozilla development are: recommended: 8gb of ram (having only 4gb ram and 4gb swap may give memory errors during compile) 35 gb free disk space. this will accomodate visual studio 2013 community edition, the required sdks, the mozillabuild package, the mercurial source repository and enough free disk space to compile. a fast ssd is recommended; the firefox build process is i/o-intensive. high speed internet installing build ...
pymake
ad type python /path/to/srcdir/build/pymake/make.py. for example: instead of make -f client.mk to start a build, you would type python build/pymake/make.py -f client.mk. to run tests instead of typing make mochitest-plain in the object directory, you would type python ../build/pymake/make.py mochitest-plain. alternately, if you would like to simply type in pymake -f client.mk from within the mingw32 shell. while in the shell type cd ~ (without quotes). 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. try typi...
Gecko Logging
it is enabled for all builds, thread-safe, and the preferred alternative to nspr logging. some other mostly-useless information on logging can be found on the nspr logging page. logging framework declaring a log module lazylogmodule defers the creation the backing logmodule in a thread-safe manner and is the preferred method to declare a log module. multiple lazylogmodules with the same name can be declared, all will share the same backing logmodule. this makes it much simpler to share a log module across multiple translation units. lazyloglodule provides a conversion operator to logmodule* and is suitable for passing into the logging macros detailed below. ...
Interface Compatibility
the rules which govern interface changes are different depending on the consumers and the languages involved. web content apis which are visible to web content are not modified, except as a last resort when inherent security vulnerabilities or incompatibility with other browsers make it the only option. any changes, including new features, must have super-review. one exception to this rule is apis which are explicitly shipped with mozilla prefixes as a technology preview. ...
Reviewer Checklist
erify the fix, you should provide steps to reproduce (str). quality if you can unit-test it, you should unit-test it. if it's js, try to design and build so that xpcshell can exercise most functionality. it's quicker. make sure the patch doesn't create any unused code (e.g., remove strings when removing a feature) all caught exceptions should be logged at the appropriate level, bearing in mind personally identifiable information, but also considering the expense of computing and recording log output. [fennec: checking for log levels is expensive unless you're using logger.] style follow the style guide for the language and module in question. follow local style for the surrounding code, even if that local style isn't formally documented. new files have license declarations and ...
Frame script loading and lifetime
ly no way to unload them when loaded, other than closing the tab they were loaded into. to listen for an event, when your frame script is unloaded (due to tab close for instance), you must set the third argument of addmessagelistener to true. for example, from bootstrap.js: services.mm.addmessagelistener( 'my-addon-id', { receivemessage: function() { console.log('incoming message from frame script:', amsg.data); } }, true // must set this argument to true, otherwise sending message from framescript will not work during and after the unload event on the contentmessagemanager triggers ); then in your frame script, listen for the unload event of the message manager (which is the global this), and sending a message. if you did not set the third argum...
Performance
the more expensive they are to execute the longer it will take for the browser to become responsive after startup. frame scripts also get executed on non-restored tabs. all their overhead is thus not just incurred by active tabs but by the total number of tabs in a session. ...
Blocked: Storage access requests from trackers
message firefox: cookieblockedtracker=request to access cookies or storage on “x” was blocked because it came from a tracker and content blocking is enabled. what went wrong? a request to access cookies or storage was blocked because the browser identified it as coming from a tracker and content blocking is enabled. the permission can be changed or removed by: going to preferences > content blocking and either adding an exception with the manage exceptions… button choosing the custom content blocking and unchecking the tracker checkbox if the blocked resource doesn't need authentication, you can fix the warning message by adding a crossorigin="anonymous" attribute to the relevant element. ...
Security best practices for Firefox front-end engineers
sures that developers will identify and avoid the problems early on in the development cycle and before shipping the code. linter rules against unsanitized dom interaction the security assurance team maintains an eslint rule that disallows unsafe uses of innerhtml and similar dom apis. the linter makes an exception for code that uses string literals that are hard coded in the source code, assuming benevolent developers. 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. appendix list of disallowed dom apis innerhtml outerhtml insertadjacenthtml()...
Firefox
ns that a user has made or installed into their copy of firefox. you can find details about profiles on mozilla's end-user support site.performance best practices for firefox front-end engineersthis guide will help firefox developers working on front-end code produce code which is as performant as possible—not just on its own, but in terms of its impact on other parts of firefox. ...
HTMLIFrameElement.addNextPaintListener()
this event provides information about what has been repainted. it is mainly used to investigate performance optimization. note: the handler will receive the event once and then be thrown away. syntax instanceofhtmliframeelement.addnextpaintlistener(listener); returns void. parameters listener a function handler to listen for a mozafterpaint event. ...
Browser API
he browser <iframe>. htmliframeelement.sendtouchevent() sends a touchevent to the <iframe>'s content. note that this method is available for touch enabled devices only. htmliframeelement.removenextpaintlistener() removes a handler previously set with addnextpaintlistener(). htmliframeelement.zoom() changes the zoom factor of the browser <iframe>'s content. this is particularly useful for zooming in/out on non-touch-enabled devices. events in order to allow an application to manage the browser <iframe>, the application can listen for new events about what's happening within the browser <iframe>. the following new events can be listened for: mozbrowseractivitydone sent when something inside the browser <iframe> triggers a web activity, and that web activity's message is consumed by...
Chrome-only Events reference
this page lists events that are only available in gecko chrome code (and sometimes in other privileged circumstances, eg. ua widgets). mozbeforepaintgecko 2.0 adds a new method for performing javascript controlled animations that synchronize not only with one another, but also with css transitions and smil animations being performed within the same window.mozscrolledareachangedthe mozscrolledareachanged event is fired when the document view has been scrolled or resized. smartcard-insertthe smartcard-insert event is fired when the insertion of a smart card has been detectedsmartcard-removethe smartcard-remove event is fired when the removal of a smart card has been detected. ...
Roll your own browser: An embedding how-to
l area. activex control: an activex control for mozilla using the gecko layout engine. more information at 1 and 2. mac external projects activestate's komodo: development environment, based on mozilla's xul. (screenshot) marbrow : mac port of x2web (ja, ko) embedding mozilla. mozilla examples ppembed: standard mozilla sample application implemented with metroworks' powerplant. camino: a project aimed at delivering a best-of-breed browser on the mac os x platform. camino uses cocoazilla, a variant of fizzilla that consists of a unix back end wed to a cocoa front end. java examples java webclient: provides a browser-neutral java api that enables generic web browsing capability. browserg!: a java application that uses webclient for html rendering and surfing capabilities...
Gecko Keypress Event
eyboard layout inputs a zwnj, though shift+'2' inputs '@', and so, if gecko were to replace the charcode in this case, users would not be able to input zwnj (bug 414130). otherwise, gecko can replace the charcode with an ascii character. however, gecko replaces the charcode only when the key pressed corresponds to a latin letter (vk_a to vk_z), numeral (vk_0 to vk_9), plus sign (vk_oem_plus), or minus sign key (vk_oem_minus). note that replacing the original (non-ascii) characters on these keys means that there are some accessibility issues for non-latin keyboard layout users as many non-ascii characters will not be available for shortcuts. therefore, web application developers should use only letters, ascii numerals, plus sign, and minus sign for custom shortcut keys. linux the charcode ...
Getting Started with Chat
directly, try to use name: message format. for example, "ashughes: good morning!" every channel has its own topic. try to keep your messages within that subject matter. for example, do not talk about thunderbird issues in #firefox. mozilla's channels are most active between 9am and 7pm pst monday to friday, excluding us holidays. when asking a question, be patient. sometimes, it can take a few minutes for people to respond. posting a message like "help!" is not particularly helpful. asking a good question will result in a better experience for both you and the person trying to help. relax and have fun! software there are several different applications which allow you to connect to irc networks. you will need to use the following information to configure the server connection: serve...
Hacking with Bonsai
bonsai was created to solve these problems. ...
How to investigate Disconnect failures
n over the bridge or when firefox crashes. usually disconnects happens when a modal dialog freezes and we cannot close it sp we close firefox with the modal frozen. we cannot investigate failures via mozmill, because we do not catch the crashes, so the crashes' information is not logged; we have to go to ci machines and investigate directly. check if firefox crashed: windows: [user]/appdata\roaming\mozilla\firefox\crash reports ubuntu: [user/home]/.mozilla/firefox/crash reports and there we can check by timestamp if firefox crashed when we had the disconnect. check the event viewer to check if an os event interfered with the test run. the event viewer can be found on windows: computer management > event viewer > windows logs > application and here we look for errors tha...
IPDL Best Practices
ol and deallocpprotocol are asymmetric, if ipdl ends up shutting down the protocol tree due to an error, the auto pointer will attempt to trigger protocol deletion a second time. while this can be worked around with actordestroy, being explicit about deleting the protocol with send__delete__ is easier to maintain, with symmetric alloc/deallocpprotocol functions also being easier to reason about. minimize overall use of messages reducing ipc traffic is a righteous goal. consider the following protocol: async protocol pasyncquerier { child: pasyncquery(); } async protocol pasyncquery { child: kickoffquery(nsstring query); parent: returnresult(nsstring result); __delete__(); } in this situation, there is a guaranteed sequence of messages that will be sent. following actor construct...
Internationalized Domain Names (IDN) Support in Mozilla Browsers
ion bar or a request to process non-ascii host name links, it first turns them into unicode, then normalizes the input string to make it conform to general uri requirement. the process will convert uppercase characters to lowercase ones (case folding), unify characters with multiple representation, e.g. conversion of half-width kana characters in japanese into full-width ones (normalization), eliminate prohibited characters (e.g. space), eliminate ambiguities in bi-directional text (e.g. arabic and hebrew), and check whether or not unassigned characters in the unicode repertoire are used -- allowing them for "query strings" but disallowing them for "stored strings" such as the data input for domain name registration. this process is called "nameprep" and is performed according to rfc 3491 (...
JavaScript-DOM Prototypes in Mozilla
t through the object's class info. one of these interfaces is nsidomhtmlimageelement, others are nsidomnshtmlimageelement (netscape extensions to the standard interface), nsidomeventtarget, nsidomeventlistener, nsidom3node, and so on. the prototype object that xpconnect creates for the classes that have class info are shared within a scope (window). because of this, the following holds true (assuming img1 and img2 are two different image objects in the same document): img1.__proto__ === img2.__proto__ if img1 would come from one document and img2 from another document, then the above would not be true. both prototypes would look identical, but they would be two different jsobject's. this sharing of prototypes lets users do cool things like modify how all instances of a given class works ...
JavaScript Tips
document.getelementsbytagname(atag).item(0) != null to document.getelementsbytagname(atag).length > 0. prefer to use localname rather than tagname. xul elements have many of the attributes mapped to properties. this was done for a reason, so use them! the properties are: align allowevents contextmenu datasources dir flex height id left maxheight maxwidth minheight minwidth observes orient pack persist ref statustext top tooltip tooltiptext width xul also maps the ordinal attribute but this defaults to "1" if it is not present. xul also maps the class attribute, but unfortunately class is a reserved identifier, so the property is named classname. (the property could have been implemented as ["class"'] but that j...
AddonInstall
-on being installed. state integer the state of the installation. error integer if an error has been encountered during the download or install this will hold the error code. sourceuri nsiuri the uri that the add-on is being installed from. file nsifile the file that the add-on is being installed from. this may be null if the add-on is coming from the internet and has yet to be downloaded. progress integer the progress of any necessary downloads. maxprogress integer the expected size of any necessary downloads or -1 if unknown. certificate nsix509cert if the add-on to be installed is signed this is the certificate of the signer. only available after downloading is complete. certna...
AddonType
d-on types hold useful information about each type of add-on that may be installed. they are mostly used to help the ui know how to display the different types of add-on. properties attribute type description id string the unique id for the type. name string the localized name for the type. uipriority integer a number used to determine the order of types displayed in the user interface. the lower the number the higher in the list the type will appear. built-in values: value category 2000 locale 4000 extension 5000 theme 6000 plugin viewt...
Code Samples
simply replace yourextensionid with your add-on's id. ...
UpdateInfo
the update. updateurl string the updateurl that the update can be downloaded from. updatehash string a hash for the update's file. updateinfourl string a url containing simple release notes for the update. targetapplications object[] information about what applications the update is compatible with. each item in the array contains "id", "minversion", and "maxversion" properties. ...
Dict.jsm
cified key. object get( string akey, [optional] object adefault ); parameters akey the key whose value should be returned. adefault optional the value to return if the specified key isn't found. if you don't specify a default value, undefined is returned for keys that aren't found. return value the value of the specified key, or undefined if no matching key was found. has() determines whether or not the specified key exists in the dictionary. boolean has( string akey ); parameters akey the key for which to determine existence in the dictionary. return value true if the specified key is in the dictionary, otherwise false. listitems() returns an array of the key/value pairs in the dictionary. note: the order in which items are returned is arbitrary. array listi...
DownloadLastDir.jsm
: 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. to set the path, use setfile: // file is an nsifile downloadlastdir.setfile(uri, file); to retrieve the path in firefox 26 or later, use getfileasync: downloadlastdir.getfileasync...
DownloadSource
a downloadsource object represents the source of a download, for example a document or an uri. properties attribute type description url read only string the uri for the download source. isprivate read only boolean indicates whether the download originated from a private window. this determines the context of the network request that is made to retrieve the resource. referrer read only string referrer uri of the download source, or null if no referrer should be sent or the download source is not http. ...
Geometry.jsm
it exports two classes: point and rect. to use these routines, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/geometry.jsm"); once you've imported the module, you can then use the point and rect classes. ...
Interfacing with the Add-on Repository
and, if the preference doesn't exist or has no value, sets the value of the preference to the correct one for the amo site. starting a request to start a search of the repository, you can use either of the following methods: searchaddons() queries the add-on repository for add-ons matching given search criteria. retrieverecommendedaddons() retrieves a list of recommended add-ons, as determined by the amo site administrators. this example will use the latter, in order to randomly select a recommended add-on and offer to install it. however, the code to perform a search term based query would be very similar. 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...
JavaScript OS.Constants
rwise. os.constants.path paths of well-known files and directories. libxul the path to the file containing libxul. useful, for instance, to access the platform code from javascript in conjunction with js-ctypes. profiledir the path to the current profile. homedir the path to the user's home directory. winappdatadir the path to the user's roaming application data directory. winlocalappdatadir the path to the user's local application data directory. winstartmenuprogsdir the path to the programs subdirectory in the user's start menu. macuserlibdir the path to the user's library directory. maclocalapplicationsdir the path to the local applications directory. os.constants.libc constants...
OS.File.Error
methods os.file.error.closed() return an error representing the fact that a file is closed. os.file.error.exists() return an error representing the fact that a file exists. instances of os.file.error in case of any i/o error, the functions of os.file raise instances of os.file.error. these exceptions hold both a human-readable error message detailing the i/o error and attributes to help determining the cause of the error. cross-platform attributes operation the human-readable name of the failed operation. becauseexists true if the operation failed because a file or directory exists, false otherwise. becausenosuchfile true if the operation failed because a file or directory does not exist, false otherwise. becauseclosed true if the operation...
OSFile.jsm
, etc. operations can take an arbitrary amount of time. we are talking about several seconds to execute operations that look trivial, such as closing a file, or checking when it was last modified. if the operation is called on the main thread, this means that the whole user experience is stuck for several seconds, which is quite bad. why is i/o efficiency important? i/o efficiency is all about minimizing the number of actual i/o calls. this is critical because some platforms have extremely slow storage (e.g. smartphones, tablets) and because, regardless of the platforms, doing too much i/o penalizes not just your application but potentially all the applications running on the system, which is quite bad for the user experience. finally, i/o is often expensive in terms of energy, so wasting ...
SourceMap.jsm
s original associated source's line/column location. fn: the traversal function. sourcenode.prototype.join(sep) like array.prototype.join except for sourcenodes. inserts the separator between each of this source node's children. sep: the separator. sourcenode.prototype.replaceright(pattern, replacement) call string.prototype.replace on the very rightmost source snippet. useful for trimming whitespace from the end of a source node, etc. pattern: the pattern to replace. replacement: the thing to replace the pattern with. sourcenode.prototype.tostring() return the string representation of this source node. walks over the tree and concatenates all the various snippets together to one string. sourcenode.prototype.tostringwithsourcemap(startofsourcemap) returns the st...
Task.jsm
m javascript code module implements a subset of task.js to make sequential, asynchronous operations simple, using the power of javascript's yield operator. to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/task.jsm"); introduction for an introduction to tasks, you may start from the task.js documentation, keeping in mind that only the core subset is implemented in this module. tasks are built upon generator functions and promises. the task.spawn() function takes a generator function and starts running it as a task. every time the task yields a promise, it waits until the promise is resolved. task.spawn() returns a promise that is resolved when the task completes successfully, or is rejected if an exception occu...
Using JavaScript code modules
this means you can't use components.utils.import() with your own resource url at the top level in a component source. a possible solution is moving the call to components.utils.import() into the xpcom compone...
Application Translation with Mercurial
es can help figuring out the translation style and translate according to them: check your localization team's page by clicking on the team with your language code (e.g. "de" for german) for a style guide (e.g. style guide for german). transvision offers searching for texts and text ids ("entities" or "keys"), allowing to quickly find translations for already translated texts. microsoft's terminology search allows fast lookups of localized technical terms. choosing what to translate go to the localization status page and click on the '<number> missing' label of the firefox branch on which you want to translate, e.g. fx_aurora. the page which opens has a bar holding information about how many texts (strings) have already been translated, how many there are in english and your locale an...
Localizing with Pontoon
also available in the out-of-context translation panel. we call all of these translation helpers and here's how each of them will help you as you translate strings: history displays previously suggested translations, including from other users. machinery displays matches from various services: internal translation memory, mozilla transvision, open source translation memory, microsoft terminology and machine translation. other locales displays matching translations from other locales. search almost like machinery, but takes provided keyword as input parameter instead of the original string. by clicking a suggestion, it gets copied into translation area. publishing your localization suppose you now want to publish your l10n work by committing it to a repo. pontoon lets you d...
Localizing without a specialized tool
ectory with your localization files) please either follow this structure closely or adjust all commands in the documentation as needed by your custom set-up. get the source change your current directory to your working directory with the following command: $ cd /path/to/your/working/directory first, you will need to check out the sources of mozilla-1.9.2 together with the en-us strings. assuming that you have installed mercurial, issue the following command: $ hg clone http://hg.mozilla.org/releases/mozilla-1.9.2 this will pull the mozilla 1.9.2 sources from the remote repository and create a mercurial clone in mozilla-1.9.2 inside your working directory. next, again in your working dir, create a directory that will serve as localization base: $ mkdir l10n-mozilla-1.9.2 $ cd l10n-mozil...
Localization prerequisites
conf 2.5x will not work. zip 2.3 (or higher) mercurial 1.2 or higher recommended. needed for development of firefox 3.5/seamonkey 2.0/thunderbird 3.0 and later. a text editor. you can try one of these: notepad++ or notepad2 on windows, vim, gedit or kate on gnu/linux, bbedit on mac os x. to verify that they work, open a shell. linux users should know, on the mac, you find terminal in applications/utilities. on windows, mozillabuild offers a start-shell-l10n.bat in c:\mozilla-build. let’s try our entry points: $ hg --version mercurial distributed scm (version 1.3.1) copyright (c) 2005-2009 matt mackall <mpm@selenic.com> and others this is free software; see the source for copying conditions. there is no warranty; not even for merchantability or fitness for a particul...
Localization sign-off reviews
e this review process to perform quality assurance (qa) testing on your l10n efforts. this ensures that every user who downloads your localized mozilla application receives all of your hard work in a functional product. each qa review helps us in these ways: ensures that your l10n work is visible and functional within the mozilla application. allows us to understand how each l10n team is performing their localization work. allows us to discover potential bugs within l10n tools. overview you've done some localization work and are ready for it to be released. the merge date for migrating from one product release channel to the next is rapidly approaching. you need to make sure that your work can effectively be compiled into a build for the next release channel. here is a detailed overview ...
Localization formats
lization project no tools to validate syntax, so a localizer may cause accidental errors that can cause breakage (level of breakage depends on level of error) cannot use po editor, which most localizers know and love gettext (.po) gettext is a widely-used localization format that uses .po files. with this arrangement, content for localization is presented in the following manner: msgid "coming soon" msgstr "bientôt disponible" where the value in the "" of the msgid is the english content, and the value in the "" of the msgstr is the translation. msgstr can be longer translations than just the exact above. for example, below is the entire introduction used for a certificate that was presented to those who downloaded firefox during the download day campaign. the french content runs ...
Writing localizable code
la and extension developers. for technical details please also look at xul_tutorial:localization. about localizers a few notes about localizers for developers who rarely deal with them: localizers like tools, and they don't like editors, localization tools are often based on key-value pairs, at least some localizers have their talents focused on language skills and are not savvy in programming, or even building applications. guidelines thus, there are a few guidelines you should follow to make localization of your code easier: choose good key names the names chosen for your keys (regardless of whether that's a dtd or a properties file) should be descriptive. think of them as long variable names. if you change the semantics of a localized string, change the key. this will more li...
Fonts for Mozilla 2.0's MathML engine
you may also want to check out the mozilla mathml torture test to test your installation against concrete examples. on windows: use this mathml fonts installer. ...
Mozilla MathML Status
element [- attribute] notes mtable implemented. mtable - alignmentscope not implemented. see bug 122253. mtable - columnspacing, rowspacing, framespacing implemented. see bug 330964. mtable - columnwidth not implemented. see bug 958953. mtable - equalrows, equalcolumns not implemented. see bug 958954. mtable - side, minlabelspacing not implemented. see bug 356870. mtr implemented. mlabeledtr not implemented. see bug 689641. mtd implemented. * - groupalign. not implemented. see bug 122253. maligngroup not implemented. see bug 122253. malignmark not implemented. see bug 122253. elementary math element [- attribute] notes ...
Updates
mathml too? may 23, 1999 reader opinion: mathml's viability - talkback may 14, 1999 mozilla mathml project underway may 1999 mozilla mathml project initiation ...
MathML Demo: <mfrac> - fractions
inline, auto, thick line x 2 + 1 x , the superscripted 2 should be script-script size. inline, display style, thick line x - 1 0.98 × 10 2 + y , the superscripted 2 should be script size. inline, text style, thick line x 2 + 1 x x 2 + 1 x the end. inline, auto, no line x 2 + 1 x the end. ...
MathML Demo: <mo> - operator, fence, separator, or accent
neral, the lspace and rspace around arrows should be similar to the spacing around relations. there is an issue with the markup of "long" latex arrows in mathml. there are entities from these arrows, &xlarr; &xlarr; &xrarr; etc. but they have no standard unicodes. they can be viewed as stretched versions of short arrows. \longleftarrow can be scripted as <mo>&xlarr;</mo> or as <mo stretchy="true" minsize="1.8">&larr;</mo>. a ↑ b ← c a ⇑ b ⇐ c a ↓ b → c a ⇓ b ⇒ c a ↕ b ↔ c a ⇕ b ⇔ c a ↗ b ↦ c a ↘ b ↩ c a ↙ b ↼ c a ↖ b ↽ c a ↻ b ⟵ c a ↺ b ⟸ c a ⇈ b ⟶ c ...
Mozilla projects on GitHub
zilla-metrics tools used to collect metrics about mozilla code. mozilla-services mozilla cloud services projects. opennews the knight-mozilla open news project, helping the journalism/technology community do great work through shared knowledge and code. pluotsorbet a j2me-compatible virtual machine written in javascript. rust-lang the rust programming language, designed for safe concurrent code. servo the next-generation rendering engine. ...
Mozilla Style System
in the form of style rules. nsistylerule an nsistylerule is animmutable set of css property-value pairs. for css style sheets, they correspond to css's concept of rules. however, they also exist for the other types of rule processors. when script dynamically changes the data represented by a css style rule, we create a new nsistylerule object; keeping the old one around briefly helps to determine what changed and how we need to handle that change. computed style (front end) the interface that the front end exposes to the rest of mozilla consists of a single nsstyleset object and many nsstylecontext objects, each of which holds the computed style for an element, pseudo-element, or text node. the style set provides the api managing the rule processors and for creating style contexts. t...
mozilla::MutexAutoLock
ke using mozilla::mutex safer and easier. to use mozilla::mutexautolock, declare and initialize it with a reference to an mozilla::mutex. the mozilla::mutexautolock constructor will lock() the underlying mozilla::mutex automatically. when the mozilla::mutexautolock goes out of scope, its destructor will unlock() the underlying mozilla::mutex. because of mozilla::mutexautounlock, the rule for determining if your code owns the mutex underlying the mutexautolock is slightly more complicated than that for monitorautoenter. this is because mutexautounlocks can be nested within mutexautolocks and vice versa, indefinitely deeply. important: when a mozilla::mutexautolock is the mutex raii wrapper most recently pushed on the stack, your code is guaranteed to own the underlying mozilla::mutex. construc...
mozilla::MutexAutoUnlock
ozilla::mutex safer and easier. to use mozilla::mutexautounlock, declare and initialize it with a reference to a locked mozilla::mutex. the mozilla::mutexautounlock constructor will unlock() the underlying mozilla::mutex automatically. when the mozilla::mutexautounlock goes out of scope, its destructor will lock() the underlying mozilla::mutex. because of mozilla::mutexautolock, the rule for determining if your code does not own the mutex underlying the mutexautounlock is slightly more complicated than that for monitorautoenter. this is because mutexautounlocks can be nested within mutexautolocks and vice versa, indefinitely deeply. important: when a mozilla::mutexautounlock is the mutex raii wrapper most recently pushed on the stack, your code is guaranteed not to own the underlying mozilla:...
BloatView
24 0.00% nsframe 47568 -26.15% 48096 -50.49% cssdeclarationimpl 42984 0.67% 43488 0.67% this "delta report" shows the leak offenders, sorted from most leaks to fewest. the delta numbers show the percentage change between runs for the amount of leaks and amount of bloat (negative numbers are better!). the bloat number is a metric determined by multiplying the total number of objects allocated of a given class by the class size. note that although this isn't necessarily the amount of memory consumed at any given time, it does give an indication of how much memory we're consuming. the more memory in general, the worse the performance and footprint. the percentage 99999.99% will show up indicating an "infinite" amount of leakage. thi...
GPU performance
works reasonably well with firefox. see also debugging with pix. nvidia perfhud - last i checked required a special build to be used. nvidia parallel nsight - haven't tried. amd gpu shaderanalyzer - will compile a shader and show the machine code and give static pipeline estimations. not that useful for firefox because all of our shaders are pretty simple. amd gpu perfstudio - i had trouble getting this to work, and can't remember whether i actually did or not. ...
Investigating CSS Performance
if we get a erestyle_subtree we will restyle more elements. this was developed while investigating bug 1110625 ...
JS::PerfMeasurement
t will not have any more bits set than were set in the mask passed to the constructor, but if the os cannot or will not measure all of the requested events, then only those events that will actually be measured have their bits set. all the counter variables for events that are not being measured will have the fixed value (uint64)-1. void start() call this on a perfmeasurement instance to start timing. void stop() and call this to stop timing again. the counter variables do not update in real time; they only change when stop is called. counter values are accumulated across many start/stop cycles, and you can modify their values if you want; stop simply adds counts read back from the os to whatever is already in each counter. void reset() resets all enabled counters to zero. uint64 cpu_cycle...
Leak-hunting strategies and tips
by native code. the nsxpcwrappedjs object creates a gc root that exists as long as the wrapper does. the wrapper itself is just a normal reference-counted object, so a leaked nsxpcwrappedjs can be debugged using the normal refcount-balancer tools. if you really need to debug leaks that involve js objects closely, you can get detailed printouts of the paths js uses to mark objects when it is determining the set of live objects by using the functions added in bug 378261 and bug 378255. (more documentation of this replacement for gc_mark_debug, the old way of doing it, would be useful. it may just involve setting the xpc_shutdown_heap_dump environment variable to a file name, but i haven't tested that.) post-processing of stack traces on mac and linux, the stack traces generated by our intern...
Memory reporting
e called sizeoffoo. try to make the names descriptive enough that it's clear what's being measured. sometimes you might want to split the measurements of an object into two or more numbers, e.g. because you want to show them separately in about:memory. in this case it's often clearer to increment the numbers rather than assigning to them, especially if you're measuring multiple entities and summing their measurements. for example: void foobar::addsizeofexcludingthis(nsmallocsizeoffun amallocsizeof, size_t *afoosizeout, size_t* abarsizeout) const { *afoosizeout += ...; *abarsizeout += ...; } alternatively, you could create a struct: struct foobarsizes { size_t mfoo; size_t mbar; foobarsizes() { mozilla::podzero(this); } } void foobar...
Profiling with the Gecko Profiler and Local Symbols on Windows
y reads symbols from the pdb files that are generated during the build process. you probably need a 64 bit build of firefox for this to work, though. it looks like we consume too much memory when creating the symbol table for this to work in 32 bit firefox builds. unfortunately, 32 bit is still the default when building firefox locally. you need to add the lines ac_add_options --target=x86_64-pc-mingw32 and ac_add_options --host=x86_64-pc-mingw32 to your mozconfig in order to build a 64 bit build of firefox. profiling local talos runs if you would like to use the gecko profiler with a local talos run of a local build of firefox for windows, you will need to point talos to a zipfile containing breakpad-style symbols for your build. follow the steps below: note: you only need to do this if ...
Refcount tracing and balancing
will run and how large the logs it produces will be. xpcom_mem_comptr_log this environment variable enables logging of additions and releases of objects into nscomptrs. this requires c++ dynamic casts, so it is not supported on all platforms. 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. this results in slower code, but at least yo...
TimerFirings logging
in.js:20:330 135 -495057024[7f74e105ba00]: [7108] fn timer (one_shot 4 ms): [content] https://self-repair.mozilla.org/repair/:7:13669 118 801266240[7f7c1f248000]: [7163] fn timer (one_shot 100 ms): [content] http://a.visualrevenue.com/vrs.js:6:9423 103 801266240[7f7c1f248000]: [7163] fn timer (one_shot 50 ms): [content] http://static.dynamicyield.com/scripts/12086/dy-min.js?v=12086:3:3389 94 801266240[7f7c1f248000]: [7163] fn timer (one_shot 50 ms): [content] https://ad.doubleclick.net/ddm/adi/n7921.1283839cadreon.com.au/b9038144.122190976;sz=300x600;click=http://pixel.mathtag.com/click/img?mt_aid=2744535504761193354&mt_id=1895890&mt_adid=148611&mt_sid=973379&mt_exid=9&mt_inapp=0&mt_uuid=353d5460-19f6-4400-9bbd-d0fcc3bcf595&mt_3pck=http%3a//beacon-apac...
Phishing: a short definition
logging in, and only enter their credentials when they recognize the user defined pictures or words. a study on the efficacy of security indicators, presented at the 2007 ieee symposium on security and privacy, suggests that the above countermeasures fail to protect the majority of users. this too, includes missing https or ev certificate indicators in a browser’s navigation bar. services assuming responsibility technical solutions can be more efficient if implemented to protect millions of users automatically. as most phishing attacks start with unsolicited email messages, a clear starting point is improving spam filters, thus reducing the number of fraudulent messages reaching users. web browser vendors too, are interested in protecting their users from phishing. after all, the browse...
Productization guide
e, putting one sample news feed on the bookmarks toolbar in new profiles in firefox helps in learning about the live bookmarks. including a couple of search engines instead of one in the search toolbar can help users understand that they can add as many plug-ins as they wish. this guide will walk you through the steps to successfully productizing your localization. the first page will cover performing research and preparing to submit productization recommendations. the following (and last) page will cover the technical steps to creating and submitting productization patches. next » ...
Profile Manager
the version of firefox which will be launched is indicated in the "firefox version" dropdown in the launch options box: there are several additional launch options available for firefox. these cause firefox to be launched with various command-line arguments. see command line options for a description of these. launch option command line argument run firefox i...
JSHydra
it is inspired by the dehydra and treehydra tools, which can perform similar tasks in c++ code. in its back-end, it uses the parse tree created by the spidermonkey engine. all analysis is performed by running javascripts. documentation installing jshydra download, installation and dependency info for jshydra community view jshydra forums... ...
L20n Javascript API
tiated asynchronously by the negotiator registered by registerlocalenegotiator. ctx.requestlocales('pl'); ctx.requestlocales('fr-ca', 'fr'); if requestedlocales argument list is empty or undefined, the default locale from registerlocales will be used. ctx.requestlocales('pl'); if registerlocales hasn't been called, the special i-default locale is used, which means that the following minimal code is valid and will result in a fully operational context instance. var ctx = l20n.getcontext(); ctx.addresource('<hello "hello, world!">'); ctx.requestlocales(); requestlocales can be called multiple times after the context instance emitted the ready event, in order to change the current language fallback chain, for instance if requested by the user. ctx.supportedlocales a read-onl...
L20n
ion and application logic. it allows to adapt your web application not only to languages and cultures, but also contextual data, user gender and screen dimensions. what l20n looks like here is a simple, straightforward example showing an english string being provided: <brandname "firefox"> <about "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. internationalization for your web app first read for developers looking to use the l2...
Leak And Bloat Tests
startup.enabledmailcheckonce", true); user_pref("mailnews.start_page_override.mstone", "1.9pre"); user_pref("mail.shell.checkdefaultclient", false); // ensure os x and outlook/oe books are disabled user_pref("ldap_2.servers.osx.position", 0); user_pref("ldap_2.servers.oe.position", 0); preferences in generated profile, but not set: user_pref("mail.root.none", "/home/moztest/.thunderbird/t7i1txfw.minimum/mail"); user_pref("mail.root.pop3", "/home/moztest/.thunderbird/t7i1txfw.minimum/mail"); user_pref("mail.server.server1.directory", "/home/moztest/.thunderbird/t7i1txfw.minimum/mail/local folders"); user_pref("mail.server.server2.directory", "/home/moztest/.thunderbird/t7i1txfw.minimum/mail/tinderbox"); user_pref("mail.attachment.store.version", 1); user_pref("mail.folder.views.version", 1); ...
MailNews automated testing
to other folders, trash them, etc. enhanced logging: supports generating rich json streams to disk or over the network for consumption by logsploder or other tools. performance testing mail leak and bloat tests these tests start up thunderbird or seamonkey and record any leaks found, as well as the total memory requirement. although currently based on simple tests, these are useful for determining if new leaks have been introduced. for more information, see leak and bloat tests. ...
McCoy
order to verify the update manifests applications need to already have information from you for how to verify it. this is in the form of the public part of a cryptographic key included in the original add-on you release. the first step is to create a cryptographic key. simply click the "create" toolbar button or select "create key" from the "keys" menu. 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. once you have a key you need to add its public part to your add-on's install.rdf file. the simplest way to do this is to select the key then click the install toolbar button. you must then locate your install.rdf for mccoy and the public p...
Midas editor module security preferences
...
NSPR Contributor Guide
have a similar api, with some slightly different behavior or different function prototype, then suggest a new api with a different name. c language api the nspr api is a c language api. please do not contribute java, c or other language wrappers. coding style nspr does not have a documented coding style guide. look at the extant code. make yours look like that. some guidelines concerning naming conventions can be found in nspr naming conventions in the nspr reference. see also: xxx ownership of your contribution when you contribute something to nspr, you must have intellectual property rights to that contribution. this means that you cannot give us something you snatched from somewhere else;. it must be your own invention, free and clear of encumberment of anyone or anything else; p...
NSPR Poll Method
ned by in_flags without involving the underlying network transport, its poll method sets the corresponding event in *out_flags on return. for example, consider an i/o layer that buffers input data. if the caller wishes to test for read ready (that is, pr_poll_read is set in in_flags) and the layer has input data buffered, the poll method would set the pr_poll_read event in *out_flags. it can determine that without asking the underlying network transport. the current implementation of pr_poll (the primary user of the poll method) requires that the events in *out_flags reflect the caller's view. this requirement may be relaxed in a future nspr release. to remain compatible with this potential semantic change, nspr clients should only use *out_flags as described in the how to use the poll method...
NSPR build instructions
bug build by default. --disable-debug --enable-optimize specify these two options to generate an optimized (release) build. these two options can actually be used independently, but it's not recommended. --enable-64bit on a dual 32-bit/64-bit platform, nspr build generates a 32-bit build by default. to generate a 64-bit build, specify the --enable-64bit configure option. --target=x86_64-pc-mingw32 for 64-bit builds on windows, when using the mozillabuild environment. --enable-win32-target=win95 this option is only used on windows. nspr build generates a "winnt" configuration by default on windows for historical reasons. we recommend most applications use the "win95" configuration. the "win95" configuration supports all versions of windows. the "win95" name is historical; it should h...
NSPR release procedure
release checklist change the nspr version in mozilla/nsprpub/pr/include/prinit.h. change the nspr version in mozilla/nsprpub/{configure.in,configure}. change the nspr version in mozilla/nsprpub/pr/tests/vercheck.c. change the nspr version in mozilla/nsprpub/admin/repackage.sh. source tarball binary distributions right now i use the mozilla/nsprpub/admin/repackage.sh script to generate the binary distributions published on ftp.mozilla.org. as the name of the shell script implies, repackage.sh merely repackages binary distributions in a different format. before you run repackage.sh, you need to have built the binary distributions using the "gmake release" makefile target. these binary distributions are jar files, which are really zip files, and they are published in the directory /...
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. most of these are derived from netscape servers. netscape alumni took nspr with them to their new companies: good technology, kontiki, tellme networks. ...
Anonymous Shared Memory
red memory. on platforms where the shared memory is backed by a file, the file's name in the filesystem is visible to other processes for only the duration of the creation of the file, hopefully a very short time. this restricts processes that do not inherit the shared memory from opening the file and reading or writing its contents. further, when all processes using an anonymous shared memory terminate, the backing file is deleted. ... if you are not paranoid, you're not paying attention. the file-mapped shared memory requires a protocol for the parent process and child process to share the memory. nspr provides two protocols. use one or the other; don't mix and match. in the first protocol, the job of passing the inheritable shared memory is done via helper-functions with pr_createprocess...
Dynamic Library Linking
it also provides a method by which to condition symbols of statically linked code so that to other clients it appears as though they are dynamically loaded. library linking types these data types are defined for dynamic library linking: prlibrary prstaticlinktable library linking functions the library linking functions are: pr_setlibrarypath pr_getlibrarypath pr_getlibraryname pr_freelibraryname pr_loadlibrary pr_unloadlibrary pr_findsymbol pr_findsymbolandlibrary finding symbols defined in the main executable program pr_loadlibrary cannot open a handle that references the main executable program. ...
Locks
n variables communicate changes in state among threads. when a programmer associates a mutex with an arbitrary collection of data, the mutex provides a protective monitor around the data. in general, a monitor is a conceptual entity composed of a mutex, one or more condition variables, and the monitored data. monitors in this generic sense should not be confused with monitors used in java programming. in addition to prlock, nspr provides another mutex type, prmonitor, which is reentrant and can have only one associated condition variable. prmonitor is intended for use with java and reflects the java approach to thread synchronization. for an introduction to nspr thread synchronization, including locks and condition variables, see introduction to nspr. for reference information on nspr cond...
Memory Management Operations
gnatures as their libc equivalents malloc(), calloc(), realloc(), and free(), and have the same semantics. ...
Monitors
this chapter describes the nspr api for creation and manipulation of a mutex of type prmonitor. monitor type monitor functions with a mutex of type prlock, a single thread may enter the monitor only once before it exits, and the mutex can have multiple associated condition variables. with a mutex of type prmonitor, a single thread may re-enter a monitor as many times as it sees fit. the first time the thread enters a monitor, it acquires the monitor's lock and the thread's entry count is incremented to 1. ...
NSPR Types
the most common nspr types. other chapters describe more specialized types when describing the functions that use them. calling convention types are used for externally visible functions and globals. algebraic types of various lengths are used for integer algebra. miscellaneous types are used for representing size, pointer difference, boolean values, and return values. for information on naming conventions for nspr types, functions, and macros, see nspr naming conventions. calling convention types these types are used to support cross-platform declarations of prototypes and implementations: pr_extern is used for declarations of external functions or variables. pr_implement is used for definitions of external functions or variables. pr_callback is used for definitions and declara...
Network Addresses
s types and constants network address functions the api described in this chapter recognizes the emergence of internet protocol version 6 (ipv6). to facilitate the transition to ipv6, it is recommended that clients treat all structures containing network addresses as transparent objects and use the functions documented here to manipulate the information. if used consistently, this api also eliminates the need to deal with the byte ordering of network addresses. typically, the only numeric declarations required are the well-known port numbers that are part of the prnetaddr structure. network address types and constants prhostent prprotoent pr_netdb_buf_size network address functions initializing a network address pr_initializenetaddr facilitates the use of prnetaddr, the basic ne...
PL_HashTableLookup
fied by key. key a pointer to the key for the entry to look up. returns the value of the entry with the specified key, or null if there is no such entry. description if there is no entry with the specified key, pl_hashtablelookup returns null. this means that one cannot tell whether a null return value means the entry does not exist or the value of the entry is null. keep this ambiguity in mind if you want to store null values in a hash table. ...
PL_strcpy
...
PL_strdup
ew memory node in the nspr heap containing a copy of a specified string. syntax #include <plstr.h> char *pl_strdup(const char *s); parameter the function has a single parameter: s the string to copy, may be null. returns the function returns one of these values: if successful, a pointer to a copy of the specified string. if the memory allocation fails, null. description to accommodate the terminator, the size of the allocated memory is one greater than the length of the string being copied. a null argument, like a zero-length argument, results in a pointer to a one-byte block of memory containing the null value. notes the memory allocated by pl_strdup should be freed with pl_strfree. ...
PRIOMethods
e; prgetsocknamefn getsockname; prgetpeernamefn getpeername; prgetsockoptfn getsockopt; prsetsockoptfn setsockopt; }; typedef struct priomethods priomethods; parameters file_type type of file represented (tos). close close file and destroy descriptor. read read up to the specified number of bytes into buffer. write write specified number of bytes from buffer. available determine number of bytes available for reading. available64 same as previous field, except 64-bit. fsync flush all in-memory buffers of file to permanent store. seek position the file pointer to the desired place. seek64 same as previous field, except 64-bit. fileinfo get information about an open file. fileinfo64 same as previous field, except 64-bit. writev write from a vector of buffers.
PRLinger
ata remain in the socket send buffer. syntax #include <prio.h> typedef struct prlinger { prbool polarity; printervaltime linger; } prlinger; fields the structure has the following fields: polarity polarity of the option's setting: pr_false means the option is off, in which case the value of linger is ignored. pr_true means the option is on, and the value of linger will be used to determine how long pr_close waits before returning. linger time (in printervaltime units) to linger before closing if any data remain in the socket send buffer. description by default, pr_close returns immediately, but if there are any data remaining in the socket send buffer, the system attempts to deliver the data to the peer. the pr_sockopt_linger socket option, with a value represented by a structu...
PRLogModuleLevel
the enumerated type prlogmodulelevel defines levels of logging available to application programs. syntax #include <prlog.h> typedef enum prlogmodulelevel { pr_log_none = 0, pr_log_always = 1, pr_log_error = 2, pr_log_warning = 3, pr_log_debug = 4, pr_log_notice = pr_log_debug, pr_log_warn = pr_log_warning, pr_log_min = pr_log_debug, pr_log_max = pr_log_debug } prlogmodulelevel; ...
PRProtoEnt
ry returned by pr_getprotobyname and pr_getprotobynumber. syntax #include <prnetdb.h> typedef struct prprotoent { char *p_name; char **p_aliases; #if defined(_win32) print16 p_num; #else print32 p_num; #endif } prprotoent; fields the structure has the following fields: p_name pointer to official protocol name. p_aliases pointer to a pointer to a list of aliases. the list is terminated with a null entry. p_num protocol number. ...
PRThreadPriority
pr_priority_last = 3 } prthreadpriority; enumerators pr_priority_first placeholder. pr_priority_low the lowest possible priority. this priority is appropriate for threads that are expected to perform intensive computation. pr_priority_normal the most commonly expected priority. pr_priority_high slightly higher priority than pr_priority_normal. this priority is for threads performing work of high urgency but short duration. pr_priority_urgent highest priority. only one thread at a time typically has this priority. pr_priority_last placeholder description in general, an nspr thread of higher priority has a statistically better chance of running relative to threads of lower priority. however, because of the multiple strategies nspr uses to implement threading on various...
PRThreadPrivateDTOR
...
PRThreadType
the type of an nspr thread, specified as a parameter to pr_createthread. syntax #include <prthread.h> typedef enum prthreadtype { pr_user_thread, pr_system_thread } prthreadtype; enumerators pr_user_thread pr_cleanup blocks until the last thread of type pr_user_thread terminates. pr_system_thread nspr ignores threads of type pr_system_thread when determining when a call to pr_cleanup should return. description threads can be either user threads or system threads. nspr allows the client to synchronize the termination of all user threads and ignores those created as system threads. this arrangement implies that a system thread should not have volatile data that needs to be safely stored away. the applicability of system threads is somewhat dubious; therefore, they should be...
PRTime
he nspr epoch, midnight (00:00:00) 1 january 1970 coordinated universal time (utc). a time after the epoch has a positive value, and a time before the epoch has a negative value. in nspr, we use the more familiar term greenwich mean time (gmt) in place of utc. although utc and gmt are not exactly the same in their precise definitions, they can generally be treated as if they were. note: keep in mind that while prtime stores times in microseconds since epoch, javascript date objects store times in milliseconds since epoch. ...
PRTimeParameters
. the prtimeparameters structure represents the local time zone information in terms of the offset (in seconds) from gmt. the overall offset is broken into two components: tp_gmt_offset the offset of the local standard time from gmt. tp_dst_offset if daylight savings time (dst) is in effect, the dst adjustment from the local standard time. this is most commonly 1 hour, but may also be 30 minutes or some other amount. if dst is not in effect, the tp_dst_offset component is 0. for example, the us pacific time zone has both a standard time zone (pacific standard time, or pst) and a daylight time zone (pacific daylight time, or pdt). in pst, the local time is 8 hours behind gmt, so tp_gmt_offset is -28800 seconds. tp_dst_offset is 0, indicating that daylight saving time is not in ef...
PR_Access
how specifies which access permission to check for. use one of the following values: pr_access_read_ok. test for read permission. pr_access_write_ok. test for write permission. pr_access_exists. check existence of file. returns one of the following values: if the requested access is permitted, pr_success. if the requested access is not permitted, pr_failure. ...
PR_Assert
syntax #include <prlog.h> void pr_assert ( const char *s, const char *file, printn ln); parameters the function has these parameters: s a string to be displayed in the log. file the file name of the compilation unit containing this function call. ln the line number within the specified file of this function call. returns nothing description this function displays data in the log. ...
PR_Available
syntax #include <prio.h> print32 pr_available(prfiledesc *fd); parameter the function has the following parameter: fd pointer to a prfiledesc object representing a file or socket. returns the function returns one of the following values: if the function completes successfully, it returns the number of bytes that are available for reading. for a normal file, these are the bytes beyond the current file pointer. if the function fails, it returns the value -1. the error code can then be retrieved via pr_geterror. description pr_available works on normal files and sockets. ...
PR_Available64
syntax #include <prio.h> print64 pr_available64(prfiledesc *fd); parameter the function has the following parameter: fd pointer to a prfiledesc object representing a file or socket. returns the function returns one of the following values: if the function completes successfully, it returns the number of bytes that are available for reading. for a normal file, these are the bytes beyond the current file pointer. if the function fails, it returns the value -1. the error code can then be retrieved via pr_geterror. description pr_available64 works on normal files and sockets. ...
PR_CWait
ion that the monitor's state has changed. while the thread is waiting, it exits the monitor (just as if it had called pr_cexitmonitor as many times as it had called pr_centermonitor). when the wait has finished, the thread regains control of the monitor's lock with the same entry count as before the wait began. the thread waiting on the monitor resumes execution when the monitor is notified (assuming the thread is the next in line to receive the notify) or when the interval specified in the timeout parameter has been exceeded. when the thread resumes execution, it is the caller's responsibility to test the state of the monitored data to determine the appropriate action. ...
PR_Cleanup
#include <prinit.h> prstatus pr_cleanup(void); returns the function returns one of the following values: if nspr has been shut down successfully, pr_success. if the calling thread of this function is not the primordial thread, pr_failure. description pr_cleanup must be called by the primordial thread near the end of the main function. pr_cleanup attempts to synchronize the natural termination of the process. it does so by blocking the caller, if and only if it is the primordial thread, until all user threads have terminated. when the primordial thread returns from main, the process immediately and silently exits. that is, the process (if necessary) forcibly terminates any existing threads and exits without significant blocking and without error messages or core files. ...
PR_ConnectContinue
rns. - other errors: the nonblocking connect has failed with this error code. description continue a nonblocking connect. after a nonblocking connect is initiated with pr_connect() (which fails with pr_in_progress_error), one should call pr_poll() on the socket, with the in_flags pr_poll_write | pr_poll_except. when pr_poll() returns, one calls pr_connectcontinue() on the socket to determine whether the nonblocking connect has completed or is still in progress. repeat the pr_poll(), pr_connectcontinue() sequence until the nonblocking connect has completed. ...
PR_GMTParameters
urns the time zone offset information that maps the specified prexplodedtime to gmt. note: since this function requires gmt as input, its primary use is as "filler" for cases in which you need a do-nothing callback. syntax #include <prtime.h> prtimeparameters pr_gmtparameters ( const prexplodedtime *gmt); parameter gmt a pointer to the clock/calendar time whose offsets are to be determined. this time should be specified in gmt. returns a time parameters structure that expresses the time zone offsets at the specified time. description this is a frequently-used time parameter callback function. you don't normally call it directly; instead, you pass it as a parameter to pr_explodetime() or pr_normalizetime(). this is a trivial function; for any input, it returns a prtimeparame...
PR GetAddrInfoByName
drinfo *pr getaddrinfobyname( const char *hostname, pruint16 af, printn flags); parameters the function has the following parameters: hostname the character string defining the host name of interest. af the address family. may be pr_af_unspec or pr_af_inet. flags may be either pr_ai_addrconfig or pr_ai_addrconfig | pr_ai_nocanonname. include pr_ai_nocanonname to suppress the determination of the canonical name corresponding to hostname returns the function returns one of the following values: if successful, a pointer to the opaque praddrinfo structure containing the results of the host lookup. use pr_enumerateaddrinfo to inspect the prnetaddr values stored in this structure. when no longer needed, this pointer must be destroyed with a call to pr_freeaddrinfo. if unsucc...
PR_GetConnectStatus
...
PR_GetLibraryName
lib the leaf name of the library of interest. returns if successful, returns a new character string containing a constructed path name. in case of error, returns null. description this function constructs a full path name from the specified directory name and library name. ...
PR_GetRandomNoise
and its ability to provide a random value at that moment. pr_getrandomnoise is intended to provide a "seed" value for a another random number generator that may be suitable for cryptographic operations. this implies that the random value provided may not be, by itself, cryptographically secure. the value generated by pr_getrandomnoise is at best, extremely difficult to predict and is as nondeterministic as the underlying platfrom permits. ...
PR_InitializeNetAddr
paddrany, pr_ipaddrloopback } prnetaddrvalue; the enum has the following enumerators: pr_ipaddrnull do not overwrite the ip address. this allows the caller to change the network address' port number assignment without affecting the host address. pr_ipaddrany assign logical pr_inaddr_any to ip address. this wildcard value is typically used to establish a socket on which to listen for incoming connection requests. pr_ipaddrloopback assign logical pr_inaddr_loopback. a client can use this value to connect to itself without knowing the host's network address. ...
PR_Interrupt
ude <prthread.h> prstatus pr_interrupt(prthread *thread); parameter pr_interrupt has the following parameter: thread the thread whose interrupt request you want to set. returns the function returns one of the following values: if the specified thread is currently blocked, pr_success. otherwise, pr_failure. description the purpose of pr_interrupt is to request that a thread performing some task stop what it is doing and return to some control point. it is assumed that a control point has been mutually arranged between the thread doing the interrupting and the thread being interrupted. when the interrupted thread reaches the prearranged point, it can communicate with its peer to discover the real reason behind the change in plans. the interrupt request remains in the thread's...
PR_IntervalNow
pr_intervalnow() is both very efficient and nonblocking, so it is appropriate to use (for example) while holding a mutex. ...
PR_LOG
prlogmodulelevel _level ... _args); parameters the macro has these parameters: _module a pointer to a log module structure. _level a level value. possible values are: pr_log_none = 0 pr_log_always = 1 pr_log_error = 2 pr_log_warning = 3 pr_log_debug = 4 pr_log_notice = pr_log_debug pr_log_warn = pr_log_warning pr_log_min = pr_log_debug pr_log_max = pr_log_debug _args a variable length argument list, as if to printf. returns nothing description this macro formats the specified arguments and writes the output to the log file, if logging is enabled for the specified module and level. for a description of formatting and format strings, see "formatted printi...
PR_LOG_TEST
determines if logging is enabled for a module and level. syntax #include <prlog.h> prbool pr_log_test ( prlogmoduleinfo *_module, prlogmodulelevel _level); parameters the macro has these parameters: _module a pointer to a log module structure. _level a level value. possible values are: pr_log_none = 0 pr_log_always = 1 pr_log_error = 2 pr_log_warning = 3 pr_log_debug = 4 pr_log_notice = pr_log_debug pr_log_warn = pr_log_warning pr_log_min = pr_log_debug pr_log_max = pr_log_debug returns pr_true when logging is enabled for the given module and level, otherwise pr_false. description this macro tests whether logging is enabled for the specified modul...
PR_LocalTimeParameters
this time should be specified in gmt. ...
PR_NetAddrToString
uffer that will hold the converted string on output. size the size of the result buffer (string). returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. you can retrieve the reason for the failure by calling pr_geterror. description the network address to be converted (addr) may be either an ipv4 or ipv6 address structure, assuming that the nspr library and the host system are both configured to utilize ipv6 addressing. if addr is an ipv4 address, size needs to be at least 16. if addr is an ipv6 address, size needs to be at least 46. ...
PR_NormalizeTime
e in the prexplodedtime format. params a time parameter callback function. returns nothing; the time parameter is altered by the 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. call this function in these situations: to normalize a time after performing arithmetic operations directly on the field values of the calendar time object. for example, if you have a ] object that represents the date 3 march 1998 and you want to say "forty days from 3 march 1998", you can simply add 40 to the tm_mday field and then call pr_normalizetime(). to calculate the optional field values tm_wday and tm_yday. for example, suppose you want to compute the day of...
PR_Notify
pr_failure. description notification of a monitor signals the change of state of some monitored data. the changing of that data and the notification must all be performed while in the monitor. when the notification occurs, the runtime promotes a thread that is waiting on the monitor to a ready state. if more than one thread is waiting, the selection of which thread gets promoted cannot be determined in advance. this implies that all threads waiting on a single monitor must have the same semantics. if no thread is waiting on the monitor, the notify operation is a no-op. ...
PR_Poll
ntervaltime timeout); parameters the function has the following parameters: pds a pointer to the first element of an array of prpolldesc structures. npds the number of elements in the pds array. if this parameter is zero, pr_poll is equivalent to pr_sleep with a timeout. timeout amount of time the call will block waiting for i/o to become ready. if this time expires without any i/o becoming ready, pr_poll returns zero. returns the function returns one of these values: if successful, the function returns a positive number indicating the number of prpolldesc structures in pds that have events. the value 0 indicates the function timed out. the value -1 indicates the function failed. the reason for the failure can be obtained by calling pr_geterror. description this function...
PR_ProcessExit
causes an immediate, nongraceful, forced termination of the process. syntax #include <prinit.h> void pr_processexit(printn status); parameter pr_processexit has one parameter: status the exit status code of the process. ...
PR_SetErrorText
otherwise the text is assumed to be the length specified and to possibly include null characters (as might occur in a multilingual string). ...
PR_SetThreadPrivate
x is swapped with null. if the swapped out value is not null, the destructor function is called. on return, the private data associated with the index is reassigned the new private data's value, even if it is null. the runtime provides no protection for the private data. the destructor is called with the runtime holding no locks. synchronization is the client's responsibility. the only way to eliminate thread private data at an index prior to the thread's termination is to call pr_setthreadprivate with a null argument. this causes the index's destructor function to be called, and afterwards assigns a null in the table. a client must not delete the referant object of a non-null private data without first eliminating it from the table. ...
PR_ShutdownThreadPool
notifies all threads in a thread pool to terminate. syntax #include <prtpool.h> nspr_api(prstatus) pr_shutdownthreadpool( prthreadpool *tpool ); parameter the function has the following parameter: tpool a pointer to a prthreadpool structure previously created by a call to pr_createthreadpool. returns prstatus ...
PR_VERSION
...
PR_Wait
state change ... pr_exitmonitor(&ml); a thread can be resumed from a wait for a variety of reasons. the most obvious is that it was notified by another thread. if the value of timeout is not pr_interval_no_timeout, pr_wait resumes execution after the specified interval has expired. if a timeout value is used, the boolean expression must include elapsed time as part of the monitored data. resuming from the wait is merely an opportunity to evaluate the expression, not an assertion that the expression is true. ...
PR_dtoa
t string, of the conversion's decimal point. sign a location where the runtime can store an indication that the conversion was of a negative value. *rve if not null this location is set to the address of the end of the result. buf the address of the buffer in which to store the result. bufsz the size of the buffer provided to hold the result. results the principle output is the null-terminated string stored in buf. if rve is not null, *rve is set to point to the end of the returned value. description this function converts the specified floating point number to a string, using the method specified by mode. possible modes are: 0 shortest string that yields d when read in and rounded to nearest. 1 like 0, but with steele & white stopping rule. for example, with ieee 754 arith...
PR_strtod
meter se is not null the location it references is also set. description pr_strtod converts the prefix of the input decimal string pointed to by s00 to a nearest double-precision floating point number. ties are broken by the ieee round-even rule. the string is scanned up to the first unrecognized character. if the value of se is not (char **) null, pr_strtod stores a pointer to the character terminating the scan in *se. if the answer would overflow, a properly signed huge_val (infinity) is returned. if the answer would underflow, a properly signed 0 is returned. in both cases, pr_geterror() returns the error code pr_range_error. if no number can be formed, se is set to s00, and 0 is returned. ...
Process Management and Interprocess Communication
nspr does not provide an equivalent of the unix fork(). the newly-created process executes its program from the beginning. a new process can inherit specified file descriptors from its parent, and the parent can redirect the standard i/o streams of the child process to specified file descriptors. note that the functions described in this chapter are not available for macos or win16 operating systems. ...
String Operations
this chapter describes some of the key nspr functions for manipulating strings. libraries built on top of nspr, such as the netscape security libraries, use these functions to manipulate strings. if you are copying or examining strings for use by such libraries or freeing strings that were allocated by such libraries, you must use these nspr functions rather than the libc equivalents. pl_strlen pl_strcpy pl_strdup pl_strfree ...
Thread Pools
this chapter describes the nspr api thread pools. note: this api is a preliminary version in nspr 4.0 and is subject to change. thread pools create and manage threads to provide support for scheduling work (jobs) onto one or more threads. nspr's thread pool is modeled on the thread pools described by david r. butenhof inprogramming with posix threads (addison-wesley, 1997). thread pool types thread pool functions thread pool types prjobiodesc prjobfn prthreadpool prjob thread pool functions pr_createthreadpool pr_queuejob pr_queuejob_read pr_queuejob_write pr_queuejob_accept pr_queuejob_connect pr_queuejob_timer pr_canceljob pr_joinjob pr_shutdownthreadpool pr_jointhreadpool ...
Running NSPR tests
passed ... sprintf failed ... timetest passed tpd passed udpsrv passed vercheck passed version passed writev passed xnotify passed zerolen passed end mon mar 12 11:55:47 pdt 2007 how to determine if the test suite passed if all the tests reported passed as the results, the test suite passed. what if some of the tests crashed or reported failed as the results? it doesn't necessarily mean the test suite failed because some of the test programs are known to fail. until the test failures are fixed, you should run nspr tests against a known good version of nspr on the same platform, and sav...
Building NSS
for building, you also need make. ...
NSS CERTVerify Log
when you are through, you will need to walk the list and free all the cert entries, then free the arena. ...
Cryptography functions
pk11_getinternalkeyslot mxr 3.2 and later pk11_getinternalslot mxr 3.2 and later pk11_getkeygen mxr 3.4 and later pk11_getkeylength mxr 3.2 and later pk11_getkeystrength mxr 3.2 and later pk11_getmechanism mxr 3.2 and later pk11_getminimumpwdlength mxr 3.4 and later pk11_getmodinfo mxr 3.6 and later pk11_getmodule mxr 3.3 and later pk11_getmoduleid mxr 3.2 and later pk11_getnextgenericobject mxr 3.9.2 and later pk11_getnextsafe mxr 3.4 and later pk11_getnextsymke...
NSS FAQ
Mozilla › Projects › NSS › FAQ
re about tls? see https://developer.mozilla.org/docs/glossary/tls. licensing questions how is nss licensed? nss is available under the mozilla public license, version 2. is nss available outside the united states? this section is out of date yes; see build instructions for nss 3.1. and ftp://ftp.mozilla.org/pub/mozilla.org/security/. however, nss source code is subject to the u.s. export administration regulations and other u.s. law, and may not be exported or re-exported to certain countries (cuba, iran, iraq, libya, north korea, serbia, sudan, syria, and taleban-controlled areas of afghanistan as of january 2000) or to persons or entities prohibited from receiving u.s. exports (including those (a) on the bureau of industry and security denied parties list or entity list, (b) on the o...
Getting Started With NSS
of nss? we are looking forward to your contributions! we have a large list of tasks waiting for attention, and we are happy to assist you in identifying areas that match your interest or skills. you can find us on mozilla irc in channel #nss or you could ask your questions on the mozilla.dev.tech.crypto newsgroup. the nss library and its supporting command line tools are written in the c programming language. its build system and the automated tests are based on makefiles and bash scripts. over time, many documents have been produced that describe various aspects of nss. you can start with: the current primary nss documentation page from which we link to other documentation. a general overview of the applications that use nss and the features it provides. a high level introduction to ...
Introduction to Network Security Services
2 , see migration from nss 3.1.1. figure 1, below, shows a simplified view of the relationships among the three shared libraries listed above and nspr, which provides low-level cross platform support for operations such as threading and i/o. (note that nspr is a separate mozilla project; see netscape portable runtime for details.) figure 1 relationships among core nss libraries and nspr naming conventions and special libraries windows and unix use different naming conventions for static and dynamic libraries: windows unix static .lib .a dynamic .dll .so or .sl in addition, windows has "import" libraries that bind to dynamic libraries. so the nss library has the following forms: libnss3.so - unix shared library libnss3.sl - hp...
4.3.1 Release Notes
new in jss 4.3.1 a list of bug fixes and enhancement requests were implemented in this release can be obtained by running this bugzilla query jss 4.3.1 requires nss 3.12.5 or higher. ssl3 & tls renegotiation vulnerability see cve-2009-3555 and us-cert vu#120541 for more information about this security vulnerability. ...
4.3 Release Notes
new in jss 4.3 a list of bug fixes and enhancement requests were implemented in this release can be obtained by running this bugzilla query jss 4.3 requires nss 3.12 or higher. ...
Build instructions for JSS 4.3.x
install a java compiler and runtime. jss supports java version 1.5 or later. we suggest you use the latest. ...
JSS 4.4.0 Release Notes
distribution information the hg tag is jss_4_4_20170313. jss 4.4.0 requires netswork security services (nss) 3.29.1 and netscape portable runtime (nspr) 4.13.1 or newer. jss 4.4.0 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/jss/releases/jss_4_4_0_rtm/src/ new in jss 4.40 new functionality new functions new macros notable changes in jss 4.40 picks up work done downstream for fedora and rhel and used by various linux distributions with includes:. support for ipv6. ...
NSS_3.12.1_release_notes.html
ers 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.4 release notes
nssckbi pkcs #11 module's version changed to 1.75. obsolete code for win16 has been removed. support for openvms has been removed. bugs fixed the following bugs have been fixed in nss 3.12.4. ...
NSS 3.12.5 release_notes
ate undiscoverable by cert_pkixverifycert bug 518443: pk11_importandreturnprivatekey leaks an arena bug 518446: pk11_derencodepublickey leaks a certsubjectpublickeyinfo bug 518457: seckey_encodedersubjectpublickeyinfo and pk11_derencodepublickey are duplicate bug 522510: add deprecated comments to key.h and pk11func.h bug 522580: nss uses port_memcmp for comparing secret data. bug 525056: timing attack against ssl3ext.c:ssl3_serverhandlesessionticketxtn() bug 526689: ssl3 & tls renegotiation vulnerability documentation for a list of the primary nss documentation pages on mozilla.org, see nss documentation. new and revised documents available since the release of nss 3.11 include the following: build instructions nss shared db compatibility nss 3.12.5 shared libraries ...
NSS 3.14.3 release notes
ed block of data. 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. notable changes in nss 3.14.3 cve-2013-1620 recent research by nadhem alfardan and kenny patterson has highlighted a weakness in the handling of cbc padding as used in ssl, tls, and dtls that allows an attacker to exploit timing differences in mac processing. the details of their research and the attack can be found at http://www.isg.rhul.ac.uk/tls/, and has been referred to as "lucky thirteen". nss 3.14.3 includes changes to the softoken and ssl libraries to address and mitigate these attacks, contributed by adam langley of google. this attack is mitigated when using nss 3.14.3 with an nss cryptographic module ("so...
NSS 3.15 release notes
distribution information the hg tag is nss_3_15_rtm. nss 3.15 requires nspr 4.10 or newer. nss 3.15 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_15_rtm/src/ new in nss 3.15 new functionality support for ocsp stapling (rfc 6066, certificate status request) has been added for both client and server sockets. tls client applications may enable this via a call to ssl_optionsetdefault(ssl_enable_ocsp_stapling, pr_true); added function secitem_reallocitemv2. ...
NSS 3.16.2.3 release notes
h ssl_error_inappropriate_fallback_alert - a new ssl error code. in sslproto.h tls_fallback_scsv - a a signaling cipher suite value that indicates a handshake is the result of tls version fallback. notable changes in nss 3.16.2.3 bug 1057161: check that an imported elliptic curve public key is valid. previously nss would only validate the peer's public key before performing ecdh key agreement. now ec public keys are validated at import time. bugs fixed in nss 3.16.2.3 bug 1057161 - nss hangs with 100% cpu on invalid ec key bug 1036735 - add support for draft-ietf-tls-downgrade-scsv to nss compatibility nss 3.16.2.3 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will wor...
NSS 3.16.4 release notes
hanges as listed below, and includes a small number of bug fixes. notable changes in nss 3.16.4 the following 1024-bit root ca certificate was restored to allow more time to develop a better transition strategy for affected sites. it was removed in nss 3.16.3, but discussion in the mozilla.dev.security.policy forum led to the decision to keep this root included longer in order to give website administrators more time to update their web servers. cn = gte cybertrust global root sha1 fingerprint: 97:81:79:50:d8:1c:96:70:cc:34:d8:09:cf:79:44:31:36:7e:f4:74 in nss 3.16.3, the 1024-bit "entrust.net secure server certification authority" root ca certificate (sha1 fingerprint: 99:a6:9b:e6:1a:fe:88:6b:4d:2b:82:00:7c:b8:54:fc:31:7e:15:39) was removed. in nss 3.16.4, a ...
NSS 3.16 release notes
introduction the nss team has released network security services (nss) 3.16, which is a minor release. distribution information the hg tag is nss_3_16_rtm. nss 3.16 requires nspr 4.10.3 or newer. nss 3.16 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_16_rtm/src/ new in nss 3.16 new functionality supports the linux x32 abi. (this requires nspr 4.10.4.) to build for the linux x32 target, set the environment variable use_x32=1 when building nss. new functions in cms.h nss_cmssignerinfo_verify - verify the signature of a single signerinfo. it just verifies the signature, assuming that the certificate has been verified already. new macros in sslpro...
NSS 3.17.2 release notes
changes in nss 3.17.2 bug 1049435: change rsa_privatekeycheck to not require p > q. this fixes a regression introduced in nss 3.16.2 that prevented nss from importing some rsa private keys (such as in pkcs #12 files) generated by other crypto libraries. bug 1057161: check that an imported elliptic curve public key is valid. previously nss would only validate the peer's public key before performing ecdh key agreement. now ec public keys are validated at import time. bug 1078669: certutil crashes when an argument is passed to the --certversion option. bugs fixed in nss 3.17.2 this bugzilla query returns all the bugs fixed in nss 3.17.2: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.17.2 compatibilit...
NSS 3.17 release notes
distribution information the hg tag is nss_3_17_rtm. nss 3.17 requires nspr 4.10.7 or newer. 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.1 release notes
ca certificate had the websites and code signing trust bits restored to their original state to allow more time to develop a better transition strategy for affected sites. the websites and code signing trust bits were turned off in nss 3.18. but when firefox 38 went into beta, there was a huge spike in the number of certificate verification errors attributed to this change. so, to give website administrators more time to update their web servers, we reverted the trust bits back to being enabled. ou = equifax secure certificate authority sha1 fingerprint: d2:32:09:ad:23:d3:14:23:21:74:e4:0d:7f:9d:62:13:97:86:63:3a the following ca certificate was removed after discussion about it in the mozilla.dev.security.policy forum. cn = e-guven kok elektronik sertif...
NSS 3.18 release notes
distribution information the hg tag is nss_3_18_rtm. nss 3.18 requires nspr 4.10.8 or newer. 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.19.2.1 release notes
/mozilla.org/security/nss/releases/nss_3_19_2_1_rtm/src/ https://ftp.mozilla.org/pub/nspr/releases/v4.10.10/src/ security advisories the following security-relevant bugs have been resolved in nss 3.19.2.1. users are encouraged to upgrade immediately. bug 1192028 (cve-2015-7181) and bug 1202868 (cve-2015-7182): several issues existed within the asn.1 decoder used by nss for handling streaming ber data. while the majority of nss uses a separate, unaffected der decoder, several public routines also accept ber data, and thus are affected. an attacker that successfully exploited these issues can overflow the heap and may be able to obtain remote code execution. the following security-relevant bugs have been resolved in nspr 4.10.10, which affect nss. because nss includes portions of t...
NSS 3.19.4 release notes
/pub/mozilla.org/security/nss/releases/nss_3_19_4_rtm/src/ https://ftp.mozilla.org/pub/nspr/releases/v4.10.10/src/ security advisories the following security-relevant bugs have been resolved in nss 3.19.4. users are encouraged to upgrade immediately. bug 1192028 (cve-2015-7181) and bug 1202868 (cve-2015-7182): several issues existed within the asn.1 decoder used by nss for handling streaming ber data. while the majority of nss uses a separate, unaffected der decoder, several public routines also accept ber data, and thus are affected. an attacker that successfully exploited these issues can overflow the heap and may be able to obtain remote code execution. the following security-relevant bugs have been resolved in nspr 4.10.10, which affect nss. because nss includes portions of t...
NSS 3.19 release notes
distribution information the hg tag is nss_3_19_rtm. nss 3.19 requires nspr 4.10.8 or newer. nss 3.19 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_19_rtm/src/ security fixes in nss 3.19 bug 1086145 / cve-2015-2721 - fixed a bug related to the ordering of tls handshake messages. this was also known as smack. ...
NSS 3.20.1 release notes
/pub/mozilla.org/security/nss/releases/nss_3_20_1_rtm/src/ https://ftp.mozilla.org/pub/nspr/releases/v4.10.10/src/ security advisories the following security-relevant bugs have been resolved in nss 3.20.1. users are encouraged to upgrade immediately. bug 1192028 (cve-2015-7181) and bug 1202868 (cve-2015-7182): several issues existed within the asn.1 decoder used by nss for handling streaming ber data. while the majority of nss uses a separate, unaffected der decoder, several public routines also accept ber data, and thus are affected. an attacker that successfully exploited these issues can overflow the heap and may be able to obtain remote code execution. the following security-relevant bugs have been resolved in nspr 4.10.10, which affect nss. because nss includes portions of t...
NSS 3.21.2 release notes
21.2 requires nspr 4.10.10 or newer. nss 3.21.2 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_21_2_rtm/src/ new in nss 3.21.2 new functionality no new functionality is introduced in this release. security fixes in nss 3.21.2 bug 1293334 / cve-2016-9074 - fixed a timing side channel in the tls cbc code. compatibility nss 3.21.2 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.21.2 shared libraries without recompiling or relinking. furthermore, applications that restrict their use of nss apis to the functions listed in nss public functions will remain co...
NSS 3.25 release notes
distribution information the hg tag is nss_3_25_rtm. nss 3.25 requires netscape portable runtime (nspr) 4.12 or newer. nss 3.25 source distributions are available on ftp.mozilla.org for secure https download at the following location. source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_25_rtm/src/ new in nss 3.25 new functionality implemented dhe key agreement for tls 1.3. added support for chacha with tls 1.3. added support for tls 1.2 ciphersuites that use sha384 as the prf. ...
NSS 3.26 release notes
distribution information the hg tag is nss_3_26_rtm. nss 3.26 requires netscape portable runtime (nspr) 4.12 or newer. ...
NSS 3.27 release notes
distribution information the hg tag is nss_3_27_rtm. nss 3.27 requires netscape portable runtime (nspr) 4.13 or newer. nss 3.27 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_27_rtm/src/ new in nss 3.27 new functionality allow custom named group priorities for tls key exchange handshake (ssl_namedgroupconfig). ...
NSS 3.28.1 release notes
_rtm. nss 3.28.1 requires nspr 4.13.1 or newer. nss 3.28.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_28_1_rtm/src/ new in nss 3.28.1 no new functionality is introduced in this release. this is a patch release to update the list of root ca certificates, and address a minor tls compatibility issue, that some applications experienced with nss 3.28. notable changes in nss 3.28.1 the following ca certificates were removed cn = buypass class 2 ca 1 sha-256 fingerprint: 0f:4e:9c:dd:26:4b:02:55:50:d1:70:80:63:40:21:4f:e9:44:34:c9:b0:2f:69:7e:c7:10:fc:5f:ea:fb:5e:38 cn = root ca generalitat valenciana sha-256 fingerprint: 8c:4e:...
NSS 3.28 release notes
distribution information the hg tag is nss_3_28_rtm. nss 3.28 requires netscape portable runtime (nspr) 4.13.1 or newer. nss 3.28 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_28_rtm/src/ new in nss 3.28 new functionality nss includes support for tls 1.3 draft -18. this includes a number of improvements to tls 1.3: the signed certificate timestamp, used in certificate transparency, is supported in tls 1.3 (bug 1252745). ...
NSS 3.29 release notes
distribution information the hg tag is nss_3_29_rtm. nss 3.29 requires netscape portable runtime (nspr) 4.13.1 or newer. nss 3.29 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_29_rtm/src/ notable changes in nss 3.29 fixed a nss 3.28 regression in the signature scheme flexibility that causes connectivity issues between ios 8 clients and nss servers with ecdsa certificates (bug1334114). tls 1.3 is now enabled by default in (bug1311296). ...
NSS 3.30 release notes
distribution information the hg tag is nss_3_30_rtm. nss 3.30 requires netscape portable runtime (nspr); 4.13.1 or newer. nss 3.30 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_30_rtm/src/ new in nss 3.30 new functionality in the pkcs#11 root ca module (nssckbi), cas with positive trust are marked with a new boolean attribute, cka_nss_mozilla_ca_policy, set to true. ...
NSS 3.31 release notes
distribution information the hg tag is nss_3_31_rtm. nss 3.31 requires netscape portable runtime (nspr) 4.15 or newer. nss 3.31 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_31_rtm/src/ new in nss 3.31 new functionality allow certificates to be specified by rfc7512 pkcs#11 uris. allow querying a certificate object for its temporary or permanent storage status in a thread safe way. ...
NSS 3.34.1 release notes
distribution information the hg tag is nss_3_34.1_rtm. nss 3.34.1 requires netscape portable runtime (nspr) 4.17, or newer. nss 3.34.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_34_1_rtm/src/ notable changes in nss 3.34.1 the following ca certificate was re-added. it was previously removed in nss 3.34, but now re-added with only the email trust bit set. (bug 1418678) cn = certum ca, o=unizeto sp. z o.o. ...
NSS 3.34 release notes
distribution information the hg tag is nss_3_34_rtm. nss 3.34 requires netscape portable runtime (nspr) 4.17, or newer. ...
NSS 3.36.6 release notes
d: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_36_6_rtm/src/ new in nss 3.36.6 new functionality no new functionality is introduced in this release. this is a patch release to fix cve-2018-12404 bugs fixed in nss 3.36.6 bug 1485864 - cache side-channel variant of the bleichenbacher attack (cve-2018-12404) bug 1389967 and bug 1448748 - fixes for mingw on x64 platforms. compatibility nss 3.36.6 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.36.6 shared libraries without recompiling or relinking. furthermore, applications that restrict their use of nss apis to the functions listed in nss public functions will remain compatible with ...
NSS 3.36 release notes
distribution information the hg tag is nss_3_36_rtm. nss 3.36 requires nspr 4.19 or newer. nss 3.36 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_36_rtm/src/ (make a link) new in nss 3.36 new functionality experimental apis for tls session cache handling. notable changes in nss 3.36 replaced existing vectorized chacha20 code with verified hacl* implementation. ...
NSS 3.37 release notes
distribution information the hg tag is nss_3_37_rtm. nss 3.37 requires nspr 4.19 or newer. nss 3.37 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_37_rtm/src/ notable changes in nss 3.37 the tls 1.3 implementation was updated to draft 28. an issue where nss erroneously accepted hrr requests was resolved. this issue was found by oss fuzz. ...
NSS 3.38 release notes
distribution information the hg tag is nss_3_38_rtm. nss 3.38 requires nspr 4.19 or newer. nss 3.38 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_38_rtm/src/ new in nss 3.38 new functionality added support for the tls record size limit extension. when creating a certificate request (csr) using certutil -r, an existing orphan private key can be reused. parameter -k may be used to specify the id of an existing orphan key. ...
NSS 3.39 release notes
distribution information the hg tag is nss_3_39_rtm. nss 3.39 requires nspr 4.20 or newer. 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. nss will use rsa-pss keys to authenticate in tls. ...
NSS 3.40 release notes
distribution information the hg tag is nss_3_40_rtm. nss 3.40 requires nspr 4.20 or newer. nss 3.40 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_40_rtm/src/ new in nss 3.40 new functionality the draft-00 version of encrypted sni support is implemented tstclnt now takes -n option to specify encrypted sni key new functions none notable changes in nss 3.40 the mozilla::pkix library has been ported from mozilla psm to nss. ...
NSS 3.41 release notes
distribution information the hg tag is nss_3_41_rtm. nss 3.41 requires nspr 4.20 or newer. nss 3.41 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_41_rtm/src/ new in nss 3.41 new functionality bug 1252891 - implemented eku handling for ipsec ike. bug 1423043 - enable half-closed states for tls. ...
NSS 3.42 release notes
distribution information the hg tag is nss_3_42_rtm. nss 3.42 requires nspr 4.20 or newer. nss 3.42 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_42_rtm/src/ other releases are available in nss releases. ...
NSS 3.43 release notes
distribution information the hg tag is nss_3_43_rtm. nss 3.43 requires nspr 4.21 or newer. nss 3.43 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_43_rtm/src/ other releases are available in nss releases. ...
NSS 3.44 release notes
the nss team would like to recognize first-time contributors: kevin jacobs, david carlier, alexander scheel, and edouard oger. distribution information the hg tag is nss_3_44_rtm. nss 3.44 requires nspr 4.21 or newer. nss 3.44 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_44_rtm/src/ other releases are available in nss releases. ...
NSS 3.49 release notes
the nss team would like to recognize first-time contributors: alex henrie distribution information the hg tag is nss_3_49_rtm. nss 3.49 requires nspr 4.24 or newer. nss 3.49 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_49_rtm/src/ other releases are available in nss releases. notable changes in nss 3.49 the legacy dbm database, libnssdbm, is no longer built by default when using gyp builds. ...
NSS 3.50 release notes
distribution information the hg tag is nss_3_50_rtm. nss 3.50 requires nspr 4.25 or newer. nss 3.50 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_50_rtm/src/ other releases are available in nss releases. notable changes in nss 3.50 verified primitives from hacl* were updated, bringing performance improvements for several platforms. ...
NSS 3.51.1 release notes
distribution information the hg tag is nss_3_51_1_rtm. nss 3.51.1 requires nspr 4.25 or newer. nss 3.51.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_51_1_rtm/src/ other releases are available in nss releases. notable changes in nss 3.51.1 bug 1617968 - update delegated credentials implementation to draft-07. ...
NSS 3.54 release notes
distribution information the hg tag is nss_3_54_rtm. nss 3.54 requires nspr 4.26 or newer. nss 3.54 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_54_rtm/src/ other releases are available in nss releases. notable changes in nss 3.54 support for tls 1.3 external pre-shared keys (bug 1603042). use arm cryptography extension for sha256, when available. (bug 1528113). ...
NSS 3.56 release notes
distribution information the hg tag is nss_3_56_rtm. nss 3.56 requires nspr 4.28 or newer. nss 3.56 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_56_rtm/src/ other releases are available in nss releases. notable changes in nss 3.56 nspr dependency updated to 4.28. the known issue where makefile builds failed to locate seccomon.h was fixed in bug 1653975. ...
NSS Developer Tutorial
: if (condition) { action(); } or: if (condition) action(); although the use of curly braces is more common. multiple-line comments should be formatted as follows: /* * line1 * line2 */ or /* ** line 1 ** line 2 */ the following styles are also common, because they conserve vertical space: /* line1 * line2 */ or /* line1 ** line2 */ or /* line1 * line2 */ naming public functions are named foo_dooneaction. global, but unexported functions, are usually named foo_dooneaction. variable, and function parameter names, always start with a lowercase letter. the most common style is foobarbaz, although foobarbaz and foo_bar_baz are also used. miscellaneous goto can be used, to simplify resource deallocation, before returning from a function. a data buffer ...
Enc Dec MAC Output Public Key as CSR
pedef enum { gen_csr, encrypt, decrypt, unknown } commandtype; typedef enum { symkey = 0, mackey = 1, iv = 2, mac = 3, pad = 4, pubkey = 5, lab = 6 } headertype; /* this is conditionalized because port_errortostring was introduced with nss 3.13. * though pr_errortostring was available, support for it in nss wasn't. * fixme: samples should determine the version of nss that's available and refuse * to run if not 3.13 or higher. */ #ifndef port_errortostring #ifndef sec_error_base #define sec_error_base (-0x2000) #define port_errortostring(err) pr_errortostring((err), pr_language_i_default) #endif #endif /* * print usage message and exit */ static void usage(const char *progname) { fprintf(stderr, "\nusage: ...
nss tech note4
helper functions compare two secitems (e.g., two oids) prbool secitem_itemsareequal(const secitem *a, const secitem *b); interpreting a secitem value as an integer if secitem *item->len <=4, then int value = der_getinteger(item); interpreting a secitem value as a string use string copy functions to copy item->len bytes from item->data and null terminate explicitly some higher level extension functions get a specific extension from the list of extensions, given the extension tag secstatus cert_findcertextension (certcertificate *cert, int tag, secitem *value); get a specific extension from the issuer's cert secstatus cert_findissuercertextension (certcertificate *cert, in...
nss tech note7
seckeypublickey: a public key, defined in "keythi.h". seckeyprivatekey: a private key, defined in "keythi.h". pk11symkey: a symmetric key (often called a session key), defined in "secmodt.h". these data types should be used as if they were opaque structures, that is, they should only be created by some nss functions and you always pass pointers to these data types to nss functions and never examine the members of these structures. the strength of an rsa key pair is measured by the size of its modulus because given the modulus and public exponent, the best known algorithm for computing the private exponent is to factor the modulus. at present 1024 bit and 2048 bit rsa keys are the most common and recommended. to prevent denial-of-service attacks with huge public keys, nss disallows modul...
NSS Tech Notes
tn1: how to use the nss asn.1 and quickder decoders. tn2: using the pkcs #11 module logger. tn3: all about certificate extensions. tn4: pulling certificate extension information out of ssl certificates. ...
NSS release notes template
or network security services (nss) 3.xx.y is a patch release for nss 3.xx. the bug fixes in nss 3.xx.y are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_xx_rtm. nss 3.xx requires nspr 4.xx or newer. ...
PKCS11 module installation
pkcs #11 modules are external modules which add to firefox support for smartcard readers, biometric security devices, and external certificate stores. this article covers the two methods for installing pkcs #11 modules into firefox. users can use the preferences dialog to install or remove pkcs #11 module. extensions can programmatically manage pkcs #11 modules using the nsipkcs11 programming interface. note: the information in this article is specific to firefox 3.5 and newer. older versions of firefox may support the window.pkcs11 property for installing pkcs #11 modules. 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. choose "advanced" > "encryption" > "secur...
Migration to HG
the first releases using the new code layout will be nspr 4.10 and nss 3.15 ...
FC_FindObjectsFinal
syntax ck_rv fc_findobjectsfinal( ck_session_handle hsession, ); parameters hsession [in] session handle. description clears the object search criteria for a session. ...
FC_InitToken
specifically, fc_inittoken() initializes or clears the key database, removes the password, and then marks all the user certs in the certificate database as non-user certs. (user certs are the certificates that have their associated private keys in the key database.) a user must b...
FC_Initialize
return value fc_initialize returns the following return codes. ckr_ok: library initialization succeeded. ckr_arguments_bad pinitargs is null. pinitargs->libraryparameters is null. only some of the lock functions were provided by the application. ckr_cant_lock: the ckf_os_locking_ok fl...
NSC_InitToken
specifically, nsc_inittoken() initializes or clears the key database, removes the password, and then marks all the user certs in the certificate database as non-user certs. (user certs are the certificates that have their associated private keys in the key database.) note: the...
FIPS mode of operation
general-purpose functions fc_getfunctionlist fc_initialize fc_finalize fc_getinfo slot and token management functions fc_getslotlist fc_getslotinfo fc_gettokeninfo fc_waitforslotevent fc_getmechanismlist fc_getmechanisminfo fc_inittoken fc_initpin fc_setpin session management functions fc_opensession fc_closesession fc_closeallsessions fc_getsessioninfo fc_getoperationstate fc_setoperationstate fc_login fc_logout object management functions these functions manage certificates and keys. fc_createobject fc_copyobject fc_destroyobject fc_getobjectsize fc_getattributevalue fc_setattributevalue fc_findobjectsinit fc_findobjects fc_findobjectsfinal encryption functions these functions support triple des and aes in ecb and cbc modes. fc_encryptinit...
NSS environment variables
nss_allow_weak_signature_alg boolean (any non-empty value to enable) enables the use of md2 and md4 inside signatures. this was allowed by default before nss 3.12.3. 3.12.3 nss_debug_pkcs11_module string (module name) name the pkcs#11 module to be traced. pkcs #11 module logger 3.6 nss_default_db_type string ("dbm", "sql", or "extern") determines the default database type to open if the app does not specify. 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. nss_memory_allocation 3.4 nss_disable_unload string (any non-empty value) disable unloading of dynamically loaded nss ...
NSS tools : crlutil
es non-critical name-list where: subjaltnames: identifies the name of an extension should be set to 0 since this is non-critical extension name-list: comma separated list of names * add crl number extension: the crl number is a non-critical crl extension which conveys a monotonically increasing sequence number for a given crl scope and crl issuer. this extension allows users to easily determine when a particular crl supersedes another crl crlnumber non-critical number where: crlnumber: identifies the name of an extension critical: should be set to 0 since this is non-critical extension number: value of long which identifies the sequential number of a crl. * add revocation reason code extension: the reasoncode is a non-critical crl entry extension that identifies the reason for...
NSS tools : modutil
t password, try again... enter old password: enter new password: re-enter new password: token "communicator certificate db" password changed successfully. jar installation file format when a jar file is run by a server, by modutil, or by any program that does not interpret javascript, a special information file must be included to install the libraries. there are several things to keep in mind with this file: o it must be declared in the jar archive's manifest file. o the script can have any name. o the metainfo tag for this is pkcs11_install_script. to declare meta-information in the manifest file, put it in a file that is passed to signtool. sample script for example, the pkcs #11 installer script could be in the file pk11install. if so, the metainfo file for signtool inclu...
NSS tools : ssltab
. although you can run the tool at its most basic by issuing the ssltap command with no options other than hostname:port, the information you get in this way is not very useful. for example, assume your development machine is called intercept. the simplest way to use the debugging tool is to execute the following command from a command shell: $ ssltap www.netscape.com the program waits for an incoming connection on the default port 1924. in your browser window, enter the url http://intercept:1924. the browser retrieves the requested page from the server at www.netscape.com, but the page is intercepted and passed on to the browser by the debugging tool on intercept. on its way to the browser, the data is printed to the command shell from which you issued the command. data sent from the client ...
NSS tools : ssltap
. although you can run the tool at its most basic by issuing the ssltap command with no options other than hostname:port, the information you get in this way is not very useful. for example, assume your development machine is called intercept. the simplest way to use the debugging tool is to execute the following command from a command shell: $ ssltap www.netscape.com the program waits for an incoming connection on the default port 1924. in your browser window, enter the url http://intercept:1924. the browser retrieves the requested page from the server at www.netscape.com, but the page is intercepted and passed on to the browser by the debugging tool on intercept. on its way to the browser, the data is printed to the command shell from which you issued the command. data sent from the client ...
troubleshoot.html
tree with -p: cd mozilla cvs update -p building a 32-bit version on a 64-bit may fail with: /usr/include/features.h:324:26: fatal error: bits/predefs.h: no such file or directory in this case remember to set use_64=1 testing nss the ssl stress test opens 2,048 tcp connections in quick succession. kernel data structures may remain allocated for these connections for up to two minutes. some systems may not be configured to allow this many simultaneous connections by default; if the stress tests fail, try increasing the number of simultaneous sockets supported. building jss windows only: the shell invoked by gmake, shmsdos.exe, is likely to crash when invoking some java tools on windows. the current workaround is to use some other shell in place of shmsdos, such as sh...
Utility functions
3.2 and later sec_asn1encode mxr 3.2 and later sec_asn1encodeinteger mxr 3.2 and later sec_asn1encodeitem mxr 3.2 and later sec_asn1encoderabort mxr 3.9 and later sec_asn1encoderclearnotifyproc mxr 3.2 and later sec_asn1encoderclearstreaming mxr 3.2 and later sec_asn1encodercleartakefrombuf mxr 3.2 and later sec_asn1encoderfinish mxr 3.2 and later sec_asn1encodersetnotifyproc mxr 3.2 and later sec_asn1encodersetstreaming mxr 3.2 and later sec_asn1encodersettakefrombuf mxr 3.2 and lat...
NSS Tools certutil-tasks
errors provide no detail. mistakes with command-line options just print a usage message. improve certificate listings. allow for sorting by name and trust. sorting by trust will return ca certs first. allow listing and lookup of keys by index and nickname. improve coherence of key and certificate nicknames. remove keys "stranded" without a certificate (except for the imminent (????) encryption key for password files). support importing keys from a file. improve hardware token support. (bugfix) some certificate extensions cause certutil to crash. (bugfix) certificate entries require a serial number; one should be generated automatically if not provided. (bugfix) null password is given to new key3.db; should prompt user for an initial...
NSS Tools crlutil
re: subjaltnames: identifies the name of an extension should be set to 0 since this is non-critical extension name-list: comma separated list of names add crl number extension: the crl number is a non-critical crl extension which conveys a monotonically increasing sequence number for a given crl scope and crl issuer. this extension allows users to easily determine when a particular crl supersedes another crl crlnumber non-critical number where: crlnumber: identifies the name of an extension critical: should be set to 0 since this is non-critical extension number: value of long which identifies the sequential number of a crl. add revocation reason code extension: the reasoncode is a non-critical c...
NSS Tools dbck-tasks
the dbck tool should be able to update a databa ...
NSS tools : crlutil
Mozilla › Projects › NSS › tools › crlutil
me-list where: subjaltnames: identifies the name of an extension should be set to 0 since this is non-critical extension name-list: comma separated list of names * add crl number extension: the crl number is a non-critical crl extension which conveys a monotonically increasing sequence number for a given crl scope and crl issuer. this extension allows users to easily determine when a particular crl supersedes another crl crlnumber non-critical number where: crlnumber: identifies the name of an extension critical: should be set to 0 since this is non-critical extension number: value of long which identifies the sequential number of a crl. * add revocation reason code extension: the reasoncode is a non-critical crl entry extension that ident...
NSS tools : modutil
Mozilla › Projects › NSS › tools › modutil
ord, try again... enter old password: enter new password: re-enter new password: token "communicator certificate db" password changed successfully. jar installation file format when a jar file is run by a server, by modutil, or by any program that does not interpret javascript, a special information file must be included to install the libraries. there are several things to keep in mind with this file: o it must be declared in the jar archive's manifest file. o the script can have any name. o the metainfo tag for this is pkcs11_install_script. to declare meta-information in the manifest file, put it in a file that is passed to signtool. sample script for example, the pkcs #11 installer script could be in the file pk11install. if so,...
NSS tools : ssltap
Mozilla › Projects › NSS › tools › ssltap
run the tool at its most basic by issuing the ssltap command with no options other than hostname:port, the information you get in this way is not very useful. for example, assume your development machine is called intercept. the simplest way to use the debugging tool is to execute the following command from a command shell: $ ssltap www.netscape.com the program waits for an incoming connection on the default port 1924. in your browser window, enter the url http://intercept:1924. the browser retrieves the requested page from the server at www.netscape.com, but the page is intercepted and passed on to the browser by the debugging tool on intercept. on its way to the browser, the data is printed to the command shell from which you issued the command. data sent f...
NSS tools : vfyserv
Mozilla › Projects › NSS › tools › vfyserv
coming soon ...
Network Security Services
uction to network security services provides an overview of the nss libraries and what you need to know to use them. nss ssl public functions summarizes the ssl apis exported by the nss shared libraries. nss ssl reference api used to invoke ssl operations. nss api guidelines explains how the libraries and code are organized, and guidelines for developing code (naming conventions, error handling, thread safety, etc.) nss technical notes links to nss technical notes, which provide latest information about new nss features and supplementary documentation for advanced topics in programming with nss. tools, testing, and other technical details build instructions for nss describe how to check out and build nss releases. ...
Necko Architecture
tion. transports underlying i/o functionality has been consolidated into "transports." there is a transport for each type of i/o. necko implements a file transport and a socket transport that the protocol implementations (channels) use to actually move bytes to and from. how do i add my own protocol handler? adding your own protocol handler is a straightforward process in necko. there are a minimum of two interfaces you need to implement in order to fit into the necko architecture: nsiprotocolhandler, and nsichannel. recall, that the ioservice will look up your protocol handler and ask it for a channel. after registering your protocol handler necko will use it to create channels for any uris it encounters that have the scheme your protocol handler registered for. please use existing pro...
Necko FAQ
that's all! any resemblance in flavor to the necco candy is purely coincidental. what do i need to build this library? see the code section on the main page. currently you'd need to get the mozilla tree and at least build nspr, and xpcom. ...
Pork Tool Development
o an string offset. this can be translated to an unboxedloc, which has a line and column offset (see renamer.cc:65). macro expansion this section refers to macro expansion when using mcpp (see installing pork). for the rename_class.cpp test, generate the file with "gcc -e -wp,-w0,-k rename_class.cpp > rename_class.cc" and run the renamer with "../renamer -rename foo bar rename_class.cc". for terminology, suppose "my_foo" --> "foo". then any post-location variables refer to "foo" and pre-location variables refer to "my_foo". cppsourceloc wraps sourceloc, providing information about macro expansion. cppsourceloc will change the previously provided location information (in variable cpp_source_loc._loc) from post-location to pre-location. all values from the ast refer to the post-location. not...
Pork Tools
} caller1 { // case 1 // figure out that rv was only used for the rewritten // outparam call + ns_ensure_success. then nuke the declaration // nsresult rv; // move outparam to lhs var = getter(); // detect ns_ensure_success immediately following // and change it to an equivalent ns_ensure_true ns_ensure_true(var, ns_error_failure); // case 2 var = getter(); // case 3, eliminate rv2 decl given that it's not used elsewhere var = getter(); ns_ensure_true(var, ns_error_failure) } outparamdel also support rewriting getters such that they return already_addrefed<nsifoo>. in this case all of the callsites are modified to: a) getter_addrefs case: getter(getter_addrefs(foo)) -> foo = getter() b) all other cases: getter(&foo) -> foo = getter().get() ...
Pork
he pork functionality into its standard distribution; look for files and tests having the prefix "xform". documentation installing pork download, installation and dependency info for pork pork tools description of rewriting tools pork tool development in progress page... old pork page pork details that haven't been moved to mdc renaming with pork sample pork application todos pork 1.0 release tracking bug pork releases download pork here community view pork forums... mailing list newsgroup rss feed #static on irc.mozilla.org related topics dehydra, treehydra, mozilla 2, spidermonkey ...
Rhino documentation
cripts. javascript debugger debugging scripts running in rhino. javascript compiler compiling scripts into java class files. running the rhino tests running the javascript test suite with rhino. embedding rhino embedding tutorial a short tutorial on how to embed rhino into your application. api javadoc reference (link broken? try this at jarvana.) an annotated outline of the programming interface to rhino (tip only). scopes and contexts describes how to use scopes and contexts for the best performance and flexibility, with an eye toward multithreaded environments. serialization how to serialize javascript objects and functions in rhino. runtime a brief description of the javascript runtime. small footprint hints for those interested in small-footprint embeddings. examp...
Tutorial: Embedding Rhino
ces. for the counter example, no initialization work is needed, so the implementation is empty. public counter () { } the method jsconstructor defines the javascript constructor that was called with the expression new counter(7) in the javascript code above. public void jsconstructor(int a) { count = a; } class name the class name is defined by the getclassname method. this is used to determine the name of the constructor. public string getclassname() { return "counter"; } dynamic properties dynamic properties are defined by methods beginning with jsget_ or jsset_. the method jsget_count defines thecount property. public int jsget_count() { return count++; } the expression c.count in the javascript code above results in a call to this method. defining javascript "methods" meth...
Rhino Examples
pfactory that can be used to control the wrapping behavior of the rhino engine on calls to java methods. multithreaded script execution dynamicscopes.java is a program that creates a single global scope object and then shares it across multiple threads. sharing the global scope allows both information to be shared across threads, and amortizes the cost of context.initstandardobjects by only performing that expensive operation once. implementing host objects first check out the tutorial if you haven't already. the foo class - extending scriptableobject foo.java is a simple javascript host object that includes a property with an associated action and a variable argument method. the matrix class - implementing scriptable matrix.java provides a simple multidimensional array by implementing the sc...
Small Footprint
tion debug information in rhino classes consumes about 25% of code size and if you can live without that, you can recompile rhino to remove it. smalljs.jar ant build script in rhino supports smalljar target that will generate smalljs.jar that does not include tools, optimizer, javaadapter and class generation library, regular expressions, e4x implementataion and deprecated files. to build such minimalist jar without debug information, run the following command from the top directory of rhino distribution: ant clean ant -ddebug=off -dno-regexp=true -dno-e4x=true smalljar if you omit -dno-regexp=true, then the resulting smalljs.jar will include regular expression support. similarly omitting -dno-e4x=true results in smalljs.jar that includes runtime support for e4x. ...
Rhino JavaScript compiler
. note that the top-level functions available to the shell (such as print) are not available to compiled scripts when they are run outside the shell. compiler command line java org.mozilla.javascript.tools.jsc.main [options] file1.js [file2.js...] where options are: -extends java-class-name specifies that a java class extending the java class java-class-name should be generated from the incoming javascript source file. each global function in the source file is made a method of the generated class, overriding any methods in the base class by the same name. -implements java-intf-name specifies that a java class implementing the java interface java-intf-name should be generated from the incoming javascript source file. each global function in the source file is made a method of the gene...
Performance Hints
for example, you could rewrite function sum(a) { result = 0; for (i=0; i < a.length; i++) result += a[i]; return result; } as function sum(a) { var result = 0; for (var i=0; i < a.length; i++) result += a[i]; return result; } this is not equivalent code because the second version does not modify global variables result and i. ...
Rhino shell
invoking the shell java org.mozilla.javascript.tools.shell.main [options] script-filename-or-url [script-arguments] where options are: -e script-source executes script-source as a javascript script. -f script-filename-or-url reads script-filename-or-url content and execute it as a javascript script. -opt optlevel / -o optlevel optimizes at level optlevel, which must be -1 or an integer between 0 and 9. see rhino optimization for more details. -version versionnumber specifies the language version to compile with. ...
Creating JavaScript tests
1, v2[, message]) check that v1 and v2 are the same value. if they're not, throw an exception (which will cause the test to fail). if you are writing a jstests, additional testing functionality is provided for you in shell.js files. you can read about them here. performance testing and general advice do not attempt to test the performance of engine features in the test suite. please keep in mind that the javascript test suite is run on a wide variety of wildly varying hardware plaforms, from phones all the way up to servers. even tests that check for polynomial time complexity will start to fail in a few years when they have sped up enough to run faster than the granularity of the os scheduler or when run on platforms with higher latencies than your development workstation. these tests ...
FOSS
y, bytestring, cgi, posix signals, ffi, and more. ...
Exact Stack Rooting
e next js-api call. js::nullptr null (or nullptr) does not implicitly convert to a js::handlet. for places where you want to pass a null value into a function taking a js::handlet, you can construct and pass a new nullptr instance. you are free to use these as temporaries. rootedobject obj(cx, js_newobject(cx, clasp, nullptr(), nullptr()); common pitfalls the c++ type system allows us to eliminate the possibility of most common errors; however, there are still a few things that you can get wrong that the compiler cannot help you with. there is basically never a good reason to do any of these. if you think you do need to do one of these, ask on one of spidermonkey's support forums: maybe we've already solved your problem using a different mechanism. storing a js::rootedt on the heap. ...
Invariants
f an object is inextensible, its dslots will never again change. (we don't bother locking when accessing slots of a sealed object. the locking is going away regardless.) compartments suppose obj = js_getscopechain(cx) is not null. then cx->compartment == obj->compartment(). when a new object is created, it is automatically created in cx->compartment, but its parent and prototype are often determined by examining the scope chain. the object and its proto and parent must be in the same compartment. so it is utterly crucially important that this invariant always be true if objects are being created. the public api for compartment-hopping, jsautoentercompartment, and the internal api, js::autocompartment, both make sure the invariant is maintained. however, there is another internal api, js::...
Self-hosted builtins in SpiderMonkey
you have to use callfunction(fun, receiver, arg1, ... argn). this restriction was added because otherwise it's extremely easy to accidentally call methods that have been changed by content, changing the behavior from what was expected. if the fun can potentially be a content-provided function, callcontentfunction has to be used. this is to prevent accidentally calling content functions when assuming that content can't interfere with behavior. e.g., if receiver is an object that content has access to, then callfunction(receiver.fun, receiver) wouldn't be guaranteed to work, because content might have changed the value of receiver.fun, so callcontentfunction(receiver.fun, receiver) has to be used. self-hosted functions by default are not constructors and do not have a prototype property, so ...
Introduction to the JavaScript shell
m. pc2line(function, [pc]) returns the line number of the javascript code that corresponds to the first line of the specified function. if you specify a program counter offset into the function, the line number of the line of code containing that offset is returned. print([expression ...]) evaluates the expression(s) and displays the result(s) on stdout, separated by spaces (" ") and terminated by a newline ("\n"). putstr(expression) evaluates the expression and displays the result on stdout. quit([status]) exits the shell. status defaults to 0 if omitted. read(filename[, type]) reads and returns the contents of file. if type is "binary" returns an uint8array, otherwise returns an utf-8 decoded string. readline() reads a single line of input from stdin, returning it to the c...
INT_FITS_IN_JSVAL
obsolete since javascript 1.8.5this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. determines if a specified c integer is safe to pass to int_to_jsval. syntax #define int_fits_in_jsval(i) /* ... */ name type description i jsint the c integer value to check. description determines if a specified c integer value, i, lies within the range allowed for integer jsvals. if so, int_fits_in_jsval returns true, and i can be cast to jsval by calling int_to_jsval(i). otherwise, int_fits_in_jsval returns false. in this case, the application can still convert i to a jsval using js_newnumbervalue. warning: the type of the argument i must be jsint, but the ...
JS::AutoVectorRooter
bool append(const t &v) appends an element v to the array. ...
JS::CurrentGlobalOrNull
t on this jscontext. description js::currentglobalornull() returns the global object for whatever function is currently running on the context. in other words, it returns the global object on the current scope chain. if there is no javascript running on the context, this returns the context's global, i.e., js_getglobalobject(cx). note that js_getglobalobject() and context globals are becoming obsolete. see also mxr id search for js::currentglobalornull js_getglobalforobject bug 899245 ...
JS::DeflateStringToUTF8Buffer
the pointer to receive the number of unicode characters written to the buffer. description js::deflatestringtoutf8buffer encodes src as utf8. the caller must either ensure dst has enough space to encode the entire string, or pass the length of the buffer as dstlenp. in which case, the function will encode characters from the string until the buffer is exhausted. does not write the null terminator. if dstlenp is provided, it will be updated to hold the number of bytes written to the buffer. if numcharsp is provided, it will be updated to hold the number of unicode characters written to the buffer. this can be less than the length of the string, if the buffer is exhausted before the string is fully encoded. examples char16_t uchars[] = { 0xd83e, 0xdd8a, 0 }; js::rootedstring str(cx,...
JS::Evaluate
ytes are the string containing the text of the script. length indicates the size of the text version of the script in characters. filename is the name of the file (or url) containing the script. this information is used in messages if an error occurs during compilation. rval is an optional out parameter. if it is non-null, then on success, the result value is stored in *rval. this value is determined the same way as for the standard eval function. in the common case where the script is just an expression, the result value is simply the value of that expression. more generally, the result value is the value of the last-executed expression statement in the script that isn't in a function. if a script compiles and executes successfully, js::evaluate stores the result in *rval, if non-null, an...
JS::GetDeflatedUTF8StringLength
ffer required to encode given string as utf8. syntax size_t getdeflatedutf8stringlength(jsflatstring* s); name type description s jsflatstring * the pointer to the string to calculate the length. description js::getdeflatedutf8stringlength returns the length of the char buffer required to encode s as utf8. the returned length does not include the null-terminator. see also js::deflatestringtoutf8buffer bug 1034627 ...
JS::PropertySpecNameEqualsId
this article covers features introduced in spidermonkey 38 determine if the given jspropertyspec::name or jsfunctionspec::name value equals the given jsid. syntax bool js::propertyspecnameequalsid(const char *name, js::handleid id); name type description name const char * jspropertyspec::name or jsfunctionspec::name. id js::handleid a jsid to compare with. description js::propertyspecnameequalsid determines if the given jspropertyspec::name or jsfunctionspec::name value equals the given jsid, and returns true if so. see also mxr id search for js::propertyspecnameequalsid js::propertyspecnameissymbol js::propertyspecnametopermanentid jspropertyspec jsfunctionspec bug 1082672 ...
JS::PropertySpecNameIsSymbol
this article covers features introduced in spidermonkey 38 determine if the given jspropertyspec::name or jsfunctionspec::name value is actually a symbol code and not a string. syntax bool js::propertyspecnameissymbol(const char *name); name type description name const char * the pointer of the name, actually the uintptr_t type, and not a pointer to any string. description js::propertyspecnameissymbol determines if the given jspropertyspec::name or jsfunctionspec::name value is actually a symbol code and not a string, and returns true if so. see also mxr id search for js::propertyspecnameissymbol js::propertyspecnameequalsid js::propertyspecnametopermanentid jspropertyspec jsfunctionspec bug 1082672 ...
JSCheckAccessOp
her obj[id] may be accessed per mode, returning js_false on error/exception, js_true on success with obj[id]'s stored value in *vp. as for jspropertyop, id is either a string or an int jsval. 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. the nature of principals and the security policy are entirely up to the application. if a class leaves the checkaccess field null, a runtime-wide object access callback is called instead; see js_setcheckobjectaccesscallback. jsclass hooks jsclass offers the following hook: the jsclass.checkaccess callback is called...
JSClass.flags
lates_undefined added in spidermonkey 24 causes objects which have this class to emulate undefined in certain circumstances. an object obj that emulates undefined behaves like any other object, except in the following ways: typeof obj === "undefined" obj converts to false when obj is converted to a boolean when used in boolean contexts (if conditions, loop continuation/termination conditions [for/while/do { } while], the condition in a ternary ?: expression, and so on) (obj == undefined) is true, and (obj != undefined) is false (obj == null) is true, and (obj != null) is false == and != comparisons to values other than null or undefined (including to an object that emulates undefined) are unaffected by this flag. strict equality (=== and !==) comp...
JSErrorReport
nts. to counter this attack, html5 specifies that script errors should be sanitized ("muted") when the script is not same-origin with the global for which it is loaded. callers should set this flag for cross-origin scripts, and it will be propagated appropriately to child scripts and passed back in jserrorreports. linebuf const char * text of the line that caused the error, minus the trailing newline character. tokenptr const char * pointer to the error token in *linebuf. uclinebuf const char16_t * unicode line buffer. this is the buffer that contains the original data. uctokenptr const char16_t * pointer to the error token in *uclinebuf. flags unsigned the logical or of zero or more of the following flags...
JSFUN_BOUND_METHOD
syntax jsfun_bound_method description this macro exists only for backward compatibility with existing applications. its use is deprecated. ...
JSNative
ts, and the eventual return value. on success, the callback must set js::callargs::rval() or call js_set_rval (at least once) and return true. 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. (returning false without reporting an error or raising an exception terminates the script with an uncatchable error. this has limited use cases; it's used to implement firefox's "slow script" dialog, for example.) when a jsnative is called, no jsstackframe is generated. this causes the function not to appear on the stack in javascript debuggers. it also means that applications that implement jscheckaccessop or jscheckaccessidop in terms of apis such as js_frameiterato...
JSPrincipals
pals if they are no longer in use. obsolete since jsapi 13 methods name description void dump() this is not defined by the js engine but should be provided by the embedding. added in spidermonkey 17 description jsprincipals is the abstract base class of all principals objects, the objects that identify the source of a function or script and are used to determine its privileges. a principals object is like a java codesource. jsprincipals could be passed into the js engine through the js_newglobalobject function. jsprincipals has refcount property that is the reference count. this is used for memory management. each time an object is referenced, refcount must be increased by one. each time an object is dereferenced, refcount must be decremented by one. ...
JSVAL_IS_BOOLEAN
obsolete since jsapi 32this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. determines if a given jsval is a javascript boolean. syntax jsval_is_boolean(v) description jsval_is_boolean(v) is true if the given javascript value, v, is a boolean value (that is, it is either jsval_true or jsval_false). to convert between javascript boolean values (jsval) and c boolean values, use jsval_to_boolean and boolean_to_jsval. see also bug 952650 ...
JSVAL_IS_DOUBLE
syntax jsval_is_double(v) description jsval_is_double(v) is true if v is a number represented in memory as a jsdouble. to check whether v is a number, regardless of implementation details, use jsval_is_number instead. ...
JSVAL_IS_INT
syntax jsval_is_int(v) description jsval_is_int(v) is true if the jsval v is a number represented in memory as an integer. to test whether a value is a number, regardless of how it is represented in memory, use jsval_is_number instead. to convert between c integer types and jsval, use jsval_to_int, int_fits_in_jsval, and int_to_jsval. ...
JSVAL_IS_NULL
syntax jsval_is_null(v) description jsval_is_null(v) is true if v is jsval_null, which is the javascript null value. (note: jsval_is_object(jsval_null) is also true.) example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it contains a null value. if (jsval_is_null(myitem)) { ... ...
JSVAL_IS_NUMBER
syntax jsval_is_number(v) description jsval_is_number(v) is true if v is a javascript number. to convert a numeric jsval to a c floating-point number, use js_valuetonumber. ...
JSVAL_IS_OBJECT
syntax jsbool jsval_is_object(jsval v); description jsval_is_object(v) returns true if v is either an object or jsval_null. this indicates that it is safe to call jsval_to_object(v) to convert v to type jsobject *. ...
JSVAL_IS_PRIMITIVE
obsolete since jsapi 32this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. determine if a given jsval is of a primitive type. syntax jsval_is_primitive(v) description jsval_is_primitive(v) is true if v is undefined, null, a boolean, a number, or a string. otherwise it is false, and v is an object. see also bug 952650 ...
JSVAL_IS_STRING
syntax jsval_is_string(v) description jsval_is_string(v) is true if v is a string. to access the content of a string jsval, use jsval_to_string, js_getstringchars, and js_getstringlength. ...
JSVAL_IS_VOID
syntax jsval_is_void(v) description jsval_is_void(v) is true if v is jsval_void, which represents the javascript value undefined. ...
JSVAL_LOCK
. locks a js value to prevent garbage collection on it. syntax jsval_lock(cx,v) description jsval_lock is a deprecated feature that is supported only for backward compatibility with existing applications. to lock a value, use local roots with js_addroot. jsval_lock locks a js value, v, to prevent the value from being garbage collected. v is a js object, string, or double value. jsval_lock determines if v is an object, string, or double value, and if it is, it locks the value. if locking is successful, or v already cannot be garbage collected because it is not an object, string, or double value, jsval_lock evaluates to true. otherwise, it evaluates to false. see also jsval_is_gcthing jsval_to_gcthing jsval_unlock js_addroot js_lockgcthing bug 787580 ...
JSVAL_UNLOCK
value, enabling garbage collection on it. syntax jsval_unlock(cx,v) description jsval_unlock is a deprecated feature that is supported only for backward compatibility with existing applications. to unlock a value, use local roots with js_removeroot. jsval_unlock unlocks a previously locked js value, v, so it can be garbage collected. v is a js object, string, or double value. jsval_unlock determines if v is an object, string, or double value, and if it is, it unlocks the value. if unlocking is successful, or v not affected by garbage collection because it is not an object, string, or double value, jsval_unlock evaluates to true. otherwise, it evaluates to false. see also jsval_is_gcthing jsval_to_gcthing jsval_lock js_addroot js_lockgcthing bug 787580 ...
JS_ASSERT_STRING_IS_FLAT
this article covers features introduced in spidermonkey 1.8.5 assert a string is flattened. syntax static moz_always_inline jsflatstring * js_assert_string_is_flat(jsstring *str) { moz_assert(js_stringisflat(str)); return (jsflatstring *)str; } name type description str jsstring * string to examine. description js_assert_string_is_flat asserts the string is flattened, and returns a pointer to jsflatstring. see also mxr id search for js_assert_string_is_flat js_stringisflat bug 609440 ...
JS_BufferIsCompilableUnit
syntax bool js_bufferiscompilableunit(jscontext *cx, js::handle<jsobject*> obj, const char *utf8, size_t length); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject the global object, or null. utf8 const char * string containing the script to compile. length size_t the length of utf8 in characters. description given a buffer, return false if the buffer might become a valid javascript statement with the addition of more lines. ...
JS_CheckAccess
ed. id jsid the name or index of the property being accessed. mode jsaccessmode the type of access requested (read, write, etc.) vp jsval * out parameter. on success, *vp receives the property's stored value. attrsp unsigned int * out parameter. on success, *attrsp receives the property attributes. description js_checkaccess determines whether the property of obj given by id can be accessed by the code currently running in the context cx. the mode parameter specifies what kind of access to check for. it is one of the following values: value description jsacc_proto check for permission to read to obj's prototype. (this is redundant with passing the string id "__proto__" as id.) jsacc_parent ...
JS_ClearContextThread
at no thread was previously associated with the context. js_clearcontextthread relinquishes the calling thread's right to use cx. it returns the thread id of the last thread to be associated with this context. (this is always the current thread id when the function is used properly.) js_newcontext automatically associates the new context with the calling thread. use js_getcontextthread to determine whether a context is associated with a thread. js_setcontextthread and js_clearcontextthread are available only in js_threadsafe builds. mxr id search for js_setcontextthread mxr id search for js_clearcontextthread ...
JS_ConvertArgumentsVA
argv jsval * pointer to the vector of arguments to convert. obsolete since jsapi 30 format const char * character array containing the recognized format to which to convert. ap va_list the list of pointers into which to store the converted types. there should be one pointer for each converted value. the type va_list is a standard feature of the c programming language. it is defined in <stdarg.h>. description js_convertargumentsva is to js_convertarguments as vprintf is to printf. see js_convertarguments for further information. if js_convertargumentsva successfully converts all arguments, it returns true. otherwise it returns false. see also mxr id search for js_convertargumentsva js_convertarguments bug 969798 - added args bug 11257...
JS_DefaultValue
] hook. ecmascript specifies that all objects have a [[defaultvalue]] hook. objects with classes defined by ecmascript itself all use the [[defaultvalue]] algorithm specified in §8.12.8 (but note the algorithm's special case for date objects). objects with a custom jsclass specified by the embedder will invoke that class's convert hook, which must convert the object to a primitive value, to determine the primitive result of conversion. behavior when the convert hook is js_convertstub is identical to that for objects defined by ecmascript. on success, js_defaultvalue stores the converted value in *vp and returns true. on error or exception, it returns false, and the value left in *vp is undefined. see also mxr id search for js_defaultvalue js::toprimitive bug 1054756 - renamed to js::t...
JS_DefineFunctions
ns prior to spidermonkey 24, fs was not const. name type description cx jscontext * the context in which to define functions. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handle&lt;jsobject*&gt; the object on which functions are to be defined. fs const jsfunctionspec * a null-terminated array of function specifications. each element of the array defines an individual function. behavior propertydefinitionbehavior see below. added in spidermonkey 38 enum propertydefinitionbehavior { defineallproperties, onlydefinelateproperties, dontdefinelateproperties }; name description defineallproperties define all properties reg...
JS_DeleteProperty
uires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject object from which to delete a property. name or id const char * or jsid or const char16_t * name of the property to delete. namelen size_t (only in js_deleteucproperty) the length of name in characters; or -1 to indicate that name is null-terminated. result js::objectopresult &amp; (out parameter) receives the result of the operation. description js_deleteproperty removes a specified property, name, from an object, obj. js_deletepropertybyid is the same but takes a jsid for the property name. these functions are identical to js_deleteproperty2 and js_deletepropertybyid2 except that they do not have an out paramete...
JS_DeleteProperty2
equest. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject object from which to delete a property. name or id const char * or const char16_t or js::handleid name of the property to delete. namelen size_t (only in js_deleteucproperty2) the length of name in characters; or -1 to indicate that name is null-terminated. succeeded bool * out parameter. on success, *succeeded receives false if the property was not deleted because it is permanent and true otherwise. description js_deleteproperty2 removes a specified property, name, from an object, obj, and stores true or false in *succeeded. it behaves like the javascript expression delete obj[name]. js_deleteucproperty2 is the unicode v...
JS_DumpHeap
ject graph leading to the specified thing. maxdepth size_t the upper bound on the number of edges to descend from the graph roots. thingtoignore void * null or a pointer to a gc thing that will be ignored during graph traversal. enum jsgctracekind { // these trace kinds have a publicly exposed, although opaque, c++ type. // note: the order here is determined by our value packing. other users // should sort alphabetically, for consistency. jstrace_object = 0x00, jstrace_string = 0x01, jstrace_symbol = 0x02, jstrace_script = 0x03, // shape details are exposed through js_traceshapecyclecollectorchildren. jstrace_shape = 0x04, // the kind associated with a nullptr. jstrace_null = 0x06, // a kind that ind...
JS_EncodeString
ify it and is responsible for freeing it. note that for non-ascii strings, if js_cstringsareutf8 is false, these functions can return a corrupted copy of the contents of the string. use js_getstringchars to access the 16-bit characters of a javascript string without conversions or copying. on success, js_encodestring and js_encodestringtoutf8 return a pointer to the char array, which is null-terminated. on failure, js_encodestring and js_encodestringtoutf8 return null see also mxr id search for js_encodestring mxr id search for js_encodestringtoutf8 js_encodestringtobuffer bug 397215 - added js_encodestring bug 835719 - added js_encodestringtobuffer ...
JS_EnterLocalRootScope
withresult must be called once for every prior successful call to js_enterlocalrootscope. if js_enterlocalrootscope fails, you must not make the matching js_leavelocalrootscope call. local root scopes do not cover objects that are the result of jsapi calls like js_getproperty or js_callfunction. to remove a gc thing from a local root scope (perhaps to save memory), use js_forgetlocalroot. to determine if a jsval points to a gc thing, use jsval_is_gcthing. see also bug 519949 bug 803907 ...
JS_EnumerateDiagnosticMemoryRegions
see also mxr id search for js_enumeratediagnosticmemoryregions mxr id search for jsenumeratediagnosticmemorycallback bug 662646 ...
JS_EvaluateScript
characters. filename is the name of the file (or url) containing the script. this information is used in messages if an error occurs during compilation. similarly, lineno is used to report the line number of the script or file where an error occurred during compilation. rval is an optional out parameter. if it is non-null, then on success, the result value is stored in *rval. this value is determined the same way as for the standard eval function. in the common case where the script is just an expression, the result value is simply the value of that expression. more generally, the result value is the value of the last-executed expression statement in the script that isn't in a function. if a script compiles and executes successfully, js_evaluatescript or js_evaluateucscript stores the resu...
JS_GC
tion. obsolete since jsapi 50 description js_gc performs garbage collection of js objects, strings and other internal data structures that are no longer reachable in the specified context or runtime. garbage collection frees memory so that it can be reused by the system. when your scripts create many objects, you may want to call js_gc directly in your code, particularly when a script terminates or when the application has idle time. to perform garbage collection only if needed, call js_maybegc instead. use js_setgccallback to add hooks that are called during garbage collection. see also mxr id search for js_gc js_maybegc bug 737364 -- changed to jsruntime bug 1283855 -- changed to jscontext ...
JS_GetArrayLength
y object. syntax bool js_getarraylength(jscontext *cx, js::handle<jsobject*> obj, uint32_t *lengthp); name type description cx jscontext * the context in which to look up the array's length. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handle&lt;jsobject*&gt; the object to examine. lengthp uint32_t * out parameter. on success, *lengthp receives the length of the array. description js_getarraylength gets the .length property of obj as though by calling js_getproperty and converts it to a 32-bit unsigned integer. if obj is an array (see js_isarrayobject), this is guaranteed to succeed, because the .length property of an array is always a number and can'...
JS_GetContextThread
obsolete since jsapi 8this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. returns the id of the associated thread for a context. syntax int js_getcontextthread(jscontext *cx); name type description cx jscontext * the context to examine. description js_getcontextthread returns the id of the thread currently associated with this context. if the context is not currently associated with any thread, the return value is 0. see js_setcontextthread. js_getcontextthread is available only if the engine is built with js_threadsafe. mxr id search for js_getcontextthread ...
JS_GetElement
a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject the object to search for the element. index uint32_t index of the element to look up. vp js::mutablehandlevalue out parameter. on success, *vp receives the current value of the element, if it exists, and undefined otherwise. description js_getelement examines a specified js object, obj, and its prototype chain, for an element or numeric property numbered index. if the element exists, js_getelement sets *vp to the element's current value. if not, it sets *vp to undefined and returns true (to indicate no error occurred). if the search fails with an error or exception, js_getelement returns false, and the value left in *vp is undefined. see also mxr i...
JS_GetExternalStringClosure
t from which to retrieve the closure for a string. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. str jsstring * the string for which to return the closure. the result is null if the external string was created without one (that is, by calling js_newexternalstring rather than js_newexternalstringwithclosure). description to determine if a string was created as an external string, you can call js_isexternalstring. see also bug 724810 ...
JS_GetFunctionFlags
obsolete since jsapi 19this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. retrieve the function flags of a given javascript function. syntax unsigned int js_getfunctionflags(jsfunction *fun); name type description fun jsfunction * the function to examine. description js_getfunctionflags retrieves the function flags of a given javascript function, fun. these flags are for the javascript engine’s internal use. most applications can’t do anything useful with them. function flags are a value of type unsigned int, the bitwise or of zero or more of the jsfun flags described below. once a function is created, its flags cannot be modified. js...
JS_GetGlobalForScopeChain
st on this jscontext. description js_getglobalforscopechain() returns the global object for whatever function is currently running on the context. in other words, it returns the global object on the current scope chain. if there is no javascript running on the context, this returns the context's global, i.e., js_getglobalobject(cx). note that js_getglobalobject() and context globals are becoming obsolete. see also js_getglobalforobject js::currentglobalornull bug 899245 ...
JS_GetGlobalObject
ntext *, cx. this returns null if cx has no global object. spidermonkey supports applications that have multiple global objects, such as the various window objects in a web browser. the object returned by js_getglobalobject is not necessarily the same thing as the global object seen by any javascript code that runs in cx! if a function is executing, the global object used by that function is determined when the function is created. furthermore, some jsapi functions, such as js_executescript, allow the caller to specify a global object in which the script executes. in either case, the global function used by the function or script may differ from the context's global object. the context's global object field serves two purposes. first, it is a convenient place for the application to stash the ...
JS_GetInstancePrivate
rgv jsval * optional argument vector, used for error reporting. obsolete since jsapi 32 this must be one of the following: an argv pointer created by the javascript engine and passed to a jsnative callback; js_argv(cx, vp) where vp is a pointer created by the engine and passed to a jsfastnative callback; or null. description js_getinstanceprivate determines if a javascript object, obj, is an instance of a given jsclass, clasp, and if it is, returns a pointer to the object's private data. otherwise it returns null. note that if obj is an instance of clasp, but there is no private data currently associated with the object, or the object cannot have private data, js_getinstanceprivate also returns null. if you pass a non-null argument vector, argv, t...
JS_GetParent
bject or js_constructobject. an application can also use js_setparent, but see the caveats on that page. an object's parent serves two purposes in spidermonkey: for some functions, it is used to implement lexical scoping (but this is an implementation detail). applications that use spidermonkey's custom security features can use the parent during security checks, as a convenient way to determine the security domain of an object being accessed. the typical rule is that every object is in the same security domain as its parent. (but each application can define its own security rules. see the security section of the user guide for an introduction to the security model.) in some cases, javascript code can get an object's parent via the read-only obj.__parent__ property. but if an object's...
JS_GetProperty
request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject object to search on for the property. name or id const char * or const char16_t * or js::handleid name of the property to look up. namelen size_t (in js_getucproperty only) the length of name, in characters; or -1 to indicate that name is null-terminated. vp js::mutablehandlevalue out parameter. on success, *vp receives the current value of the property, or undefined if no such property is found. description js_getproperty examines a specified js object obj and its prototype chain for a property with the specified name. it behaves like the javascript expression obj[name]. js_getucproperty is the unicode version of the f...
JS_GetPropertyAttributes
eadsafe build, the caller must be in a request on this jscontext. obj jsobject * the object that has the property to be queried. name const char * or const jschar * name of the property from which to retrieve attributes. namelen size_t (only in js_getucpropertyattributes) the length of name in characters; or (size_t) -1 to indicate that name is null-terminated. attrsp unsigned int * out parameter. if the specified property is found on obj, *attrsp receives its attributes. foundp jsbool * out parameter. if no error occurs, *foundp receives js_true if the specified property is found and js_false if it is not found. if an error occurs, the value left in *foundp is unspecified. description js_getpropertyattributes ...
JS_GetPropertyAttrsGetterAndSetter
1.8.1 name type description cx jscontext * the context in which to perform the property lookup. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * object from which to retrieve property attributes. name or id const char * or const jschar * or jsid the name of the property to examine. namelen size_t (only in js_getucpropertyattrsgetterandsetter) the length of name in characters; or (size_t) -1 to indicate that name is null-terminated. attrsp unsigned int * out parameter. pointer to the storage area into which to place retrieves attributes. foundp jsbool * out parameter. flag indicating whether or not the specified property was loc...
JS_GetPropertyDefault
to search on for the property. name or id const char * or js::handleid name of the property to look up. def js::handlevalue default value if the property is not found. vp js::mutablehandlevalue out parameter. on success, *vp receives the current value of the property, or undefined if no such property is found. description js_getpropertydefault examines a specified js object obj and its prototype chain for a property with the specified name. on success, these functions set *vp to the current value of the property, or def if obj has no such property, and return true. on an error or exception, these functions return false, and the value left in *vp is undefined. see also bug 905774 ...
JS_GetStringBytes
rieve bytes from. description js_getstringbytes and js_getstringbytesz convert the specified javascript string, str, to a c string (an array of 8-bit chars). if js_cstringsareutf8 is true, then the returned string is utf-8, and the conversion is lossless. otherwise the high byte is simply dropped from each jschar. on success, the return value is a pointer to the char array, which is null-terminated. on failure, js_getstringbytes returns a pointer to a null-terminated empty string; js_getstringbytesz returns null. note: js_getstringbytes() and js_getstringbytesz() have both been removed as of javascript 1.8.5 (firefox 4). instead, you should use js_encodestring, js_getstringencodinglength, js_encodestringtobuffer. the array returned by js_getstringbytes or js_getstringbytesz is automat...
JS_GetStringLength
description js_getstringlength reports the length, in 16-bit code units, of the string str. this is the same as the length property of the string. this is the same as the length of the array returned by js_getstringchars, in char16_ts (not bytes). ...
JS_HasElement
determine whether a javascript array has an element in the specified index. syntax bool js_haselement(jscontext *cx, js::handleobject obj, uint32_t index, bool *foundp); name type description cx jscontext * the context in which to perform the property lookup. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject the object to search for the element. index uint32_t index of the element to look up. foundp bool * out parameter. on success, it stores true to *foundp, false otherwise. description js_haselement examines a specified js object, obj, and its prototype chain, for an element or numeric property numbered index. if the element exists, js_...
JS_HasInstance
hich to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handle&lt;jsobject*&gt; constructor/prototype to test. v js::handle&lt;js::value&gt; the value to test. bp bool * out parameter. on success, *bp receives the result of the test. description js_hasinstance determines if a specified js value, v, is an instance of js object, obj. this function is equivalent to v instanceof obj test in javascript. on success, js_hasinstance stores the result of the instanceof test in *bp and returns true. on error or exception, it returns false, and the value left in *bp is undefined. when providing a prototype as obj, the prototype's jsclass must have its hasinstance method ...
JS_HasOwnProperty
syntax bool js_hasownproperty(jscontext* cx, handleobject obj, const char* name, bool* foundp) bool js_hasownpropertybyid(jscontext* cx, handleobject obj, handleid id, bool* foundp) name type description cx jscontext * a context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject object to search on for the property. name or id const char * or js::handleid name of the property to look up. ...
JS_InternString
*cx, const char16_t *s, size_t length); name type description cx jscontext * a context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. s const char * or const char16_t * pointer to a character array containing the data for the string. in js_internstring and js_internucstring, the string must be null-terminated. length size_t (only in js_internstringn and js_internucstringn) the length of s in characters. description js_internstring and js_internstringn return an interned javascript string with a specified value, s. js_internucstring and js_internucstringn are the unicode versions of the function. each jsruntime keeps a table of all existing interned strings. if an interned stri...
JS_IsArrayObject
determine if a specified object is an array. syntax bool js_isarrayobject(jscontext *cx, js::handlevalue value, bool *isarray); bool js_isarrayobject(jscontext *cx, js::handleobject obj, bool *isarray); // obsolete since jsapi 44 bool js_isarrayobject(jscontext *cx, js::handlevalue value); bool js_isarrayobject(jscontext *cx, js::handleobject obj); name type description cx jscontext * a context. value js::handlevalue the value to examine. obj js::handleobject the object to examine. isarray bool whether the value/object is an array. description js_isarrayobject determines if a specified object, obj or value, is an array object. on success, returns true and sets isarray indicating whether obj is an ar...
JS_IsAssigning
obsolete since javascript 1.8.5this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. determine whether script is executing assignment operation. syntax jsbool js_isassigning(jscontext *cx); name type description description js_isassigning returns true if a script is executing and its current bytecode is a set (assignment) operation, even if there are native (no script) stack frames between the script and the caller to js_isassigning. see also bug 458421 ...
JS_IsConstructing
js_isconstructing has been removed in bug 918462. use callargs::isconstructing or callreceiver::isconstructing instead. syntax jsbool js_isconstructing(jscontext *cx, jsval *vp); name type description cx jscontext * the cx parameter passed to the jsnative. ...
JS_IsConstructing_PossiblyWithGivenThisObject
obsolete since jsapi 17this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. this article covers features introduced in spidermonkey 1.8.5 determine if a special this object was supplied to the constructor. syntax static jsbool js_isconstructing_possiblywithgiventhisobject(jscontext *cx, const jsval *vp, jsobject **maybethis); name type description cx jscontext * the context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. vp const jsval * maybethis jsobject ** description in the case of a constructor cal...
JS_IsConstructor
this article covers features introduced in spidermonkey 24 return whether the given function is a valid constructor. syntax bool js_isconstructor(jsfunction *fun); name type description fun jsfunction * the function to examine. description js_isconstructor determines if a specified function, fun is a valid constructor object. if so, js_isconstructor returns true. otherwise it returns false. see also mxr id search for js_isconstructor js::isconstructor bug 807228 ...
JS_IsExtensible
troduced in spidermonkey 1.8.5 query [[extensible]] properly of the given object. syntax bool js_isextensible(jscontext *cx, js::handleobject obj, bool *extensible); name type description cx jscontext * the context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject the object to examine. extensible bool * out parameter. receives true if extensible, false otherwise. description js_isextensible queries [[extensible]] property of the specified object, obj. if successful, js_isextensible stores [[extensible]] property to *extensible and returns true, otherwise returns false and the value of *extensible is undefined. see also mxr id search for js_preventextens...
JS_IsExternalString
syntax bool js_isexternalstring(jsstring *str); name type description str jsstring * the string to check. description js_isexternalstring returns true if the string is an external string; otherwise it's false. ...
JS_IsNative
syntax bool js_isnative(jsobject *obj); name type description str jsobject * the object to check. description js_isnative returns true if the object is a native object. ...
JS_IsNativeFunction
this article covers features introduced in spidermonkey 17 return whether the given function object equals the specified native function. syntax bool js_isnativefunction(jsobject *funobj, jsnative call); name type description funobj jsobject * the function object to examine. call jsnative the native function to compare. description js_isnativefunction determines if a specified function object, funobj equals a specified native function, call. if so, js_isnativefunction returns true. otherwise it returns false. see also mxr id search for js_isnativefunction js_isnative bug 648801 ...
JS_IsRunning
indicates whether or not a script or function is currently executing in a given context. syntax bool js_isrunning(jscontext *cx); name type description cx jscontext * the context to query. description js_isrunning determines if a script or function is currently executing in a specified jscontext, cx. if a script is executing, js_isrunning returns true. otherwise it returns false. see also mxr id search for js_isrunning ...
JS_IsStopIteration
syntax // added in spidermonkey 42 bool js_isstopiteration(js::value v); // obsolete since spidermonkey 42 bool js_isstopiteration(jsval v); name type description v js::value the value to check. description js_isstopiteration returns true if v is stopiteration, otherwise false. ...
JS_LockGCThing
oid * pointer to the item to protect. description js_lockgcthing is a deprecated function that protects a specified item, thing, associated with an executable script context, cx, from garbage collection. thing is a pointer to a jsdouble, jsstring, or jsobject. js_unlockgcthing removes a lock from a specified item, thing, allowing it to be garbage collected when the javascript engine determines it is unreachable. js_lockgcthing and js_unlockgcthing are available only for backward compatibility with existing applications. use js_addroot and js_removeroot instead. see also bug 734250 - removed *rt functions bug 706885 ...
JS_MakeStringImmutable
see also bug 1115986 ...
JS_NewDateObject
this article covers features introduced in spidermonkey 1.8.5 creates a new date object instance for the given time and date. syntax jsobject * js_newdateobject(jscontext *cx, int year, int mon, int mday, int hour, int min, int sec); name type description cx jscontext * the context in which to create the new date object. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. year int the year to set the new object to. mon int the month to set the new object to. mday int the day of the month to set the new object to. hour int the hour to set the new object to. min int the minute to set the new object's time to. sec int...
JS_NewObjectForConstructor
constructor argument is not an object jsval, this function will assert (in debug builds). if the constructor does not have a prototype property, this function will return null and set an exception on cx. the standard object creation api, js_newobject, takes explicit arguments for the class, prototype, and parent of the new object. with js_newobjectforconstructor, the prototype and parent are determined by the constructor, and class is still determined by the caller. the prototype is the prototype of the constructor if it is an object, otherwise null. the parent is the constructor's parent. see also mxr id search for js_newobjectforconstructor js_newobject object_to_jsval bug 581263 - added bug 738075 - added clasp parameter bug 959787 - added args parameter ...
JS_ObjectIsDate
syntax bool js_objectisdate(jscontext *cx, js::handleobject obj); name type description cx jscontext * pointer to a javascript context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * jsobject that should be checked. description js_objectisdate() can be used to check if you are dealing with a date object, or a date object used across compartments (or windows or sites, in the browser embedding). ...
JS_PreventExtensions
tempt to prevent extensions either succeeded or failed: it's a category error. thus in this case js_preventextensions will throw an error. var target = {}; var handler = {}; var pair = proxy.revocable(target, handler); var proxy = pair.proxy; var revoke = pair.revoke; revoke(); // bool succeeded; // bool rv = js_preventextensions(cx, proxy, &succeeded); // // rv == false, succeeded is indeterminate the second case occurs when no internal error is encountered, but the object simply refuses to be made non-extensible. for example, a proxy might refuse to be made non-extensible; this refusal would show up in the post-call value of *succeeded. var target = {}; var handler = { preventextensions: function(obj) { return false; } }; var obj = new proxy(target, handler); // bool succeeded; // ...
JS_PropertyStub
does nothing and returns true. js_enumeratestub is a stub for jsclass.enumerate. it does nothing and returns true. js_resolvestub is a stub for jsclass.resolve. it does nothing and returns true. js_convertstub is a stub for jsclass.convert. its behavior is the same as the default conversion behavior for objects. it attempts to call the object's valueof and tostring functions, in the order determined by the specified type, in accordance with the default defaultvalue algorithm in es5 §8.12.8. js_finalizestub is a stub for jsclass.finalize. it does nothing. see also mxr id search for js_propertystub mxr id search for js_strictpropertystub jspropertyop jsstrictpropertyop bug 1103152 - removed js_deletepropertystub, js_enumeratestub, js_resolvestub, and js_convertstub bug 736978 - re...
JS_ReportErrorNumber
or number is up to the application. ... / args ... / const char16_t ** additional arguments for the error message. these arguments must be of type char * for js_reporterrornumber or js_reporterrorflagsandnumber, or char16_t * for js_reporterrornumberuc or js_reporterrorflagsandnumberuc. the number of additional arguments required depends on the error message, which is determined by the errorcallback. callback syntax typedef const jserrorformatstring * (* jserrorcallback)(void *userref, const unsigned errornumber); name type description userref void * the userref pointer that was passed to the reporterrornumber api. errornumber const unsigned the errornumber that was passed to the reporterrornumber api. descr...
JS_SET_TRACING_DETAILS
e); name type description trc jstracer * the tracer. buf char * out parameter. the callback stores a string describing the reference traced in buf. bufsize size_t the size of buf, in chars. description set debugging information about a reference to a traceable thing to prepare for the following call to js_calltracer. when printer is null, arg must be const char * or char * c string naming the reference and index must be either (size_t)-1 indicating that the name alone describes the reference or it must be an index into some array vector that stores the reference. when printer is not null, the arg and index arguments are available to the callback as the debugprinterarg and debugprintindex fields of trc. the storage for name or callback's arguments needs to live only until the foll...
JS_SetCompartmentNameCallback
_t the maximum size of the buffer. description js_setcompartmentnamecallback sets callback function which will be called to name the compartment. if the runtime has no jscompartmentnamecallback, a compartment will be named "<unknown>"</unknown>. jscompartmentnamecallback will be called when visiting the compartment, and it should store the name of the compartment into buf with null terminated string. see also mxr id search for js_setcompartmentnamecallback mxr id search for jscompartmentnamecallback bug 777528 ...
JS_SetFunctionCallback
in a request on this jscontext. fcb jsfunctioncallback the callback to execute when javascript functions are invoked and exited. specify null to stop calling the current callback. the callback must not modify the current state of execution. the call stack cannot be relied upon, because this callback may be invoked from the jit code when the stack frame and context are in an indeterminate state. description js_setfunctioncallback sets a c function to be called each time a javascript function is invoked or exits. fcb is a pointer to the c function to call. note that debuggers should probably use js_setcallhook in preference to this function, because it is invoked when the javascript stack is guaranteed to be in a consistent state (and therefore it is valid to inspect a...
JS_SetGCZeal
nursery allocations. 8 incremental gc in two slices: 1) mark roots 2) finish collection. 9 incremental gc in two slices: 1) mark all 2) new marking and finish. 10 incremental gc in multiple slices. 11 verify post write barriers between instructions. 12 verify post write barriers between paints. 13 check internal hashtables on minor gc. 14 perform a shrinking collection every frequency allocations. with gc zeal enabled, gc-related crashes are much easier to reproduce (they happen more reliably) and debug (they happen sooner, closer to the source of the bug). the drawback is that gc zeal can cause javascript code to run extremely slowly. regularly running your test suite with gc zeal enabled at level 2 is ...
JS_SetInterruptCallback
ack sets a callback that can be called asynchronously. some common uses for an interrupt callback are: to run garbage collection periodically, by calling js_maybegc; to periodically take a break from script execution to update the ui (though note that mozilla does not do this, by design); to enforce application limits on the amount of time a script may run. (in this case, the callback may terminate the script by returning false.) js_getinterruptcallback returns the currently installed interrupt callback, or null if none is currently installed. js_requestinterruptcallback requests a callback set using js_setinterruptcallback. see also mxr id search for js_setinterruptcallback mxr id search for js_getinterruptcallback mxr id search for js_requestinterruptcallback bug 977287 ...
JS_SetNativeStackQuota
of trustedscriptstacksize. added in spidermonkey 31 description js_setnativestackquota sets the size of the native stack that should not be exceeded. to disable stack size checking, pass 0. spidermonkey allows for a distinction between system code (such as gcs, which may incidentally be triggered by script but are not strictly performed on behalf of such script), trusted script (as determined by js_settrustedprincipals), and untrusted script. each kind of code may have a different stack quota, allowing embedders to keep higher-priority machinery running in the face of scripted stack exhaustion by something else. the stack quotas for each kind of code should be monotonically descending, and may be specified with this function. if 0 is passed for a given kind of code, it defaults to ...
JS_SetOperationCallback
ack sets a callback that can be called asynchronously. some common uses for an operation callback are: to run garbage collection periodically, by calling js_maybegc; to periodically take a break from script execution to update the ui (though note that mozilla does not do this, by design); to enforce application limits on the amount of time a script may run. (in this case, the callback may terminate the script by returning js_false.) js_getoperationcallback returns the currently installed operation callback, or null if none is currently installed. js_triggeroperationcallback triggers a callback set using js_setoperationcallback. js_clearoperationcallback clears the current operation callback. obsolete since javascript 1.9.1 js_setoperationcallbackfunction sets the operation callback ...
JS_SetProperty
request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handlevalue object to which the property to set belongs. name or id const char * or const char16_t *or js::handleid name of the property to set. namelen size_t (only in js_setucproperty) the length of name in characters; or -1 to indicate that name is null-terminated. v js::handlevalue in/out parameter. *vp is the value to assign to the property. ordinarily this function leaves v unchanged, but it is possible for a jsclass.addproperty hook or a non-default setter to assign to v. description js_setproperty assigns the value v to the property name of the object obj. it behaves like the javascript expression obj[name] = v. js_setucprop...
JS_SetThreadStackLimit
void js_setthreadstacklimit(jscontext *cx, jsuword limitaddr) name type description cx jscontext * the context to configure. limitaddr jsuword an address near the top of the c stack. this should be a safely writeable address well short of the actual top of the stack. description js_setthreadstacklimit sets the maximum (if stack grows upward) or minimum (downward) legal stack byte address in limitaddr for the thread or process stack used by cx. to disable stack size checking, pass 0 for limitaddr. in a js_threadsafe build, after passing a jscontext from one thread to another, call js_setthreadstacklimit(cx, 0) after calling js_setcontextthread. (see also js_setcontextthread and js_clearcontextthread.) see also mxr id search for js_setthrea...
JS_StringHasLatin1Chars
description js_stringhaslatin1chars returns true iff the string's characters are stored as latin1. string characters are stored as either latin1char (8-bit) or char16_t (16-bit). clients can use js_stringhaslatin1chars and can then call either the latin1* or twobyte* functions. some functions like js_copystringchars and js_getstringcharat accept both latin1 and twobyte strings. ...
JS_ValueToInt32
the floating-point number is rounded to the nearest integer value. on success, js_valuetoint32 stores the converted value in *ip and returns js_true. on error or exception, it returns js_false, and the value left in *ip is undefined. js_valuetoint32 is pre-ecma-262 edition 1, and rounds differently than js_valuetoecmaint32 and js::toint32. this routine was added for layers-based graphics programming in netscape 4, but unless you know you need its rounding behavior, it is best to avoid it in favour of js::toint32. js::toint32 rounds as specified in ecma 262-3 §9.5, while this routine rounds by adding 0.5 to the converted float-point number and truncating the result at the decimal point. js::toint32 will also convert nan (and anything that converts to nan, such as an array of strings) to 0, ...
PRIVATE_TO_JSVAL
l. this can be useful with reserved slots. the private data pointer can point to application-defined memory of any type, but the pointer must be two-byte-aligned (that is, (int) p must be even). private data is managed entirely by the application. the javascript engine itself never uses a private data pointer. private data is not garbage collected. it is the application's responsibility to determine when it is safe to dereference a private data pointer. see also mxr id search for private_to_jsval js::privatevalue bug 952650 bug 1177892 -- removed ...
JSAPI reference
rbage collector to traverse those references. otherwise the garbage collector will not find all reachable objects and may collect objects that are still reachable, leading to a crash. (in spidermonkey 1.7 and earlier, the jsmarkop hook was used instead. this has since been removed.) the tracing apis are used by the garbage collector and jstraceop hooks. jsapi applications may also use them to examine the object graph. (for example, these apis support very smooth integration between the js garbage collector and other garbage collectors.) struct jstracer added in spidermonkey 1.8 js_tracechildren added in spidermonkey 1.8 js_traceruntime added in spidermonkey 1.8 jsval_is_traceable added in spidermonkey 1.8 obsolete since jsapi 31 jsval_to_traceable added in spidermonkey 1.8 obsolete...
JSDBGAPI
me js_isdebuggerframe js_getframereturnvalue js_setframereturnvalue js_getframecalleeobject js_getscriptfilename js_getscriptbaselinenumber js_getscriptlineextent js_getscriptversion js_gettopscriptfilenameflags js_getscriptfilenameflags js_flagscriptfilenameprefix jsfilename_null jsfilename_system jsfilename_protected evaluating debug code js_evaluateinstackframe examining object properties typedef jspropertydesc jspd_enumerate jspd_readonly jspd_permanent jspd_alias jspd_argument jspd_variable jspd_exception jspd_error typedef jspropertydescarray js_propertyiterator js_getpropertydesc js_getpropertydescarray js_putpropertydescarray hooks js_setdebuggerhandler js_setsourcehandler js_setexecutehook js_setcallhook js_setobjecthook...
SpiderMonkey 24
platform support spidermonkey 24 is supported on all the platforms where firefox 24 runs. compiling it requires a c++ compiler, and the jsapi can only be used from c++ code. (this change was motivated by garbage collector improvements, which lean quite heavily on c++'s support for raii through constructors and destructors.) if you are compiling with microsoft's visual studio, note that the minimum supported version is msvc10/2010: msvc8/9 support has been dropped. spidermonkey 24 includes a just-in-time compiler (jit) that compiles javascript to machine code, for a significant speed increase. it is supported on x86, x86_64, and arm architectures. on some other platforms (sparc, mips), the jit is provided but not supported. on all other platforms the jit is simply disabled; javascript...
SpiderMonkey 31
s outdated and spidermonkey not release alone! get it here mozilla-esr31 you will find it in "firefox extended support release 31" package on hg release platform support spidermonkey 31 is supported on all the platforms where firefox 31 runs. compiling it requires a c++ compiler, and the jsapi can only be used from c++ code. if you are compiling with microsoft's visual studio, note that the minimum supported version is msvc10/2010: msvc8/9 support has been dropped. spidermonkey 31 includes a just-in-time compiler (jit) that compiles javascript to machine code, for a significant speed increase. it is supported on x86, x86_64, and arm architectures. on some other platforms (sparc, mips), the jit is provided but not supported. on all other platforms the jit is simply disabled; javascript...
SpiderMonkey 38
s outdated and spidermonkey not release alone! get it here mozilla-esr38 you will find it in "firefox extended support release 38" package on hg release platform support spidermonkey 38 is supported on all the platforms where firefox 38 runs. compiling it requires a c++ compiler, and the jsapi can only be used from c++ code. if you are compiling with microsoft's visual studio, note that the minimum supported version is msvc10/2010. spidermonkey 38 includes a just-in-time compiler (jit) that compiles javascript to machine code, for a significant speed increase. it is supported on x86, x86_64, and arm architectures. on some other platforms (sparc, mips), the jit is provided but not supported. on all other platforms the jit is simply disabled; javascript code runs in an interpreter, as i...
SpiderMonkey 45
illa.mozilla.org under product: core, component: javascript engine. you may wish to make the bugs block bug 837921 (aliased as "sm.embedding"). — apr 14, 2016 platform support spidermonkey 45 is supported on all platforms able to run firefox 45. compiling it requires a c++ compiler, and the jsapi can only be used from c++ code. if you are compiling with microsoft's visual studio, note the minimum supported version is msvc 2013. spidermonkey 45 includes a just-in-time compiler (jit) that compiles javascript to machine code, for a significant speed increase. it is supported on x86, x86_64, and arm architectures. on several other platforms (sparc, mips), the jit is provided but not supported. on remaining platforms the jit is disabled; javascript code runs in an interpreter, as it has ...
SpiderMonkey releases
dermonkey is not an official product. our continuous integration system does produce a tarball that is built into a binary that runs our smoke tests, but we do not maintain it nor actively test its suitability for general embedding. we have periodically created "releases", but they are best-effort and incomplete. we do happily accept patches, and make some effort to keep the tip of the gecko tree minimally working as an embeddable source package. we are very limited in our ability to support older versions, including those labeled as "releases" on this page. the easiest way to fetch the version corresponding to the current firefox release is to visit the treeherder page for the release repository and click on the first sm(pkg) link you see. that will open a small window in the bottom left w...
Running Automated JavaScript Tests
g jstests on treeherder when viewing treeherder after a push to the mozilla repositories, jstests run in the browser are shown as r(j) meaning "javascript reftests". most of the spidermonkey shell jobs, labeled sm(...), will include js shell runs of both jstests and jit-tests. running jit-tests the jit-test suite uses a python harness that is similar to the jstests shell harness, but with some minor differences. basic usage is the same: jit_test.py path_to_js_shell developers will usually want to run like this to skip the slow tests and cover the most important options: jit_test.py --no-slow path_to_js_shell you can select specific tests to run in the same way as the jstests shell harness. most of the options in the jstests harness are also available for this one, but a few have differ...
TPS Formdata Lists
see bug 552531. ...
Mozinfo
level attributes (os, version, bits, processor) are available as module globals: if mozinfo.os == 'win': ... in addition, mozinfo exports a dictionary, mozinfo.info, that contain these values. mozinfo also exports: choices: a dictionary of possible values for os, bits, and processor main: the console_script entry point for mozinfo unknown: a singleton denoting a value that cannot be determined unknown has the string representation "unknown". unknown will evaluate as false in python: if not mozinfo.os: ... # unknown! command line usage mozinfo comes with a command line, mozinfo which may be used to diagnose one's current system. example output: os: linux version: ubuntu 10.10 bits: 32 processor: x86 three of these fields, os, bits, and processor, have a finite set of choices...
Mozilla Projects
clang, or from another language) and compiles that into javascript, which can be run on the web. firefox sync firefox sync synchronizes state and configuration data used by the browser, such as bookmarks, history, preferences, bookmarks, and so forth among all your devices. jshydra jshydra is a static analysis tool that is capable of performing analysis of general javascript code. l20n l20n lets localizers reach higher levels of free linguistic expression by sharpening the divide between localization and application logic. leak monitor leak monitor is a firefox extension by l. david baron that helps extension and chrome developers to find memory leaks. it will pop-up ...
Using RAII classes in Mozilla
te: autolock(mmutex); which erroneously causes the lock to be released at the end of the statement. we have two techniques for avoiding this problem: static analysis and runtime assertions. 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. this involves just one addition to the class, and the inclusion of attributes.h: class moz_raii nsautoscriptblocker {...} this is much simpler and more thorough than the guardobject runtime assertions, but are unfortunately currently only...
A Web PKI x509 certificate primer
create intermediates for each other it is called cross-signing). extensions while rfc 5280 defines 16 extensions for webpki in this document we will be describing the six extensions we considered critical for understanding. certificates can have other extensions not described on rfc 5280, but that is out of the scope of this document. extensions can be marked as critical or non-critical, conforming certificate verification libraries should stop processing verification when encountering a critical extension that they do not understand ( and should continue processing if the extension is marked as non-critical) mozila::pkix has this behavior. subject alternate name this extension defines what other names (such as dns names) are valid for this certificate. this allows for a certificate to b...
Browser security
articles provide important guides and references to ensuring the code you write is secure, including both design recommendations and testing guidelines. a web pki x509 certificate primerx.509 (in this document referred as x509) is an itu standard to describe certificates. ...
Gecko object attributes
ment. tree related attributes cycles "true" when the tree cell is a cycler, which means each click will cycle to the next option. in this case action 0 is called "cycles", which moves to the next option in the same way a manual click does. applied to: role_cell for the <xul:tree/> note: it's not exposed currently table related attributes layout-guess true when gecko's heuristic determines that it is a table that is probably used for layout, not for table. value not set means it is probably a data table. applied to: role_table table-cell-index the index of the table cell accessible. use nsiaccessibletable and nsiaccessibletablecell instead. applied to role_cell hypertext attributes formatting "block" if the object uses block formatting, and thus starts on a new lin...
Gecko states
to: role_menuitem, role_cell, role_outlineitem, xxx: continue events: event_state_change Сoncomitant state: state_selectable state_focused the object is focused applied to: events: concomitant state: state_focusable state_pressed the object is pressed. state_checked the object is checked state_mixed indicates that the state of a three-state check box or toolbar button is not determined. the check box is neither checked nor unchecked and is therefore in the third or mixed state. state_readonly the object is designated read-only. state_hottracked the object is hot-tracked by the mouse, which means that its appearance has changed to indicate that the mouse pointer is located over it. isn't used state_default this state represents the default button in a window. state_...
Embedded Dialog API
consistent dialog appearance have the option of implementing the complete dialog posing api. responsibilities of the embedding application basic windowing api to be able to respond to script requests to open new windows, an embedded gecko browser must have a way of opening new windows. this is accomplished using a callback into the embedding application. this basic api will by itself provide the minimal functionality gecko needs to create new windows, and an embedding application must implement at least this much. applications concerned with a consistent overall dialog appearance will probably choose to implement the complete api as well. an embedding application must implement the nsiwindowcreator nsiwindowcreator interface and hand off a reference to the implementation to the windowcreato...
The Places database
or more pages in moz_places refer to each entry. when no pages reference a favicon, the icon entry will be deleted. if the mime type of the image is image/png, the data blob must be reencoded from base16 (the format in which it is stored) to base64 in order to display correctly. expiration expiration is handled in toolkit/components/places/nsplacesexpiration.js. this algorithm determines the lifetime of all objects in the places system. periodically at runtime, the following happens to expire pages: expire visits that are older than the history expiration threshold. delete the history entries that were referenced by the expired visits and not referenced by any non-expired visit or bookmark. delete favicons for those expiring history entries that are not referenced by any ...
Manipulating bookmarks using Places
e nsinavbookmarksservice.getitemtitle() method: var thistitle = bmsvc.getitemtitle(newbkmkid); this code will display an alert containing the title of the item referenced by the id newbkmkid. the item uri similarly, you can obtain the uri corresponding to a given bookmark item by calling the nsinavbookmarksservice.getbookmarkuri() method. var thisuri = bmsvc.getbookmarkuri(newbkmkid); assuming you've run all the code samples previous to this one, this will output "http://google.com". you can use the nsinavbookmarksservice.changebookmarkuri() method to update the uri for a given bookmark item: var uri = ios.newuri("http://mozilla.com/", null, null); bmsvc.changebookmarkuri(newbkmkid, uri); this example changes the bookmark to refer to the mozilla web site instead of google. note: ...
Querying Places
2 attribute prtime begintime attribute unsigned long begintimereference readonly attribute boolean hasbegintime readonly attribute prtime absolutebegintime attribute prtime endtime attribute unsigned long endtimereference readonly attribute boolean hasendtime readonly attribute prtime absoluteendtime attribute astring searchterms readonly attribute boolean hassearchterms attribute long minvisits attribute long maxvisits attribute boolean onlybookmarked attribute boolean domainishost attribute autf8string domain readonly attribute boolean hasdomain attribute boolean uriisprefix attribute nsiuri uri readonly attribute boolean hasuri attribute boolean annotationisnot attribute autf8string annotation readonly attribute boolean hasannotation readonly attribute unsigned long ...
Retrieving part of the bookmarks tree
der ids from a previous query. this example will get the id of the bookmarks toolbar: var bookmarksservice = components.classes["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(components.interfaces.nsinavbookmarksservice); var toolbarfolder = bookmarksservice.toolbarfolder; the placesroot is the root folder in the whole places hierarchy. it contains administrative data as well as user data, and is therefore not recommended for use in querying. configure the query to get a hierarchical bookmarks result, pass the folder id to setfolders in your query object: query.setfolders([toolbarfolder], 1); run the query the executequery and executequeries functions will return an nsinavhistoryresult object containing the results of your query: var result = hi...
places.sqlite Database Troubleshooting
e you proceed, make a backup of the firefox profile folder, in any case. create a folder to use temporarily for this work, such as my_work_folder. copy places.sqlite-corrupt from the firefox profile folder to the work folder. download the latest precompiled binary sqlite command-line shell from: https://www.sqlite.org/download.html extract sqlite3 executable into the work folder. open a terminal window and navigate to the work folder. then open an sqlite shell: my_work_folder> sqlite3 places.sqlite-corrupt sqlite> pragma integrity_check; if the result is ok, this guide won't help; stop here and please file a bug. sqlite> .clone places.sqlite sqlite> pragma user_version; note the version number returned by the last pragma query. sqlite> .exit open a new shell for the new data...
The Publicity Stream API
ications should call this method when an user-initiated activity deemed attractive to potential consumers occurs. this spawns a doorhanger which allows the user to specify which users can view the activity, and (following successful login and authorization with the stream server) registers the activity in a stream at [address]. this stream can be pulled down by getpublicitystream() and helps determine the results for getuserrecommendedapps(). example use cases: 'adam got a high score in mafia wars', 'bethany bought a plane ticket to the caribbean', etc. activity is an object, formatted as per the fixme: deadlinkactivity streams open specification. onsuccess is a callback that will be invoked with no arguments if the activity is successfully posted. onerror is an error callback that wi...
extISessionStorage
boolean has(in astring aname) parameters aname the name of an item return value true if an item exists with the given name, false otherwise. set() sets the value of a storage item with the given name. void set(in astring aname, in nsivariant avalue) parameters aname the name of an item return value get() gets the value of a ...
Toolkit API
the mozilla toolkit is a set of programming interfaces (apis) built on top of gecko which provide advanced services to xul applications. these services include: profile management chrome registration browsing history extension and theme management application update service safe mode printing official references structure of an installable bundle: describes the common structure of installable bundles, including extensions, themes, and xulrunner applications extension packaging: specific information about how to package extensions theme packaging: specific information about how to package themes multiple-item extension packaging: specific information about multiple-item extension xpis xul application packaging: specific information about how to package ...
XML Extras
les should reside on a webserver so this shouldn't pose a problem (there you do not need that line either). additionally, "foo.com:80" and "foo.com:313" are considered different hosts for security purposes. you cannot open a connection to a different host. 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. file new bugs for additional documentation contributions, either specifically aimed at javascript developers or to complete & clarify the javadoc-style comments in the idl files. nsidomserializer (currently, the javascript constructor is xmlserializer()) nsidomparser (currently, th...
Creating a Python XPCOM component
g and wstring for unicode transfer. see here for info on describing interfaces, and on which types can be used. registering the interface in the "components" directory, execute : ../xpidl -m typelib -w -v -i /usr/share/idl/mozilla/ nsipysimple.idl on windows you must point to the idl directory as part of your mozilla build. for example: xpidl.exe -m typelib -w -v -i c:\source\mozilla\obj-i686-pc-mingw32\dist\idl foo.idl xpidl will then create nsipysimple.xpt, which should be placed correctly (e.g., in the 'components' directory). implementing the component unlike c++, pyxpcom does much of the work for you. make a file named "py_simple.py" for the actual code (again, in the 'components' directory): from xpcom import components, verbose class pysimple: #pythontestcomponent _com_interface...
Generating GUIDs
add-ons can (and should) be identified with ids of the form extensionname@organization.tld since firefox 1.5. warning: if you just want an id for your add-on, generating a guid is almost definitely not what you want to do. using the extensionname@organization.tld form is approximately one thousand times easier for everyone involved. don't have a domain name? do you have a blog on a subdomain? use that. ...
XPCOM array guide
Mozilla › Tech › XPCOM › Guide › Arrays
ic enumerator for enumerating a list of any xpcom object. there are many implementations of nsisimpleenumerator, including one that enumerates nsiarray objects, and another one for nscomarray. it is very common for other interfaces which support nsisimpleenumerator to make their own implementations. nsistringenumerator string enumerators provide an easy way to pass a list of strings around with minimal copying. both unicode strings and utf8-encoded strings are supported. for more information about the different types of strings, see the string guide. string enumerators can be created from nstarray<nsstring> or nstarray<nscstring> objects. the implementation of the string enumerator interfaces for nstarray<nsstring> and nstarray<nscstring> supports conversion between utf8 and unicode, and c...
Packaging WebLock
the following html specifies a complete webpage in which the trigger script is defined as a javascript function, installweblock, that gets called when the user clicks the ...
Preface
t we describe in this tutorial is a practical (and, we hope, genuinely useful) addition to the browser. in order to build it, your gecko sdk or mozilla source tree needs to be version 1.2 or later (xpcom interfaces were not fully frozen in prior releases). 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. details about downloading the sdk, building, and getting programmatic access to gecko components are provided in the appendix to this book, setting up the gecko sdk. conventions the formatting conventions listed below are used to designate specific types of information in the book and make things easier to scan. the goal is to use as few formats as possible, but to distinguish the various ...
Creating XPCOM components
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 access to weblock creating the weblock programming interface defining the weblock interface 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 ...
How to build a binary XPCOM component using Visual Studio
test component in a xulrunner application in order to test your component in a xulrunner application, you need to “install” the component, “clear” the component registry, and use the component from javascript. install component: copy your xpt and dll files to the {a...
Components.Constructor
ts.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. it eliminates the clutter of typing components.classes, components.interfaces, createinstance, and so on every time you wish to create an instance. it also gives creation of xpcom objects more javascript-like syntax. 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...
Components.classes
he same component, is to use the new operator on the class object: var clazz = components.classes["@mozilla.org/supports-array;1"]; var inst = new clazz(components.interfaces.nsisupportsarray); this implicitly calls the createinstance() method for you. you still have to provide the interface name each time you create an instance, which is not necessary when using components.constructor. determining if a component has to be instantiated or used as a service in the general case it is not possible to programmatically determine if a given component has to be instantiated or used as a service. often, this is stated in the documentation of the component you want to use. if this is not the case, you might want to try and find example usages of that component within mxr. ...
Components.lastResult
ng multiple tests against 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. example in the following example, the local variable i contains the actual result returned by bar() (assuming that bar() is called via xpconnect), and components.lastresult contains the success code returned by bar(). // given that foo.bar is a method that might return // the success codes ns_ok, '5', and '6' or some error code... try { var i = foo.bar(); switch (components.lastresult) { case components.results.ns_ok: // ns_ok is good! break; case 5: // do something wit...
Components.utils.Sandbox
w components.utils.sandbox(...) to create a sandbox has the same effect as calling sandbox(...) without new. the created sandbox is simply an empty javascript object marked as having been created by the restricted privilege principal. you can then use it with evalinsandbox() to make it the global scope object for the specified script. principal the security principal defined for a sandbox determines what code running in that sandbox will be allowed to do. the principal may be one of four types: the system principal, a content principal, an expanded principal, or a null principal. see security checks for more information on security principals. system principal to specify the system principal, you can create it using code like: cc["@mozilla.org/systemprincipal;1"].createinstance(ci.nsi...
Components.utils.cloneInto
re an object with less-privileged code like a normal web page script. syntax components.utils.cloneinto(obj, targetscope[, options]); parameters obj : object the object to clone. targetscope : object the object to attach the object to. options : object this optional parameter is an object with the following optional properties: clonefunctions: a boolean value that determines if functions should be cloned. if omitted the default value is false. cloned functions have the same semantics as functions exported using components.utils.exportfunction. see cloning objects that have functions below. wrapreflectors: a boolean value that determines if objects reflected from c++, such as dom objects, should be cloned. if omitted the default value is false. see cloning objects ...
Components.utils.createObjectIn
s://blog.mozilla.org/addons/2014/04/10/changes-to-unsafewindow-for-the-add-on-sdk/. syntax var newobject = components.utils.createobjectin(obj, options); parameters obj an object indicating the compartment in which the new object should be created; the new object will be created in the scope of this object's compartment. options an object containing a single option defineas, which determines the name of the object in the target compartment. return value a new object in the specified scope. example to create a new object in the scope of a specified dom window, you can simply do: function genpropdesc(value) { return { enumerable: true, configurable: true, writable: true, value: value }; } var myobject = components.utils.createobjectin(mywindow); var proplist = { nam...
Components.utils.exportFunction
tions]); parameters func : function the function to export. targetscope : object the object to attach the function to. this does not have to be the global window object: it could be any other object in the target window, or an object created by the caller. options : object optional parameter that supplies additional options. the following options are currently defined: defineas: determines the name of the function in targetscope. if this is omitted, you need to assign the return value of exportfunction() to an object in the target scope. allowcallbacks: deprecated/redundant from firefox 34. this option allows the exported function to accept callbacks as arguments. boolean, defaulting to false. this option is new in firefox 33. from firefox 34 onwards this option has no effect: t...
Components.utils.importGlobalProperties
syntax void components.utils.importglobalproperties([string1, string2, ...]); parameters [string1, string2, ...] an array of strings. each string is the name of an object to import. example components.utils.import("resource://gre/modules/devtools/console.
Components.utils.isXrayWrapper
, by default, with "xray vision": a mechanism that filters out certain changes to the objects that could cause them to behave in unexpected ways. for example, privileged code using an xray to a dom object sees only the original, native version of the dom object. any expando properties are not visible, and if any native properties have been redefined, this has no effect. use this function to determine whether a given object is an xray or not. syntax boolean components.utils.isxraywrapper(obj); parameters obj the object to check. returns true if the object is an xray: false otherwise. example var isxray = components.utils.isxraywrapper(gbrowser.contentwindow); // true var waived = components.utils.waivexrays(gbrowser.contentwindow); isxray = components.utils.isxraywrapper(waiv...
Components object
bers: classes array of classes by contractid classesbyid array of classes by cid constructor constructor for constructor of components exception constructor for xpconnect exceptions id constructor for xpcom nsids interfaces array of interfaces by interface name interfacesbyid array of interfaces by iid issuccesscode function to determine if a given result code is a success code lastresult result code of most recent xpconnect call manager the global xpcom component manager results array of known result codes by name returncode pending result for current call stack current javascript call stack utils provides access to several useful features utils.atline pr...
RbXPCOM
you can find additional information using the resource links below. ...
Profiling XPCShell
la_js_profiler_output</tt> to a filename where you want the output file. for example, on linux or macosx you do: export mozilla_js_profiler_output=/tmp/profile.txt now, run the script using xpcshell. after running has finished, the output file will contain a profile. a profile will look like this: file:///users/michiel/mozilla/tree1/...js/calutils.js [2,25420] createdatetime() {60-62} 579 {min 0, max 3, avg 0, sum 427, self 427} [2,56810] cp_qi() {860-866} 835 {min 0, max 1, avg 0, sum 950, self 950} the first line tells which file was profiled. then, the next lines shows the amount of time spend in the functions in that file. the line consists of: the compile count of the function; the call count of the function; the functions name; the starting line number; the ending lin...
XPCShell Reference
the command line the command-line syntax for xpcshell is: xpcshell [-s] [-w] [-w] [-v version] [-f scriptfile] [scriptfile] [scriptarg...] -c this option turns on the "compile-only" mode. (setting this option disables the "interactive" mode) -f this option specifies a script file to execute. xpcshell terminates upon script completion. you can specify multiple js files to execute by using multiple -f arguments, and the scripts will be executed in the order encountered. furthermore, xpcshell looks for xpcshell.js in the current directory. if that file is found, it is executed before any other js files specified. -g this option specifies which gecko runtime environment directory (gredir) to use for xpcom. -i this option turns on the "interactive" mode -s this option ...
Monitoring HTTP activity
ctivity_type_socket_transport, the activity subtype, which indicates the specific type of activity that occurred, will be a socket transport status code. observable http activities when the activity type is activity_type_http_transaction, the activity subtype will be one of the activity subtype constants. these include the ability to monitor outgoing http request headers and bodies as well as incoming http headers and complete http transactions. ...
NS_NewLocalFile
#include "nsxpcom.h" #include "nsilocalfile.h" nsresult ns_newlocalfile( const nsastring& apath, prbool afollowlinks, nsilocalfile** aresult ); parameters apath [in] a utf-16 string object that specifies an absolute filesystem path. this path does not need to reference an existing file. it is an error to pass a relative filesystem path. afollowlinks [in] this attribute will determine if the nsilocalfile instance will automatically resolve symbolic links. this parameter has no effect on unix systems. on windows, passing true causes shortcuts to be automatically resolved, and on macos, passing true causes finder aliases to be automatically resolved. aresult [out] a reference to the newly created nsilocalfile instance. return values the ns_newlocalfile function returns ns...
NS_NewNativeLocalFile
ol afollowlinks, nsilocalfile** aresult ); parameters apath [in] a string object that specifies an absolute filesystem path. this string should be encoded using ascii or the multibyte character coding corresponding to the native filesystem. this path does not need to reference an existing file. it is an error to pass a relative filesystem path. afollowlinks [in] this attribute will determine if the nsilocalfile instance will automatically resolve symbolic links. this parameter has no effect on unix systems. on windows, passing true causes shortcuts to be automatically resolved, and on macos, passing true causes finder aliases to be automatically resolved. aresult [out] a reference to the newly created nsilocalfile instance. return values the ns_newnativelocalfile function retu...
NS_ShutdownXPCOM
#include "nsxpcom.h" nsresult ns_shutdownxpcom( nsiservicemanager* asvcmanager ); parameters asvcmanager [in] the nsiservicemanager instance that was returned by ns_initxpcom2 (or ns_initxpcom3) or null. return values the ns_shutdownxpcom function returns ns_ok if successful. otherwise, it returns an error code. remarks you must call this method once you are finished using xpcom. calling this method triggers the "xpcom-shutdown" notification to be dispatched to observers. ...
Core XPCOM functions
for a list of defined result values, see error codes returned by mozilla apis. ...
Append
void append( const self_type& astring ); parameters astring [in] a nsacstring to append to this string. void append( const char_type* adata, size_type adatalength = pr_uint32_max ); parameters adata [in] a raw character array to append to this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. void append( char_type achar ); parameters achar [in] a character to append to this string. remarks if insufficient memory is available to perform the assignment, then the string's internal buffer will point to a static empty (zero-length) buffer. ...
Assign
void assign( const self_type& astring ); parameters astring [in] a nsacstring to copy into this string. void assign( const char_type* adata, size_type adatalength = pr_uint32_max ); parameters adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. void assign( char_type achar ); parameters achar [in] the character to copy into this string. remarks if insufficient memory is available to perform the assignment, then the string's internal buffer will point to a static empty (zero-length) buffer. ...
BeginReading
« xpcom api reference summary the beginreading function returns a const pointer to the first element of the string's internal buffer. const char_type* beginreading() const; remarks the resulting character array is not necessarily null-terminated. the length of the array is determined by the result of the length method. example code // count the number of times a particular character appears in the string pruint32 countchar(const nsacstring& str, char c) { const char* start = str.beginreading(); const char* end = str.endreading(); pruint32 count = 0; while (start != end) { if (*start++ == c) ++count; } return count; } see also length, endreading ...
EndReading
« xpcom api reference summary the endreading function returns a const char_type pointer to the element just beyond the last element of the string's internal buffer. const char_type* endreading() const; remarks it is generally illegal to dereference the returned pointer, unless it is known that the string's internal buffer is null-terminated. the ns_cstringgetdata function can be used to determine if a nsacstring instance has null-terminated storage. example code see beginreading for an example. see also beginreading, ns_cstringgetdata, nsacstring ...
Insert
st char_type* adata, index_type aposition, size_type adatalength = pr_uint32_max ); parameters adata [in] a raw character array to append to this string. aposition [in] an offset into the string's internal buffer specifying where to place the given characters. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. void insert( char_type achar, index_type aposition ); parameters achar [in] a character to append to this string. aposition [in] an offset into the string's internal buffer specifying where to place the given characters. remarks if insufficient memory is available to perform the assignment, then the string's internal buffer will poin...
Length
size_type length() const; ...
Replace
atalength = pr_uint32_max ); parameters acutstart [in] the starting index of the section to remove, measured in storage units. acutlength [in] the length of the section to remove, measured in storage units. adata [in] a raw character array to append to this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. void replace( index_type acutstart, index_type acutlength, char_type achar ); parameters acutstart [in] the starting index of the section to remove, measured in storage units. acutlength [in] the length of the section to remove, measured in storage units. achar [in] a character to append to this string. remarks if insufficient me...
Append
void append( const self_type& astring ); parameters astring [in] a nsastring to append to this string. void append( const char_type* adata, size_type adatalength = pr_uint32_max ); parameters adata [in] a raw character array to append to this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. void append( char_type achar ); parameters achar [in] a character to append to this string. remarks if insufficient memory is available to perform the assignment, then the string's internal buffer will point to a static empty (zero-length) buffer. ...
Assign
void assign( const self_type& astring ); parameters astring [in] a nsastring to copy into this string. void assign( const char_type* adata, size_type adatalength = pr_uint32_max ); parameters adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. void assign( char_type achar ); parameters achar [in] the character to copy into this string. remarks if insufficient memory is available to perform the assignment, then the string's internal buffer will point to a static empty (zero-length) buffer. ...
BeginReading
« xpcom api reference summary the beginreading function returns a const pointer to the first element of the string's internal buffer. const char_type* beginreading() const; remarks the resulting character array is not necessarily null-terminated. the length of the array is determined by the result of the length method. example code // count the number of times a particular character appears in the string pruint32 countchar(const nsastring& str, prunichar c) { const prunichar* start = str.beginreading(); const prunichar* end = str.endreading(); pruint32 count = 0; while (start != end) { if (*start++ == c) ++count; } return count; } see also length ...
EndReading
« xpcom api reference summary the endreading function returns a const char_type pointer to the element just beyond the last element of the string's internal buffer. const char_type* endreading() const; remarks it is generally illegal to dereference the returned pointer, unless it is known that the string's internal buffer is null-terminated. the ns_cstringgetdata function can be used to determine if a nsastring instance has null-terminated storage. example code see beginreading for an example. see also beginreading, ns_cstringgetdata, nsastring ...
Insert
st char_type* adata, index_type aposition, size_type adatalength = pr_uint32_max ); parameters adata [in] a raw character array to append to this string. aposition [in] an offset into the string's internal buffer specifying where to place the given characters. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. void insert( char_type achar, index_type aposition ); parameters achar [in] a character to append to this string. aposition [in] an offset into the string's internal buffer specifying where to place the given characters. remarks if insufficient memory is available to perform the assignment, then the string's internal buffer will poin...
Length
size_type length() const; ...
Replace
atalength = pr_uint32_max ); parameters acutstart [in] the starting index of the section to remove, measured in storage units. acutlength [in] the length of the section to remove, measured in storage units. adata [in] a raw character array to append to this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. void replace( index_type acutstart, index_type acutlength, char_type achar ); parameter acutstart [in] the starting index of the section to remove, measured in storage units. acutlength [in] the length of the section to remove, measured in storage units. achar [in] a character to append to this string. remarks if insufficient mem...
get
« xpcom api reference summary the get function returns a const pointer to the string's null-terminated, internal buffer. const char_type* get() const; example code nsembedcstring str("hello world"); printf("%s\n", str.get()); ...
nsEmbedCString
type& aabstractstring ); parameters aabstractstring [in] a nsacstring to copy into this string. explicit nsembedcstring( const char_type* adata, size_type adatalength = pr_uint32_max ); parameters adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. remarks the default constructor sets the string's internal buffer to point to a static empty (zero-length) buffer. ...
nsEmbedCString
« xpcom api reference summary the nsembedcstring concrete class provides a way to construct a nsacstring object that allocates null-terminated storage. #include "nsembedstring.h" class nsembedcstring : public nsacstring { ... }; typedefs self_type [nsembedcstring] an alias for the type of this class. abstract_string_type [nsacstring] an alias for the abstract string type this class specializes. methods nsembedcstring constructors for nsembedcstring. get the get function returns a const pointer to the string's null-terminated, internal buffer. operators operator= this operator is a shortcut for the inherited nsacstring::assign family of functions. remarks the methods defined on nsembedcstring are implemented as inline wrappers around the xpcom string functions, prefix...
get
« xpcom api reference summary the get function returns a const pointer to the string's null-terminated, internal buffer. const char_type* get() const; example code void getbar(nsastring &result); void func() { nsembedstring str; getbar(str); const prunichar *data = str.get(); ... } ...
nsEmbedString
g_type& aabstractstring ); parameters aabstractstring [in] a nsastring to copy into this string. explicit nsembedstring( const char_type* adata, size_type adatalength = pr_uint32_max ); parameters adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. remarks the default constructor sets the string's internal buffer to point to a static empty (zero-length) buffer. ...
nsEmbedString
« xpcom api reference summary the nsembedstring concrete class provides a way to construct a nsastring object that allocates null-terminated storage. #include "nsembedstring.h" // or: #include "nsstringglue.h" if inside gecko class nsembedstring : public nsastring { ... }; typedefs self_type [nsembedstring] an alias for the type of this class. abstract_string_type [nsastring] an alias for the abstract string type this class specializes. methods nsembedstring constructors for nsembedstring. get the get function returns a const pointer to the string's null-terminated, internal buffer. operators operator= this operator is a shortcut for the inherited nsastring::assign family of functions. remarks the methods defined on nsembedstring are implemented as inline wrappers aroun...
Realloc
s of the block of memory to allocate. this may be 0, in which case realloc behaves like nsmemory::free. return values this function returns nsnull if the memory allocation fails. otherwise, it returns a pointer to the newly allocated buffer. the result must be freed with a call to nsmemory::free when it is no longer needed. remarks if aptr is non-null, then its contents will be unchanged to the minimum of the old and new sizes. newly allocated memory is uninitialized. see also nsmemory::free ...
nsMemory
ng to go through the service manager to get it. #include "nsmemory.h" class nsmemory { ... }; methods alloc the alloc function allocates a block of memory of a particular size. realloc the realloc function reallocates a block of memory to a new size. free the free function frees a block of memory that was allocated by xpcom's memory manager. heapminimize the heapminimize function attempts to shrink the size of the heap. clone the clone function creates a copy of an existing memory block up to the size specified. getglobalmemoryservice the getglobalmemoryservice function returns a reference to xpcom's global nsimemory object. remarks to use the methods in this class, you must link your component or applicat...
IAccessible2
n this value is useful is if the at wants to build a cache. the at could cache the uniqueids in addition to other data being cached. when an event is fired the at could map the uniqueid to its internal model. thus, if there's a reorder/show/hide event the at knows which part of the internal structure has been invalidated and can refetch just that part. this value can also be used by an at to determine when the current control has changed. if the role is the same for two controls that are adjacent in the tab order, this can be used to detect the new control. another use of this value by an at is to identify when a grouping object has changed, for example when moving from a radio button in one group to a radio button in a different group. one means of implementing this would be to create a fact...
IAccessibleAction
returned strings are the localized human readable key sequences to be used to activate each action, e.g. "ctrl+shift+d". since these key sequences are to be used when the object has focus, they are like mnemonics (access keys), and not like shortcut (accelerator) keys. there is no need to implement this method for single action controls since that would be redundant with the standard msaa programming practice of getting the mnemonic from get_acckeyboardshortcut. an at such as an on screen keyboard might not expose these bindings but provide alternative means of activation. [propget] hresult keybinding( [in] long actionindex, [in] long nmaxbindings, [out, size_is(,nmaxbindings), length_is(, nbindings)] bstr keybindings, [out] long nbindings ); parameters actionindex 0 based index sp...
IAccessibleApplication
rmation it needs to differentiate this application from other applications, from other versions of this application, or from other versions of this application running on different versions of an accessibility bridge or accessibility toolkit. servers implementing iaccessible2 should provide access to the iaccessibleapplication interface via queryservice from any object so that ats can easily determine specific information about the application such as its name or version. method overview [propget] hresult appname([out] bstr name ); [propget] hresult appversion([out] bstr version ); [propget] hresult toolkitname([out] bstr name ); [propget] hresult toolkitversion([out] bstr version ); methods appname() returns the application name. [propget] hresult appname( [out] bstr name ); p...
IAccessibleHypertext
fied link. the returned iaccessiblehyperlink object encapsulates the hyperlink and provides several kinds of information describing it. [propget] hresult hyperlink( [in] long index, [out] iaccessiblehyperlink hyperlink ); parameters index this 0 based index specifies the hyperlink to return. hyperlink if the given index is valid, that is it lies in the interval from 0 to the number of links minus one, a reference to the specified hyperlink object is returned. if the index is invalid then a null pointer is returned. return value e_invalidarg if bad [in] passed, [out] value is null. s_ok. hyperlinkindex() returns the index of the hyperlink that is associated with this character index. this is the case when a link spans the given character index. [propget] hresult hyperlinkindex( [in] l...
imgIContainer
gecko 2.0 void unlockimage(); attributes attribute type description animated boolean whether this image is animated. you can only be guaranteed that querying this will not throw if status_decode_complete is set on the imgirequest. read only. exceptions thrown ns_error_not_available if the animated state cannot be determined. animationmode unsigned short currentframe gfxasurface get a surface for the current frame. this may be a platform-native, optimized frame, so you cannot inspect its pixel data. read only. native code only! obsolete since gecko 2.0 currentframeindex unsigned long the index of the current frame that would be drawn if the image was to be dra...
mozIRegistry
n interface. figuring out an appropriate implementation given some arbitrary desired properties. nsrepository this is basically the same as is provided today (see mozilla/xpcom/public/nsrepository.h). the primary change to this component is that we will modify it to utilize the new moziregistry interface versus the nsreg.h functions it calls today. in addition, it likely will have a couple of minor extensions: support for specifying the .reg file name on initialize(). i think this might make it a little more flexible, thereby making xpcom more general-purpose. adding support so that the underlying moziregistry implementation can be tailored by the initializer (client application). this is so that one can choose the basic libreg-based registry implementation versus a more advanced, e...
mozISpellCheckingEngine
only. provideswordutils boolean does the engine provide its own word utilities? read only. methods adddirectory() adds all the dictionaries in the specified directory to the spell checker. void adddirectory( nsifile dir ); parameters dir an nsifile object indicating the directory from which to add dictionaries. check() checks a word to determine if it's spelled correctly. when this changes, the spell checker sends a "spellcheck-dictionary-update" notification. boolean check( in wstring word ); parameters word a word to check for correct spelling. return value returns true if word is spelled correctly according to the dictionary attribute, and returns false if word is misspelled. getdictionarylist() gets the list of di...
mozIStorageError
...
TakeFocus
« nsiaccessible page summary this method focuses this accessible node. void takefocus(); remarks the state state_focusable indicates whether this node is normally focusable. it is the callers responsibility to determine whether this node is focusable.acctakefocus on a node that is not normally focusable (such as a table), will still set focus on that node, although normally that will not be visually indicated in most style sheets. see also nsiaccessible.focusedchild ...
nsIAccessibleProvider
...
nsIAccessibleScrollType
ject or substring to the bottom edge of the window (or as close as possible). scroll_type_left_edge 0x04 scroll the left edge of the object or substring to the left edge of the window (or as close as possible). scroll_type_right_edge 0x05 scroll the right edge of the object or substring to the right edge of the window (or as close as possible). scroll_type_anywhere 0x06 scroll an object the minimum amount necessary in order for the entire frame to be visible (if possible). ...
nsIAccessibleSelectable
ceptions thrown ns_error_failure if the specified object is not selectable. clearselection() clears the selection in the object so that no children in the object are selected. void clearselection(); parameters none. getselectedchildren() returns an nsiarray of the selected nsiaccessible children. nsiarray getselectedchildren(); parameters none. return value an nsiarray. ischildselected() determines if the current child of this object is selected. boolean ischildselected( in long index ); parameters index the zero-based accessible child index. return value true if the child is selected, false if not. refselection() returns a reference to the accessible object representing the specified selected child of the object. nsiaccessible refselection( in long index ); parameters index zero...
nsIAccessibleStates
object is the child of an object that allows its children to be selected and that this child is one of those children that has been selected. state_focused 0x00000004 the object is focused. state_pressed 0x00000008 the object is pressed. state_checked 0x00000010 the object is checked. state_mixed 0x00000020 indicates that the state of a three-state check box or toolbar button is not determined. the check box is neither checked nor unchecked and is therefore in the third or mixed state. state_readonly 0x00000040 the object is designated read-only. state_hottracked 0x00000080 the object is hot-tracked by the mouse, which means that its appearance has changed to indicate that the mouse pointer is located over it. currently unused. state_default 0x00000100 this state represents the...
nsIAccessibleTable
cell is not selected. iscolumnselected() return a boolean value indicating whether the specified column is selected, that is all cells within the column are selected. boolean iscolumnselected( in long columnindex ); parameters columnindex the column index. return value true if the column is selected, false if the column is not selected. isprobablyforlayout() use heuristics to determine if table is most likely used for layout. boolean isprobablyforlayout(); parameters none. return value true if the table is probably for layout, false if the table is probably not for layout. isrowselected() return a boolean value indicating whether the specified row is selected, that is all cells within the row are selected. boolean isrowselected( in long rowindex ); parameters r...
nsIAccessibleTreeCache
y. return value the nsiaccessible corresponding to the specified tree cell. invalidatecache() invalidates the number of cached treeitem accessibles. void invalidatecache( in long arow, in long acount ); parameters arow row index the invalidation starts from. acount the number of treeitem accessibles to invalidate, the number sign specifies whether rows have been inserted (plus) or removed (minus) treeviewchanged() invalidates children created for the previous tree view. void treeviewchanged(); parameters none. treeviewinvalidated() fires name change events for invalidated area of tree. void treeviewinvalidated( in long astartrow, in long aendrow, in long astartcol, in long aendcol ); parameters astartrow row index invalidation starts from. aendrow row index invalidation end...
nsIAppShellService
obsolete since gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) the appshell service needs to be informed of modal xul windows currently open. call this method as a window becomes modal or as it becomes nonmodal. void toplevelwindowismodal( in nsixulwindow awindow, in boolean amodal ); parameters awindow the window to register. amodal true if awindow is becoming modal or false if awindow is becoming nonmodal (or being closed). unregistertoplevelwindow() remove a window from the application's window registry. note: this method will not automatically attempt to quit the application when the last window is unregistered. for that, see quit(). void unregistertoplevelwindow( in nsixulwindow awindow ); parameters awindow the window to register. ...
nsIApplicationUpdateService
it also provides utilities for selecting and downloading update patches. ...
nsIAutoCompleteInput
n true if auto-complete is currently disabled; otherwise false. forcecomplete boolean if true, the text field automatically completes to the default result whenever the user hits the enter key or the text field loses focus. maxrows unsigned long the maximum number of rows to display in the autocomplete suggestion popup. minresultsforpopup unsigned long specifies a minimum number of search results that must be available before the autocomplete popup will open. popup nsiautocompletepopup the view in which results will be displayed.read only. popupopen boolean indicates whether or not the popup view is already open. searchcount un...
nsIBidiKeyboard
e type description havebidikeyboards boolean indicates whether or not the system has at least one keyboard for each direction (left-to-right and right-to-left) installed. read only. note: this throws ns_error_not_implemented if the widget layer doesn't provide this information. currently, this is only implemented on windows. methods islangrtl() determines if the current keyboard language is right-to-left. (supported on: win32, mac, gtk2) note: prior to gecko 1.9 this method used a parameter 'out prbool aisrtl' to return the value. boolean islangrtl(); parameters none. return value true if the current keyboard is right-to-left, false if it is not. exceptions thrown ns_error_failure if no right-to-left keyboards are installed. setlangfr...
nsICachingChannel
ent to the listener's onstoprequest in this case. this flag is set automatically when the application is offline. load_only_if_modified 1 << 31 this load flag controls what happens when a document would be loaded from the cache to satisfy a call to asyncopen. if this attribute is set to true, then the document will not be loaded from the cache. a stream listener can check isfromcache() to determine if the asyncopen will actually result in data being streamed. if this flag has been set, and the request can be satisfied via the cache, then the ondataavailable events will be skipped. the listener will only see onstartrequest followed by onstoprequest. methods isfromcache() obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) this method finds out...
nsICancelable
scriptable this interface provides a means to cancel an operation that is in progress. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void cancel(in nsresult areason); methods cancel() call this method to request that this object abort whatever operation it may be performing. void cancel( in nsresult areason ); parameters areason a failure code indicating why the operation is being canceled. it is an error to pass a success code. ...
nsIChannelPolicy
key 2.1) this interface exists to allow the content policy mechanism to function properly during channel redirects. channels can be created with this interface placed in the property bag and upon redirect, the interface can be transferred from the old channel to the new channel. attributes attribute type description contentsecuritypolicy nsisupports a nsicontentsecuritypolicy object to determine if the load should be allowed. loadtype unsigned long indicates what type of content is being loaded, for example nsicontentpolicy::type_image. ...
nsICharsetResolver
for calling notifyresolvedcharset() and passing it the final resolved charset and the closure that requestcharset set. acstring requestcharset( in nsiwebnavigation awebnavigation, in nsichannel achannel, out boolean awantcharset, out nsisupports aclosure ); parameters awebnavigation the nsiwebnavigation the document is being loaded in. may be null. achannel the channel the document is coming in from. awantcharset gets set to true if notifyresolvedcharset() should be called with the given aclosure object. aclosure a resulting object which should be passed to notifyresolvedcharset() if awantcharset is set to true. return value the resolved charset, or an empty string if no charset could be determined. ...
nsIChromeRegistry
hromeurl ); parameters achromeurl the url that is to be converted. return value a new nsiuri object containing the loadable uri for the specified chrome url. violates the xpcom interface guidelines wrappersenabled() returns whether xpcnativewrappers are enabled for the specified uri. boolean wrappersenabled( in nsiuri auri ); parameters auri the uri for which to determine if xpcnativewrappers are enabled. return value true if xpcnativewrappers are enabled for the specified uri; otherwise false. see also chrome registration ...
nsIClipboard
clipboard. void setdata( in nsitransferable atransferable, in nsiclipboardowner anowner, in long awhichclipboard ); parameters atransferable the transferable containing the data to put on the clipboard. anowner the owner of the transferable. awhichclipboard specifies the clipboard to which this operation applies. supportsselectionclipboard() this method allows clients to determine if the implementation supports the concept of a separate clipboard for selection. boolean supportsselectionclipboard(); parameters none. return value returns true if kselectionclipboard is available. otherwise it returns false. supportsfindclipboard() this method allows clients to determine if the implementation supports the concept of a separate clipboard for find search strings. boole...
nsICommandController
in an nsicommandparams object. void docommandwithparams( in string command, in nsicommandparams acommandparams ); parameters command the command to execute. acommandparams the parameters. getcommandstatewithparams() void getcommandstatewithparams( in string command, in nsicommandparams acommandparams ); parameters command the command whose state is to be determined. acommandparams the command parameters. see also nsicontroller nsicontrollercontext ...
nsICommandLine
text of that argument, so if the argument is a flag, the returned value is "-flag [<flagvalue>]". exceptions thrown ns_error_invalid_arg the specified index is out of bounds. handleflag() finds the specified flag, removing it from the array of flags. reports whether or not the specified flag was found. this is useful for boolean flags; that is, flags that don't accept a parameter. you can determine if the flag was provided and remove it from the list of flags waiting to be processed in one operation. boolean handleflag( in astring aflag, in boolean acasesensitive ); parameters aflag the flag name to find and remove. acasesensitive whether to do case-sensitive comparisons. return value true if the flag was found, otherwise false. handleflagwithparam() finds a flag in the list of flag...
nsIContentSniffer
netwerk/base/public/nsicontentsniffer.idlscriptable content sniffer interface. components implementing this interface can determine a mime type from a chunk of bytes. inherits from: nsisupports last changed in gecko 1.9 (firefox 3) to implement this interface use net-content-sniffers category. see netwerk/build/nsnetcid.h about ns_content_sniffer_category. method overview acstring getmimetypefromcontent(in nsirequest arequest, [const,array,size_is(alength)] in octet adata, in unsigned long alength); methods getmimetypefromcontent() given a chunk of data, determines a mime type. information from the given request may be used in order to make a better decision. note: implementations should consider the request read-only. especially, they should not attempt to set t...
nsIContentView
lysis multi-process support framework. 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) see working with content views for details on how to use this api. note: currently, only <frame> and <iframe> elements are handled as content views. support for using this api for all scrollable elements is coming; see bug 618975 for details. method overview void scrollby(in float dxpx, in float dypx); void scrollto(in float xpx, in float ypx); void setscale(in float xscale, in float yscale); attributes attribute type description contentheight float read only. contentwidth float dimensions of scrolled content in chrome-docum...
nsIController
n false. onevent() implement this method to process the event with the specified name. void onevent( in string eventname ); parameters eventname the name of the event to process. supportscommand() implement this method to report whether or not the command with the specified name is supported. boolean supportscommand( in string command ); parameters command the name of the command to determine whether or not it is supported. return value true if the specified command is supported; otherwise false. see also nsicommandcontroller nsicontrollers xul tutorial/commands ...
nsICookiePermission
ookie is invoked, this is the current issession attribute of the cookie. cansetcookie may leave this value unchanged to preserve this attribute of the cookie. aexpiry when cansetcookie is invoked, this is the current expiry time of the cookie. cansetcookie may leave this value unchanged to preserve this attribute of the cookie. return value true if the cookie can be set. getoriginatinguri() determines the originating uri for a load given a channel, for third-party cookie blocking. this is done by leveraging the loadgroup of the channel to find the root content docshell, and the uri associated with its principal. if the root content docshell or its principal's uri cannot be obtained, this method will throw. nsiuri getoriginatinguri( in nsichannel achannel ); parameters achannel the channe...
nsICryptoHash
the hash algorithms supported are md2, md5, sha-1, sha-256, sha-384, and sha-512. ...
nsIDOMGeoPositionError
dom/interfaces/geolocation/nsidomgeopositionerror.idlscriptable please add a summary to this article. last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) inherits from: nsisupports attributes attribute type description code short numerical error code; see error constants for a complete list. read only. message domstring human readable error message. read only. gecko 1.9.2 note the message attribute was removed in gecko 1.9.2 (firefox 3.6). ...
nsIDOMMozNetworkStatsManager
read only. maxstorageage long long time in milliseconds recorded by the api until present time. all samples older than maxstorageage from now are deleted. read only. constants constant type description wifi long constant for wifi, set to 0 mobile long constant for m...
nsIDOMNSHTMLDocument
domstring commandid ); parameters commandid the name of the command to query. return value returns true if the command is supported and enabled, false otherwise. querycommandindeterm() boolean querycommandindeterm( in domstring commandid ); parameters commandid the name of the command to query. return value for stateful commands, returns true if the command is in an indeterminate state, false otherwise. for instance, if there is a selection and part of the selected text is bold, then then bold command is in an indeterminate state. querycommandstate() boolean querycommandstate( in domstring commandid ); parameters commandid the name of the command to query. return value for stateful commands, returns true if the command has is active, false otherwise. query...
nsIDOMOrientationEvent
dom/interfaces/events/nsidomorientationevent.idlscriptable please add a summary to this article. ...
nsIDOMParser
ncipal, documenturi, baseuri); principals, document and base uri note: this section covers changes introduced to domparser in gecko 1.9. (this section is only relevant to firefox extensions--not to web content.) to create a document, the parser needs to specify a principal (see security check basics), a base uri (see document.baseuriobject), and a documenturi. these values are automatically determined as defined below, but if you work with domparser from privileged code, you can override the defaults by providing arguments to the domparser constructor or calling parser.init(). usually you don't need to do that. if you come across a situation when these matter, feel free to ask questions in mozilla.dev.tech.dom and update this documentation to mention these cases. when a domparser is instant...
nsIDOMStorageEventObsolete
to notify interested parties about changes to the contents of a dom storage space; it is used for both session storage and local storage. 1.0 66 introduced gecko 1.8 obsolete gecko 2.0 inherits from: nsidomevent last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) when a dom storage event is received, the recipient can check its domain attribute to determine which domain's data store has changed. if the value of the domain attribute is "#session", then the session storage has changed. note: this interface describes the old, non-standard form of this event. you should use the nsidomstorageevent interface instead. method overview void initstorageevent(in domstring typearg, in boolean canbubblearg, in boolean cancelablearg, in domstring key...
nsIDOMWindowUtils
i float the dpi of the display. read only. doccharsetisforced boolean whether the charset of the window's current document has been forced by the user. cannot be accessed from unprivileged context (not content-accessible) read only. elementsrestyled read only unsigned long long the number of elements which have been restyled for the current document. keep in mind that during a restyle operation, an element may be restyled multiple times (for example, when an inline element contains blocks). this number also counts restyling of pseudo-elements and anonymous boxes. throws ns_error_not_available if the count can't be provided. focusedinputtype string the type of the currently-focused html <input> element, if one is focused. imageani...
nsIDOMXULElement
attribute if you set it to false. id domstring gets/sets the value of the element's id attribute. left domstring gets/sets the value of the element's left attribute. maxheight domstring gets/sets the value of the element's maxheight attribute. maxwidth domstring gets/sets the value of the element's maxwidth attribute. menu domstring gets/sets the value of the element's menu attribute. minheight domstring gets/sets the value of the element's minheight attribute. minwidth domstring gets/sets the value of the element's minwidth attribute. observes domstring gets/sets the value of the element's observes attribute. ordinal domstring gets/sets the value of the element's ordinal attribute. orient domstring gets/sets the value of the element's orient attribute. pack domstring ge...
nsIDownloadManager
2 the download failed due to error. download_canceled 3 the user canceled the download. download_paused 4 the download is currently paused. download_queued 5 the download is in the queue but is not presently downloading. download_blocked_parental 6 the download has been blocked, either by parental controls or the virus scanner determining that a file is infected and cannot be cleaned. download_scanning 7 the download is being scanned by a virus checking utility. download_dirty 8 a virus was detected in the download. the target will most likely no longer exist. download_blocked_policy 9 windows specific: request was blocked by zone policy settings. (see bug 416683) downlo...
nsIDragService
custom image may be specified using the aimage argument. if this is supplied, the aimagex and aimagey arguments specify the offset within the image where the cursor would be positioned. that is, when the image is drawn, it is offset up and left the amount so that the cursor appears at that location within the image. if aimage is null, aimagex and aimagey are not used and the image is instead determined from the source node adomnode, and the offset calculated so that the initial location for the image appears in the same screen position as where the element is located. the node must be within a document. currently, supported images are all dom nodes. if this is an html <image> or <canvas> element, the drag image is taken from the image data. if the element is in a document, it will be rendere...
nsIEditorSpellCheck
astring dictionary); void setfilter(in nsitextservicesfilter filter); void uninitspellchecker(); void updatecurrentdictionary(); methods addwordtodictionary() adds the specified word to the current personal dictionary. void addwordtodictionary( in wstring word ); parameters word the word to add to the current personal dictionary. canspellcheck() determines whether or not spell checking can be enabled. boolean canspellcheck(); parameters none. return value returns true if spell checking can be enabled. if there are no available dictionaries, the return value is false. 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. if the...
nsIFaviconService
t or if it has expired from the cache. if set, it will always try to reload the favicon. afaviconloadtype one of nsifaviconservice.favicon_load_private or nsifaviconservice.favicon_load_non_private to indicate that any network requests performed should act like ones from a private browsing context (ie. no history entries, only store in the temporary disk cache, etc.). this should be determined via privatebrowsingutils.iswindowprivate(somerelatedwindow) if the favicon may expose the user's private browsing data by performing a network request, otherwise favicon_load_non_private may be used. acallback optional from gecko 2.0 an nsifavicondatacallback. example var ioservice = components.classes["@mozilla.org/network/io-service;1"] .getservice(componen...
nsIFeedContainer
not all feeds have these, but all major feed formats have ids for each entry. link nsiuri a uri containing the primary link for the feed or entry. links nsiarray an array of all links for a feed or entry. rights nsifeedtextconstruct the feed or entry's rights or license text. title nsifeedtextconstruct the feed or entry's title. keep in mind that some feeds have no title, and some use markup in their titles, so be cautious when decoding this attribute. updated astring a string containing the date the feed or entry was last updated, in rfc822 form. this string is parsable by javascript and mail code. methods normalize() synchronizes a container's fields with its convenience attributes. void normalize(); paramete...
nsIFilePicker
inherits from: nsisupports last changed in gecko 17.0 (firefox 17.0 / thunderbird 17.0 / seamonkey 2.14) implemented by: @mozilla.org/filepicker;1. ...
nsIHTMLEditor
ationoffset, in boolean adeleteselection ); parameters ainputstring the string to be inserted. acontextstr context of insertion. ainfostr related info to ainputstring. aflavor transferable flavor, can be "" asourcedoc document where input was dragged from (may be null) adestinationnode location for insertion (such as when dropped) adestinationoffset used with adestnode to determine insert location. adeleteselection used with adestnode during drag&drop. insertlinkaroundselection() insert an link element as the parent of the current selection. void insertlinkaroundselection( in nsidomelement aanchorelement ); parameters aanchorelement isanonymouselement() boolean isanonymouselement( in nsidomelement aelement ); parameters aelement return value ...
nsIHTTPHeaderListener
ring headervalue); void statusline(in string line); methods newresponseheader() called for each http response header. note: you must copy the values of the params. void newresponseheader( in string headername, in string headervalue ); parameters headername headervalue statusline() called once for the http response status line. value does not include a terminating newline. note: you must copy this value. void statusline( in string line ); parameters line ...
nsIHapticFeedback
see press length constants for permitted values. ...
nsIHttpChannel
ilure if called during visitrequestheaders(). setreferrerwithpolicy() call this method to set the channel's referrer using the referrer policy indicated with one of the predefined constants. void setreferrerwithpolicy( in nsiuri areferrer, in unsigned long areferrerpolicy ); parameters areferrer the uri to base the referrer on. areferrerpolicy the referrer policy to use when determining the referrer to use. exceptions thrown ns_error_failure if called during visitrequestheaders(). setrequestheader() this method is called to set the value of a particular request header. this method allows, for example, the cookies module to add "cookie" headers to the outgoing http request. this method may only be called before the channel is opened. if avalue is empty and amerge is ...
nsIHttpUpgradeListener
asocketout the nsiasyncoutputstream object representing the out stream for sending data to the server over the socket. ...
nsIIDNService
if the result is ascii or ace encoded; otherwise it's false. return value the display formatted hostname. convertutf8toace() converts the specified hostname from utf-8 to ace format, using the idna "toascii" algorithm. acstring convertutf8toace( in autf8string input ); parameters input the hostname to convert to ace format. return value the ace encoded version of the hostname. isace() determines whether or not the specified hostname is ace encoded. boolean isace( in acstring input ); parameters input the string to check. return value returns true if the specified string is ace encoded; otherwise, returns false. normalize() performs the unicode normalization needed for hostnames in idn. this is useful if you need to normalize a hostname separately from converting it to display form...
nsIIdleService
er running this snippet, // you'll see a number around 1000 alerted. example 2 var idleservice = components.classes["@mozilla.org/widget/idleservice;1"] .getservice(components.interfaces.nsiidleservice) var idleobserver = { observe: function(subject, topic, data) { alert("topic: " + topic + "\ndata: " + data); } }; idleservice.addidleobserver(idleobserver, 60); // one minute // ... // don't forget to remove the observer using removeidleobserver! idleservice.removeidleobserver(idleobserver, 60); ...
nsIInstallLocation
e guid of the item. return value the location of the item. getstagefile() returns the most recently staged package (for example the last xpi or jar in a directory) for an item and removes items that do not qualify. nsifile getstagefile( in astring id ); parameters id the id of the staged package. return value an nsifile if the package exists otherwise null. itemismanagedindependently() determines whether or not an item's resources are managed by the extension system or by some other user or process. for example, items linked to by text links are managed by the user, and items linked to from registry install locations are usually managed by other applications or installers. boolean itemismanagedindependently( in astring id ); parameters id the guid of the item. return value true if ...
nsIJSID
string tostring(); attributes attribute type description id nsidptr read only. native code only! obsolete since gecko 1.9 the internal nsid. name string read only. the name of the jsid, if it was set. number string read only. the string representation of the internal nsid. valid boolean read only. returns true if the jsid has been initialised. methods equals() this method determines if this nsijsid has the same nsid as another nsijsid. boolean equals( in nsijsid other ); parameters other the other nsijsid to compare to. return value true if the nsijsid's are valid and have the same nsid, otherwise false. violates the xpcom interface guidelines getid() const nsid* getid(); parameters none. return value a pointer to the internal nsid structure. initialize() init...
nsIJetpack
used to specify filename and line number information for debugging purposes. void evalscript( in astring ascript ); parameters ascript the full contents of the script to evaluate in the jetpack process. createhandle() this creates an opaque handle that can transparently be exchanged between processes. nsivariant createhandle(); parameters none. return value the new handle. destroy() this terminates the jetpack process. void destroy(); parameters none. special messages if an exception goes uncaught in the jetpack process, it will be reported to the chrome process via a message with the name core:exception. the message comes with one argument, which represents the exception object that was thrown. warning: bug 589308 prevents this message from being sent in some situations. history see b...
nsILocalFile
in long mode); native code only! void reveal(); void setrelativedescriptor(in nsilocalfile fromfile, in acstring relativedesc); attributes attribute type description diskspaceavailable print64 the number of bytes available to non-superuser on the disk volume containing the nsilocalfile. read only. followlinks prbool determines whether or not the nsilocalfile will automatically resolve symbolic links. by default, this value is false on all non-unix systems. as of mozilla 1.7, this attribute is ignored on unix systems. persistentdescriptor acstring on some platforms, the value of nsifile.path may be insufficient to uniquely identify the file on the local file system. the persistent descriptor is...
nsILoginManagerCrypto
1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview astring decrypt(in astring ciphertext); astring encrypt(in astring plaintext); attributes attribute type description isloggedin boolean current login state of the token used for encryption. if the user is not logged in, performing a crypto operation will result in a master password prompt. read only. uibusy boolean true when a master password prompt is being displayed. read only. methods decrypt() decrypts the specified string, returning the plain text value. can throw if the user cancels entry of their master password, or if the ciphertext value can not be successfully decrypted (for example, if it was encrypted wit...
nsILoginManagerPrompter
's password. if the user consents, modifylogin() will be called. void prompttochangepassword( in nsilogininfo aoldlogin, in nsilogininfo anewlogin ); parameters aoldlogin the existing login (with the old password). anewlogin the new login. prompttochangepasswordwithusernames() ask the user if they want to change the password for one of multiple logins, when the caller can not determine exactly which login should be changed. if the user consents, modifylogin() will be called. 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. void prompttochangepasswordwithusernames( [array, size_is(count)] in nsilogininfo logins, in pruint32...
nsIMarkupDocumentViewer
ual text will be displayed without reordering. 1 - the default order for the charset 2 - logical order 3 - visual order. defaultcharacterset acstring forcecharacterset acstring fullzoom float the amount by which to scale all lengths. default is 1.0. hintcharacterset acstring hintcharactersetsource print32 minfontsize long the minimum font size to allow. note: this attribute was added late in the gecko 2.0 development cycle and was implemented by the nsimarkupdocumentviewer_mozilla_2_0_branch interface; it was merged into this interface in gecko 7.0. prevdoccharacterset acstring textzoom float the amount by which to scale all text. default is 1.0. ...
nsIMicrosummary
generator nsimicrosummarygenerator the generator that generates this microsummary. may need to be loaded. needsremoval boolean used when a site author has indicated that a microsummary (or an associated generator) will no longer be available. read only. pageuri nsiuri the uri of the page being summarized. read only. updateinterval long the minimum interval after which this microsummary would like to be refreshed or null if it doesn't care. read only. methods addobserver() add a microsummary observer to this microsummary. void addobserver( in nsimicrosummaryobserver observer ); parameters observer the microsummary observer to add. equals() microsummary equivalence test. microsummaries equal if they summarize the same ...
nsIMsgAccount
nsimsgaccount mailnews/base/public/nsimsgaccount.idlscriptable an account consists of an incoming server and one or more outgoing identities. inherits from: nsisupports last changed in gecko 1.7 method overview void addidentity(in nsimsgidentity identity); void clearallvalues(); void init(); void removeidentity(in nsimsgidentity identity); astring tostring(); attributes attribute type description defaultidentity nsimsgidentity identities nsisupportsarray read only. outgoing identity list (array of nsimsgidentity's) incomingserver nsimsgincomingserver incoming server stuff key acstring internal key identifying itself methods addidentity() adds a new identity to this account. void addidentity( in nsimsgidentity identity ); parameters identity th...
nsIMsgCustomColumnHandler
that the column should be sorted by. unsigned long getsortlongforrow(in nsimsgdbhdr ahdr); parameters ahdr the message's nsimsgdbhdr. return value the long value that sorting will be done with. isstring() boolean isstring(); parameters none. return value true if the column displays a string value. false otherwise. this affects whether getsortstringforrow or getsortlongforrow is used to determine the sort key for the column. it does not affect whether getcelltext vs. getimagesrc is used to determine what to display. see also extensions:thunderbird:creating_a_custom_column ...
nsIMsgDBHdr
the state of the database, although it is not saved until the database is committed. in clear, if you want to do a persistent change to a message header, such as marking it as read, or replied to, or whatever, you must do it through its corresponding nsimsgfolder (msghdr.folder) or nsimsgdatabase (msghdr.folder.msgdatabase). it is also mandatory to set msghdr.folder.msgdatabase = null after performing this kind of operations to prevent leaking. don't even think about using orflags and/or andflags. method overview astring getproperty(in string propertyname); void setproperty(in string propertyname, in astring propertystr); void setstringproperty(in string propertyname, in string propertyvalue); string getstringproperty(in string propertyname); uns...
nsIMsgDBView
opy commands. void docommandwithfolder(in nsmsgviewcommandtypevalue command, in nsimsgfolder destfolder); parameters command the nsmsgviewcommandtypevalue to perform. defined in the interface: nsmsgviewcommandtype. destfolder the folder to perform the command with. getcommandstatus() gets the status of a particular command. used by the thunderbird ui to determine if the command is available. void getcommandstatus(in nsmsgviewcommandtypevalue command, out boolean selectable_p, out nsmsgviewcommandcheckstatevalue selected_p); parameters command the nsmsgviewcommandtypevalue to perform. defined in the interface: nsmsgviewcommandtype. return values selectable_p the state of the command. true if it i...
nsIMsgDBViewCommandUpdater
alled when the displayed message has changed. void displaymessagechanged(in nsimsgfolder afolder, in astring asubject, in acstring akeywords ); parameters afolder the folder containing selected message. asubject the subject of the selected message. akeywords keywords associated with the selected message. updatenextmessageafterdelete() allows the backend to tell the front end to re-determine which message we should select after a delete or move void updatenextmessageafterdelete(); parameters none. ...
nsIMsgFilter
readonly attribute nsimsgfiltercustomaction customaction; methods addterm() void nsimsgfilter::addterm ( in nsmsgsearchattribvalue attrib, in nsmsgsearchopvalue op, in nsimsgsearchvalue value, in boolean booleanand, in acstring arbitraryheader ) getterm() void nsimsgfilter::getterm ( in long termindex, in nsmsgsearchattribvalue attrib, in nsmsgsearchopvalue op, in nsimsgsearchvalue value, out boolean booleanand, out acstring arbitraryheader ) appendterm() void nsimsgfilter::appendterm (in nsimsgsearchterm term) createterm() nsimsgsearchterm nsimsgfilter::createterm ( ) matchhdr() void nsimsgfilter::matchhdr ( in ...
nsIMsgFilterCustomAction
* * @param actionvalue the value entered. * @param actionfolder folder in the filter list * @param filtertype filter type (manual, offlinemail, etc.) * * @return errormessage a localized message to display if invalid * set to null if the actionvalue is valid */ autf8string validat...
nsIMsgIdentity
cclist astring draftfolder astring stationeryfolder astring showsavemsgdlg boolean directoryserver astring overrideglobalpref boolean autocompletetomydomain boolean if this is false, don't append the user's domain to an autocomplete address with no matches. valid boolean determines if the ui should use this identity and the wizard uses this to determine whether or not to ask the user to complete all the fields. smtpserverkey astring the preferred smtp server for this identity. if this is set, this is the smtp server that should be used for the message send. requestreturnreceipt boolean readonly: default request for return receipt option for t...
nsIMsgSearchSession
m header use. fes should not display the custom header dialog if custom headers are not supported. [noscript] boolean scopeusescustomheaders(in nsmsgsearchscopevalue scope, in voidptr selection, in boolean forfilters); parameters scope selection could be a folder or server based on scope forfilters isstringattribute() use this to determine if your attribute is a string attribute. boolean isstringattribute(in nsmsgsearchattribvalue attrib); parameters attrib addallscopes() add all scopes of a given type to the search. void addallscopes(in nsmsgsearchscopevalue attrib); parameters attrib search() void search(in nsimsgwindow awindow); parameters awindow interruptsearch() void interruptsearch(); ...
nsINavHistoryQuery
time boolean read only: whether or not, the corresponding end time is considered. hassearchterms boolean read only: whether or not, text search terms exists. hasuri boolean read only: whether or not, uri exists. maxvisits long set upper limits for how many times an item has been visited. the default value is "-1", and in that case all items are matched regardless of their visit count. minvisits long set lower limits for how many times an item has been visited. the default value is "-1", and in that case all items are matched regardless of their visit count. onlybookmarked boolean when set, returns only bookmarked items, when unset, returns anything. setting this is equivalent to listing all bookmark folders in the folders parameter. searchterms astring text search terms. t...
nsINavHistoryVisitResultNode
this interface provides the session id so that it's possible to group items from the same session together. ...
nsINetworkLinkService
e_* constants. read only. note: as of gecko 8.0, all operating systems currently return link_type_unknown. android support was backed out due to perceived security concerns, see bug 691054. as of gecko 28.0 android support is available again, see bug 939680. constants constant value description link_type_unknown 0 we were unable to determine the network connection type. link_type_ethernet 1 a standard wired ethernet connection. link_type_usb 2 a connection via a usb port. link_type_wifi 3 a connection via a wifi access point (ieee802.11). link_type_wimax 4 a connection via wimax (ieee802.16). link_type_2g 5 a '2g' mobile connection (for example, gsm, gprs, ed...
nsIPermission
e permission to set: allow, deny, or unknown (which is the default). see nsipermissionmanager.permission_type_constants for allowed values. read only. expiretime print64 the expiration time of the permission measured in milliseconds since 1970 jan 1 0:00:00. read only. expiretype pruint32 the expiration type of the permission: on session termination, on a specified time, or never. constants are defined in nsipermissionmanager.permission_expiration_constants. read only. host autf8string the host, that is uri, on which the permission is applied. read only. type acstring the type of permission: cookie, image, and so on. this is a case-sensitive string. this string is specified by the...
nsIPluginHost
proxy info for a given url. the caller is required to free the resulting memory with nsimalloc.free(). the result will be in the following format. "direct" -- no proxy "proxy xxx.xxx.xxx.xxx" -- use proxy "socks xxx.xxx.xxx.xxx" -- use socks mixed. for example "proxy 111.111.111.111;proxy 112.112.112.112", "proxy 111.111.111.111;socks 112.112.112.112".... which proxy/socks to use is determined by the plugin. void findproxyforurl( in string aurl, out string aresult ); parameters aurl aresult native code only!getplugin nsiplugin getplugin( in string amimetype ); parameters amimetype return value getplugincount() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) void getplugincount( out unsigned lon...
Component; nsIPrefBranch
ce. long getintpref( in string aprefname, [optional] in long adefaultvalue ); parameters aprefname the integer preference to get the value of. adefaultvalue requires gecko 54 optional - a default value to use if the preference does not exist (instead of throwing an exception). return value returns long - the value of the requested integer preference. getpreftype() called to determine the type of a specific preference. long getpreftype( in string aprefname ); parameters aprefname the preference to get the type of. return value returns long - a value representing the type of the preference. this value will be pref_string, pref_int, pref_bool, or pref_invalid. lockpref() called to lock a specific preference. locking a preference will cause the preference service t...
nsIPrefLocalizedString
es attribute type description data wstring provides access to string data stored in this property. methods setdatawithlength() used to set the contents of this object. void setdatawithlength( in unsigned long length, [size_is(length)] in wstring data ); parameters length the length of the string. this value should not include space for the null terminator, nor should it account for the size of a character. it should only be the number of characters for which there is space in the string. data the string data to be stored. tostring() used to retrieve the contents of this object into a wide string. note: this makes a copy of the string argument passed in. wstring tostring(); parameters none. return value returns wstring - the string co...
nsIProfile
urns an array of strings indicating the names of all the available profiles. void getprofilelist( out unsigned long length, [retval, array, size_is(length)] out wstring profilenames ); parameters length on return, contains the number of profiles in the profilenames array. profilenames on return, contains an array of all of the available profiles' names. profileexists() determine whether or not a profile with the specified name exists. boolean profileexists( in wstring profilename ); parameters profilename the name of the profile to look for. return value true if there is a profile with the specified name. renameprofile() renames an existing profile. void renameprofile( in wstring oldname, in wstring newname ); parameters oldname the name of th...
nsIProfileUnlocker
introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void unlock(in unsigned long aseverity); constants constant value description attempt_quit 0 politely ask the process currently holding the profile's lock to quit. force_quit 1 forcibly terminate the process holding the profile lock. methods unlock() tries to unlock the profile by attempting or forcing the process that currently holds the lock to quit. void unlock( in unsigned long aseverity ); parameters aseverity either attempt_quit or force_quit. see also profile management nsitoolkitprofileservice nsitoolkitprofile nsiprofilelock ...
nsIPropertyBag
sta, 7, etc. to do this use nsipropertybag: services.sysinfo.getproperty("version"); //output 5.1 services.sysinfo.getproperty("name"); //output windows_nt services.sysinfo.getproperty("arch"); //output x86 services.sysinfo.getproperty("haswindowstouchinterface"); //outputs false or true if windows touch is there consult the uxp repo (//github.com/realityripple/uxp/blob/master/xpcom/base/nssysteminfo.cpp) for the properties supported. also pay attention to their platform-specific meaning (e.g. on android there is version and kernel_version). ...
nsIProtocolHandler
t security context, so documents loaded using this protocol should inherit the security context of the document that loads them. uri_forbids_automatic_document_replacement 1<<5 "automatic" loads that would replace the document (such as a meta refresh, certain types of xlinks, and other non-user-triggered loads) are not allowed if the originating uri has this protocol flag. keep in mind that the decision of what constitutes an automatic load is made externally, by the caller of nsiscriptsecuritymanager.checkloaduri(). typically, this flag is used by protocols that show highly untrusted content in a viewing area that the user expects to have a lot of control over, such as an email reader. uri_loadable_by_anyone 1<<6 anyone can load the uris for this protocol; for...
nsIRequest
hen set, this flag indicates that no user-specific data should be added to the request when opened. this means that things like authorization tokens or cookie headers should not be added. note: this will prevent proxy authentications from working, so use this flag with caution. methods cancel() cancels the current request. this will close any open input or output streams and terminate any async requests. users should normally pass ns_binding_aborted, although other errors may also be passed. the error passed in will become the value of the status attribute. implementations must not send any notifications (for example via nsirequestobserver) synchronously from this function. similarly, removal from the load group (if any) must also happen asynchronously. requests that use ...
nsIScriptableUnicodeConverter
rset string current character set. throws ns_error_uconv_noconv if the requested charset is not supported. methods convertfromunicode() converts the data from unicode to one charset. returns the converted string. after converting, finish should be called and its return value appended to this return value. acstring convertfromunicode( in astring asrc ); finish() returns the terminator string. should be called after convertfromunicode() and appended to that function's return value. acstring finish(); converttounicode() converts the data from one charset to unicode. astring converttounicode( in acstring asrc ); convertfrombytearray() converts an array of bytes to a unicode string. astring convertfrombytearray( [const,array,size_is(acount)] in octet adata, in u...
nsISearchEngine
f null, will default to "text/html". purpose [optional] a string meant to indicate the context of the search request. this allows the search service to provide a different nsisearchsubmission depending on e.g. where the search is triggered in the ui. possible values depend on the application's installed search engines. return value an nsisearchsubmission supportsresponsetype() determines whether the engine can return responses in the given mime type. boolean supportsresponsetype( in astring responsetype ); parameters responsetype the mime type to check for. return value returns true if the engine spec has a url with the given responsetype, false otherwise. see also nsisearchsubmission nsibrowsersearchservice ...
nsISessionStartup
ession. recover_session 1 the last session crashed. it will either be restored or about:sessionrestore will be displayed. resume_session 2 the previous session should be restored at startup. defer_session 3 the previous session is viable but shouldn't be restored without explicit action (with the exception of app tabs, which are always restored in this case). methods dorestore() determines whether or not there is a session to restore. boolean dorestore(); parameters none. return value true if the session should be restored, otherwise false. ...
nsISessionStore
use only by the browser; extensions shouldn't call it. void init( in nsidomwindow awindow ); parameters awindow the window for which to initialize the service. persisttabattribute() sets the name of a tab attribute to be saved and restored for all xul tabs. note: at present, there's no way to pick and choose tabs to set persistent attributes for. this method affects all tabs indiscriminately. void persisttabattribute( in astring aname ); parameters aname the name of the attribute to be saved and restored for all tabs. restorelastsession() restore the previous session if possible. this will not overwrite the current session. instead the previous session will be merged into the current session. current windows will be reused if they were windows that pinned tabs were p...
nsISimpleEnumerator
. must be preceded by a call to hasmoreelements() which returns pr_true. this method is generally called within a loop to iterate over the elements in the enumerator. nsisupports getnext(); parameters none. return value ns_ok if the call succeeded in returning a non-null value through the out parameter. ns_error_failure if there are no more elements to enumerate. hasmoreelements() called to determine whether or not the enumerator has any elements that can be returned via getnext(). this method is generally used to determine whether or not to initiate or continue iteration over the enumerator, though it can be called without subsequent getnext() calls. does not affect internal state of enumerator. boolean hasmoreelements(); parameters none. return value pr_true if there are remaining element...
nsISpeculativeConnect
nsiinterfacerequestor acallbacks, in nsieventtarget atarget); methods speculativeconnect() call this method to hint to the networking layer that a new transaction for the specified uri is likely to happen soon. the code implementing this method may use this information to start a tcp and/or ssl level handshake for that resource immediately so that it is ready (or at least in the process of becoming ready) when the transaction is actually submitted. no obligation is taken on by the implementer, nor is the submitter obligated to actually open the new channel. void speculativeconnect( in nsiuri auri, in nsiinterfacerequestor acallbacks, in nsieventtarget atarget ); parameters auri the uri of the hinted transaction. acallbacks any security callbacks for use with ssl for interfaces such...
nsIStackFrame
ckframe read only. filename string filename location. this is the location that caused the error, which may or may not be a source file location. for example, standard language errors would generally have the same location as their top stack entry. file parsers may put the location of the file they were parsing, and so forth. null indicates "no data" read only. language pruint32 see nsiprogramminglanguage for a list of language constants. read only. languagename string see nsiprogramminglanguage for a list of language constants. read only. linenumber print32 valid line numbers begin at '1'. '0' indicates unknown. read only. name string the name of the function at this point in the stack. read only. sourceline string the location of this function in filename read only. example t...
nsIStringEnumerator
the enumerator. the "next" element is the first string upon the first call. must be preceded by a call to hasmoreelements() which returns pr_true. this method is generally called within a loop to iterate over the strings in the enumerator. astring getnext(); parameters none. return value the next string in the enumerator. throws an exception if there are no more strings. hasmore() called to determine whether or not the enumerator has any strings that can be returned via getnext(). this method is generally used to determine whether or not to initiate or continue iteration over the enumerator, though it can be called without subsequent getnext() calls. does not affect internal state of enumerator. boolean hasmore(); parameters none. return value true if there are remaining strings in the enum...
nsISupports proxies
re two possibilities. first, you may know which event queue that you are interested in. in this case, just simply use it. in most cases, you will want the main ui thread (aka the primordial thread). if this is the case, you can simply pass nsnull as the event queue. you may also use the defined flags which are defined in xpcom/threads/nsieventqueueservice.h#44. there is also logic that will determine if the caller is on the destination thread. if this is true, i will not call via proxy, but rather invoke the method directly which is an optimization. this detection will only be used if you are using a proxy created with the proxy_sync flag. example usage nsresult rv = ns_ok; nscomptr<nsiproxyobjectmanager> piproxyobjectmanager(do_getservice("@mozilla.org/xpcomproxy;1", &rv)); if(ns_failed(...
nsISyncMessageSender
nt. for example, a child-process message manager will send messages that are only delivered to its one parent-process message manager. see message manager interfaces for more details on the distinction between message senders and message broadcasters. both sendsyncmessage() and sendrpcmessage() will block until a reply is received, but they may be temporarily interrupted to process an urgent incoming message (such as a cpow request). methods jsval sendsyncmessage([optional] in astring messagename, [optional] in jsval obj, [optional] in jsval objects, [optional] in nsiprincipal principal); jsval sendrpcmessage([optional] in astring messagename, [optional] in jsval obj, ...
nsITaskbarPreview
attribute type description active boolean indicates whether or not the preview is marked as active (currently selected) in the taskbar. controller nsitaskbarpreviewcontroller the controller for this preview. the controller provides the behavior and appearance for the taskbar preview, and is responsible for determining the size and contents of the preview, which buttons are displayed, and how the application responds to user actions on the preview. the controller is not allowed to be null. note: neither nsitaskbartabpreview or nsitaskbarwindowpreview makes full use of the controller; see the documentation for each interface for details on which controller methods are used. tooltip ...
nsITelemetry
lag indicating whether telemetry is recording pre-release data. does not indicate whether telemetry will send any data. that is governed by user preference and other mechanisms. histogramsnapshots jsval an object containing a snapshot from all of the currently registered histograms. { name1: {data1}, name2:{data2}...} where data consists of the following properties: min - minimal bucket size max - maximum bucket size histogram_type - histogram_exponential or histogram_linear counts - an array representing the values of buckets in the histogram. ranges - an array with corresponding bucket sizes. sum - sum of the counts array. static - true for histograms defined in histograms.json, false for ones defined with newhistogram(). ...
nsIThread
thread will be shut down and will no longer be available to receive events. void shutdown() parameters none. exceptions thrown ns_error_unexpected shutdown() was erroneously called from within the thread itself, the thread was not created with the thread manager's nsithreadmanager.newthread() method, or the thread is already in the process of being shut down. haspendingevents() determines whether or not the thread has events that are ready to be processed. note: this method must be called from within the thread itself, and not from another thread. boolean haspendingevents() parameters none. return value true if there are pending events at the time the function was called. since other threads may add events to the current thread, it's possible that by the time this method ...
nsIThreadEventFilter
the nsithreadeventfilter interface may be implemented to determine whether or not an event may be accepted by a nested event queue; see nsithreadinternal.pusheventqueue() for more information. you should implement this interface and its acceptevent() method, then pass the object implementing it as the filter. xpcom/threads/nsithreadinternal.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) inherits from: nsisupports method overview boolean acceptevent(in nsirunnable event);violates the xpcom interface guidelines methods violates the xpcom interface guidelines acceptevent() this method is called to determine whether or not an event may be accepted by a nested event queue. (see nsithreadinternal.pusheventqueue()) ...
nsITreeBoxObject
ut long x, out long y, out long width, out long height); parameters row the index of the row col the nsitreecolumn element the pseudoelement. this can have values of "cell", "twisty", "image", and "text". returns x the x coordinate col the y coordinate. width the width of the element height the height of the element iscellcropped() determine if the text of a cell is being cropped or not. boolean iscellcropped(in long row, in nsitreecolumn col); parameters row the index of the row col the nsitreecolumn rowcountchanged() notify the tree that the number of rows changed. the view is responsible for calling this notification method when rows are added or removed. for non-contiguous additions/removals, this method shou...
nsIURIFixupInfo
the fixed-up original input, *never* using a keyword search. (may be null if the original input was broken as a url, e.g. "foo bar"!). read only. keywordprovidername astring the keyword search provider name expected to provide a keyword search; empty string if no keyword search is performed. read only. keywordassent astring the keyword used for the search (post trimming etc.); empty string if no keyword search is performed. read only. fixupchangedprotocol boolean if we changed the protocol; instead of using one raw from the input. read only. fixupcreatedalternateuri boolean if we created an alternative uri. potentially adding a prefix and/or suffix; set by the browser.fixup.alternate.prefix and .suffix prefs, their defaults "www." ...
nsIURL
he "?") of the url. if there isn't one, an empty string is returned. some characters may be escaped. ref autf8string reference portion (the part after the "#") of the url. if there isn't one, an empty string is returned. some characters may be escaped. methods getcommonbasespec() this method takes a uri and compares the two. the common uri portion is returned as a string. the minimum common uri portion is the protocol, and any of these if present: login, password, host and port if no commonality is found, "" is returned. if they are identical, the whole path with file/ref/etc. is returned. for file uris, it is expected that the common spec would be at least "file:///" since '/' is a shared common root. examples: this.spec auritocompare.spec result ...
nsIURLParser
out parameters of the methods are all optional (that is the caller may pass-in a null value if the corresponding results are not needed). signed out parameters may hold a value of -1 if the corresponding result is not part of the string being parsed. the parsing routines attempt to be as forgiving as possible. parseauthority() breaks the...
nsIUTF8StringEnumerator
ore(), which returns pr_true. this method is generally called within a loop to iterate over the strings in the enumerator. autf8string getnext(); parameters none. return value the next string in the enumerator. throws an exception if there are no more strings. hasmore() reports whether or not the enumerator has any strings that can be returned via getnext(). this method is generally used to determine whether or not to initiate or continue iteration over the enumerator, athough it can be called without subsequent getnext() calls. calling this method doesn't affect the internal state of the enumerator. boolean hasmore(); parameters none. return value true if there are remaining strings in the enumerator, otherwise false. ...
nsIUpdateChecker
ean force ); parameters listener an object implementing nsiupdatechecklistener to be notified of the results of an update check. force if true, the update checker checks for updates, regardless of the current value of the user's update settings. this is used by any user interface that offers the user the opportunity to check for updates immediately. the force option doesn't work if the system administrator has locked the app.update.enabled preference. stopchecking() ends any pending update check. void stopchecking( in unsigned short duration ); parameters duration one of the constants indicating the set of updates to stop. see also nsiupdatepatch nsiupdate nsiupdatechecklistener nsiapplicationupdateservice nsiupdatemanager nsiupdateprompt nsiupdatetimermanager ...
nsIUpdatePatch
1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview nsidomelement serialize(in nsidomdocument updates); attributes attribute type description finalurl astring the final url this patch was being downloaded from. hashfunction astring the hash function to use when determining the integrity of the patch file. hashvalue astring the value of the hash function named in hashfunction that should be computed if the file is not corrupt. selected boolean true if this patch is currently selected as the patch to be downloaded and installed for this update transaction. false if another update is selected. size unsigned long the size of the patch file in bytes. state as...
nsIUpdateTimerManager
in nsitimercallback callback, in unsigned long interval ); parameters id an id used to identify the timer interval; used for persistence. callback an nsitimercallback object that is notified when the interval expires. interval the length of time, in seconds, until the timer should fire. remarks note that the timer is not precise, and that the default minimum interval is 2 minutes. in order to avoid having to instantiate a component to call the registertimer() method, the component can instead register an update-timer category with comma-separated values as a single string representing the timer, like this: _xpcom_categories: [{ category: "update-timer", value: "contractid," + "method," + ...
nsIUploadChannel
...
nsIUploadChannel2
eam, in acstring acontenttype, in long long acontentlength, in acstring amethod, in boolean astreamhasheaders ); parameters astream the stream to be uploaded by this channel. acontenttype this value will replace any existing content-type header on the http request, regardless of whether or not its empty. acontentlength a value of -1 indicates that the length of the stream should be determined by calling the stream's available method. amethod the http request method to set on the stream. astreamhasheaders true if the stream already contains headers for the http request. ...
nsIWebBrowserChrome
chrome_scrollbars 512 value for the chromeflags attribute. chrome_titlebar 1024 value for the chromeflags attribute. chrome_extra 2048 value for the chromeflags attribute. chrome_with_size 4096 specifically for use with nsiwindowcreator. chrome_with_position 8192 specifically for use with nsiwindowcreator. chrome_window_min 16384 represent special cases. chrome_window_popup 32768 represent special cases. chrome_window_raised 33554432 represent special cases. chrome_window_lowered 67108864 represent special cases. chrome_center_screen 134217728 represent special cases. chrome_dependent 268435456 make the new window dependent on the paren...
nsIWebBrowserChrome3
lscriptable an extension to nsiwebbrowserchrome2. 1.0 66 introduced gecko 2.0 inherits from: nsiwebbrowserchrome2 last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview astring onbeforelinktraversal(in astring originaltarget, in nsiuri linkuri, in nsidomnode linknode, in prbool isapptab); methods onbeforelinktraversal() determines the appropriate target for a link. astring onbeforelinktraversal( in astring originaltarget, in nsiuri linkuri, in nsidomnode linknode, in prbool isapptab ); parameters originaltarget the original link target. linkuri link destination uri. linknode link dom node. isapptab whether or not the link is in an application tab. return value a new link target,...
nsIWebProgressListener
to indicate the start and stop of that activity. for example, in the case of navigation within a single frame of a html frameset, a nsiwebprogresslistener instance attached to the nsiwebprogress of the frameset window will receive onstatechange() calls with the state_is_network flag set to indicate the start and stop of said navigation. in other words, an observer of an outer window can determine when activity, that may be constrained to a child window or set of child windows, starts and stops. state_is_window 0x00080000 this flag indicates that the state transition corresponds to the start or stop of activity in the indicated nsiwebprogress instance. this flag is accompanied by either state_start or state_stop, and it may be combined with other state type flags. ...
nsIWebSocketChannel
reserved and not used. 1000 close_normal normal closure; the connection successfully completed whatever purpose for which it was created. 1001 close_going_away the endpoint is going away, either because of a server failure or because the browser is navigating away from the page that opened the connection. 1002 close_protocol_error the endpoint is terminating the connection due to a protocol error. 1003 close_unsupported the connection is being terminated because the endpoint received data of a type it cannot accept (for example, a text-only endpoint received binary data). 1004 close_too_large the endpoint is terminating the connection because a data frame was received that is too large. 1005 close_no_sta...
nsIWinAppHelper
by "xre/app-info". method overview void fixreg(); obsolete since gecko 1.9 void postupdate(in nsilocalfile logfile); obsolete since gecko 1.9.2 attributes attribute type description usercanelevate boolean read only. returns true only if all the following conditions are all true at once: the operating system is at least windows vista user account control is enabled the user is an administrator the application is not already running with elevated permissions otherwise it returns false. methods fixreg() obsolete since gecko 1.9 (firefox 3) invokes helper.exe with the /fixreg parameter. note that this parameter was never actually supported. void fixreg(); parameters none. postupdate() obsolete since gecko 1.9.2 (firefox 3.6 / thunde...
nsIWindowMediator
velbelow. native code only!unregisterwindow remove the window from the list of known windows. listeners (see addlistener()) will be be notified through their onclosewindow method. void unregisterwindow( in nsixulwindow awindow ); parameters awindow the window to remove. native code only!updatewindowtimestamp call this method when a window gains focus. it's a primitive means of determining the most recent window. it's no longer necessary and it really should be removed. void updatewindowtimestamp( in nsixulwindow awindow ); parameters awindow the window which has gained focus. native code only!updatewindowtitle call this method when a window's title changes. listeners (see addlistener()) will be notified through their onwindowtitlechange method. void updatewindowtit...
nsIWindowWatcher
re opened, guaranteeing that each will be visited exactly once. nsisimpleenumerator getwindowenumerator(); parameters none. return value an nsisimpleenumerator which will itself return nsisupports objects which can be nsisupports.queryinterface() (queryinterfaced) to an nsidomwindow. openwindow() creates a new window. it will automatically be added to our list. note: this method may examine the javascript context stack for purposes of determining the security context to use for the search for a given window named aname. note: this method will try to set the default charset for the new window to the default charset of aparent. this is not guaranteed, however. note: this method may dispatch a "toplevel-window-ready" notification via nsiobserverservice if the window did not ...
nsIWorkerScope
message, [optional] in nsiworkermessageport amessageport); void close(); attributes attribute type description onclose nsidomeventlistener a listener object to be called when the worker stops running. onmessage nsidomeventlistener a listener object to be called when a message is posted on the port. the message is in the event's data member. methods close() allows the worker to terminate itself. if a listener has been established by setting the value of the onclose attribute, it gets called. void close(); parameters none. postmessage() posts a message to the scope's parent worker object. void postmessage( in domstring amessage, in nsiworkermessageport amessageport optional ); parameters amessage the message to post. it will be stored as the data member in the event. ame...
nsIXFormsModelElement
exception if there is no matching instance data. rebuild() signals the xforms processor to rebuild any internal data structures used to track computational dependencies within the given xforms model. void rebuild(); parameters none. recalculate() signals the xforms processor to perform a full recalculation of the given xforms model. note: script invocation is not necessarily equivalent to performing the recalculate action handler. though the script is assumed to have modified instance data prior to invoking recalculate, the dom mutations are not cached. thus, a full recalculation is necessary to ensure the proper changes are effected throughout the xforms model. void recalculate(); parameters none. refresh() signals the xforms processor to perform a full refresh of form controls bound to i...
nsIXULBrowserWindow
n for xulbrowserwindow for details. method overview astring onbeforelinktraversal(in astring originaltarget, in nsiuri linkuri, in nsidomnode linknode, in prbool isapptab); void setjsdefaultstatus(in astring status); void setjsstatus(in astring status); void setoverlink(in astring link, in nsidomelement element); methods onbeforelinktraversal() called before traversing a link to determine the appropriate target into which to load the link. this may be used, for example, to redirect links into new tabs or windows when it's not desirable to replace the content in the current tab (such as when the link is clicked in an app tab). astring onbeforelinktraversal( in astring originaltarget, in nsiuri linkuri, in nsidomnode linknode, in prbool isapptab ); parameters originaltarg...
nsIXULRuntime
1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) implemented by: @mozilla.org/xre/app-info;1. ...
nsIZipEntry
or the item. the possible values and their meanings are defined in the zip file specification at zip application note support. read only. crc32 unsigned long the crc-32 hash of the file in the entry. read only. isdirectory boolean true if the name of the entry ends with '/' and false otherwise. read only. issynthetic boolean use this attribute to determine whether this item is an actual zip entry or is one synthesized for part of a real entry's path. a synthesized entry represents a directory within the zip file which has no corresponding entry within the zip file. for example, the entry for the directory foo/ in a zip containing exactly one entry for foo/bar.txt is synthetic. if the zip file contains an actual entry for a directory, this attribut...
nsMsgSearchAttrib
defined in comm-central/ mailnews/ base/ search/ public/ nsmsgsearchcore.idl typedef long nsmsgsearchattribvalue; /** * definitions of search attribute types. the numerical order * from here will also be used to determine the order that the * attributes display in the filter editor. */ [scriptable, uuid(a83ca7e8-4591-4111-8fb8-fd76ac73c866)] interface nsmsgsearchattrib { const nsmsgsearchattribvalue custom = -2; /* a custom term, see nsimsgsearchcustomterm */ const nsmsgsearchattribvalue default = -1; const nsmsgsearchattribvalue subject = 0; /* mail and news */ const nsmsgsearchattribvalue sender = 1; const nsmsgsearchattribvalue body = 2; const nsmsgsearchattribvalue date = 3; const nsmsgsearchattribvalue priority = 4; /* mail only */ co...
NS_ASSERTION
true. in a debug build the failure text is written to console (stderr), into the nspr debug log, and on windows a dialog box is opened. the behavior of an assertion failure can be controlled using the xpcom_debug_break environment variable. an assertion failure should be thrown on critical program errors only. a triggered assertion failure is equivalent to crashing in tinderbox tests. note on terminology: "assertion" is the condition to test. there is always an assertion in ns_assertion; it is the first argument. only if the assertion evaluates to false is there an "assertion failure", which is thrown. the phrase "throwing an assertion" makes no sense. syntax ns_assertion(expressiontotest, "error text"); see also ns_abort_if_false ns_precondition ns_postcondition disabling assertion dialo...
XPCOM Interface Reference by grouping
nsiwintaskbar nsialertsservice nsiwebprogress nsiwebprogresslistener nsiwebprogresslistener2 update nsiupdate nsiupdatechecker nsiupdatechecklistener nsiupdateitem nsiupdatemanager nsiupdatepatch nsiupdateprompt nsiupdatetimermanager nsiprogramminglanguage thunderbird credentials nsimsgaccountmanagerextension element nsieditormailsupport message nsidbchangeannouncer nsidbchangelistener nsimessenger nsimsgcompfields nsimsgcustomcolumnhandler nsimsgdatabase nsimsgdbhdr nsimsgdbview nsimsgdbviewcommandu...
NS_CStringAppendData
lude "nsstringapi.h" nsresult ns_cstringappenddata( nsacstring& astring, const char* adata, pruint32 adatalength = pr_uint32_max ); parameters astring [in] a nsacstring instance to be modified. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null-terminated. return values the ns_cstringappenddata function returns ns_ok if successful. otherwise, it returns an error code. remarks this function is defined inline as a wrapper around ns_cstringsetdatarange. example nscstringcontainer str; ns_cstringcontainerinit(str); ns_cstringsetdata(str, "hello"); ns_cstringappenddata(str, " world"); const c...
NS_CStringGetData
« xpcom api reference summary the ns_cstringgetdata function gives the caller read access to the string's internal buffer. #include "nsstringapi.h" pruint32 ns_cstringgetdata( const nsacstring& astring, const char** adata, prbool* aterminated = nsnull ); parameters astring [in] a nsacstring instance to inspect. adata [out] a const pointer to the string's internal buffer. aterminated [out] this optional result parameter indicates whether or not adata is null-terminated. it may be null if the caller is not interested in this information. return values the ns_cstringgetdata function returns the length of adata, measured in storage units (bytes). example code // count the number of times a particular character appears in a string. pruint32 countchar(const ns...
NS_CStringInsertData
ruint32 adatalength = pr_uint32_max ); parameters astring [in] a nsacstring instance to be modified. aoffset [in] an offset into the string's internal buffer specifying where to place the given characters. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. return values the ns_cstringinsertdata function returns ns_ok if successful. otherwise, it returns an error code. remarks this function is defined inline as a wrapper around ns_cstringsetdatarange. example code nscstringcontainer str; ns_cstringcontainerinit(str); ns_cstringsetdata(str, "hello"); ns_cstringinsertdata(str, 5, " world"...
NS_CStringSetData
i. #include "nsstringapi.h" nsresult ns_cstringsetdata( nsacstring& astring, const char* adata, pruint32 adatalength = pr_uint32_max ); parameters astring [in] a nsacstring instance to modify. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null-terminated. return values the ns_cstringsetdata function returns ns_ok if successful. otherwise, it returns an error code. example nscstringcontainer str; rv = ns_cstringcontainerinit(str); if (ns_succeeded(rv)) { rv = ns_cstringsetdata(str, "hello world"); if (ns_succeeded(rv)) { // now, pass |str| to some function expecting a |const nsacstr...
NS_CStringSetDataRange
nsacstring instance to modify. acutstart [in] the starting index of the section to replace, measured in storage units. acutlength [in] the length of the section to replace, measured in storage units. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. return values the ns_cstringsetdatarange function returns ns_ok if successful. otherwise, it returns an error code. example // replace all occurances of |matchval| with |newval| void replacesubstring(nsacstring& str, const nsacstring& matchval, const nsacstring& newval) { const char* sp, *mp, *...
NS_StringAppendData
ringapi.h" nsresult ns_stringappenddata( nsastring& astring, const prunichar* adata, pruint32 adatalength = pr_uint32_max ); parameters astring [in] a nsastring instance to be modified. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. return values the ns_stringappenddata function returns ns_ok if successful. otherwise, it returns an error code. remarks this function is defined inline as a wrapper around ns_stringsetdatarange note: gcc requires the -fshort-wchar option to compile this example since prunichar is an unsigned short. this example should compile by default un...
NS_StringContainerInit
n values the ns_stringcontainerinit function returns ns_ok if successful. otherwise, it returns an error code. remarks the nsstringcontainer structure has unspecified size and layout. its members may not be accessed directly. after a nsstringcontainer object has been initialized, it may be used as an ordinary nsastring object. the internal buffer allocated by a nsstringcontainer is always null-terminated. with ns_stringcontainerinit, the coder is required to call ns_stringcontainerfinish when done with the nsstringcontainer object. therefore, it is generally better to use nsembedstring, to instantiate a nsastring object, since it automatically releases allocated memory when the object goes out of scope. example code nsstringcontainer str; if (ns_succeeded(ns_stringcontainerinit(str))) {...
NS_StringGetData
« xpcom api reference summary the ns_stringgetdata function gives the caller access to the string's internal buffer. this is a low-level api. #include "nsstringapi.h" pruint32 ns_stringgetdata( const nsastring& astring, const prunichar** adata, prbool* aterminated ); parameters astring [in] a nsastring instance to inspect. adata [out] a const pointer to the string's internal buffer. aterminated [out] this optional result parameter indicates whether or not adata is null-terminated. return values the ns_stringgetdata function returns the length of adata, measured in storage units (bytes). example code pruint32 countchar(const nsastring& str, prunichar c) { const prunichar* data; pruint32 len = ns_stringgetdata(str, &data); pruint32 count = ...
NS_StringInsertData
adatalength = pr_uint32_max ); parameters astring [in] a nsacstring instance to be modified. aoffset [in] an offset into the string's internal buffer specifying where to place the given characters. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. return values the ns_stringinsertdata function returns ns_ok if successful. otherwise, it returns an error code. remarks this function is defined inline as a wrapper around ns_stringsetdatarange . note: gcc requires the -fshort-wchar option to compile this example since prunichar is an unsigned short. this example should compile by default ...
NS_StringSetData
#include "nsstringapi.h" nsresult ns_stringsetdata( nsastring& astring, const prunichar* adata, pruint32 adatalength = pr_uint32_max ); parameters astring [in] a nsastring instance to modify. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. return values the ns_stringsetdata function returns ns_ok if successful. otherwise, it returns an error code. example code nsstringcontainer str; rv = ns_stringcontainerinit(str); if (ns_succeeded(rv)) { rv = ns_stringsetdata(str, "hello world"); if (ns_succeeded(rv)) { // now, pass |str| to some function expecting a |...
NS_StringSetDataRange
g [in] a nsastring instance to modify. acutstart [in] the starting index of the section to replace, measured in storage units. acutlength [in] the length of the section to replace, measured in storage units. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. return values the ns_stringsetdatarange function returns ns_ok if successful. otherwise, it returns an error code. example code // replace all occurances of |matchval| with |newval| void replacesubstring(nsastring& str, const nsastring& matchval, const nsastring& newval) { const prunich...
nsMsgNavigationType
the nsmsgnavigationtype interface contains constants used for message navigation in thunderbird. for example to move forward a message, you would call: // assuming gdbview is a global nsimsgdbview var resultid = new object(); var resultindex = new object(); var threadindex = new object(); gdbview.viewnavigate(components.interfaces.nsmsgnavigationtype.nextmessage, resultid, resultindex, threadindex, true); the nsmsgnavigationtype interface is defined as a global variable in thunderbird: var nsmsgviewcommandtype = components.interfaces.nsmsgviewcommandtype; mailnews/base/public/nsimsgdbview.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) constants name value description firstmessage 1 go to the first message in t...
nsStaticModuleInfo
summary this data structure is used by ns_initxpcom3 to specify static xpcom modules. #include "nsxpcom.h" struct nsstaticmoduleinfo { const char* name; nsgetmoduleproc getmodule; }; members name this member provides the name of the module as a null-terminated, ascii-valued character array. getmodule this member provides a function pointer of type nsgetmoduleproc that returns a nsimodule instance. ...
XPCOM Thread Synchronization
this article covers the api of mozilla synchronization only. for a higher-level introduction to thread synchronization, see introduction_to_nspr. ...
Troubleshooting XPCOM components registration
onents that fail to load will print an error to the error console. chrome errors must be enabled. if the error appears, you can use nspr logging to see additional information about the failure by running firefox from a command prompt: rem close all firefox windows! set nspr_log_modules=nsnativemoduleloader:5 set nspr_log_file=c:\path\to\logfile "c:\program files\mozilla firefox\firefox.exe" examining this log for warning and errors may provide valuable clues why the component failed to load. if using firefox 4 / xulrunner 2.0, make sure that your extension is unpacked and you declared the binary component in your chrome.manifest. see xpcom changes in gecko 2.0 parsing errors in javascript components the most common reason for components written in javascript to fail is that there are pa...
Status, Recent Changes, and Plans
tion at the top so that checking for recent changes will be easy. recent changes to nscomptr most recent first made == and != between an nscomptr and a raw pointer (or a literal 0 or nsnull) work correctly on all compilers. see bug 65664. made getter_addrefs( nscomptr& ) apply the same type-safety check that the simple assignment forms do. added do_createinstance. added do_getservice. eliminated the need to cast getter_addrefs when an nsisupports** is needed. relaxed the invariant for nscomptr<nsisupports>, so that it is now a pointer to any xpcom interface. added do_queryreferent to make using nsiweakreferences easier. plans for nscomptr bug 59212: as soon as we test on more compilers, start recommending already_addrefed as a function result. bug 59414: making operator& priv...
Using nsIDirectoryService
will allow you to get(), set(), define(), and undefine() nsifile. getting a location: most developers need to find where a file or directory is located. with nsdirectoryservice, there are two steps involved. first, you must know what the string key (or property) is that refers to this locations. header files containing known keys are listed in the known locations section of this document. bear in mind that this list is not static. components can add and remove locations at their will. second, you must acquire the implementation and call get() passing the known string key. in the example below, prop is a string that references your requested file locations. c++ nscomptr<nsifile> dir; ns_getspecialdirectory(prop, getter_addrefs(dir)); if (!dir) return ns_error_failure; jav...
Working with Multiple Versions of Interfaces
if you are lucky enough with your api's this technique may work without further ado. we are not so lucky. the realist's solution to make sure we call the right methods of the right interfaces we need to have two versions of both the nsiaccessibledocument and nsiaccessibleretrieval interfaces at our fingertips. i called my old ones: nsiaccessibleretrieval_old.h and nsiaccessibledocument_old.h. mine date back to august of 2006, which is when i first built the lizard. to get these four files to co-exist together peacefully i had to resort to some preprocessor magic and an ugly hack. maybe the ugly hack can be replaced by even more preprocessor magic, but not today. lets do the magic first, then describe the ugly hack. to include both retrieval interfaces (and remember the old iid without hav...
Working with out parameters
meaning that they act as "return values" for this method, and are changed during the method call. these are so-called out parameters. usage in order to use such a method from javascript via xpconnect, you have to follow a specific rule. to get at the out parameters, you have to pass in an object. after the call, this object will have a new property called value, which contains the out values. assuming you have an object called transferable, you would invoke gettransferdata() as follows: var adata = {}; var adatalen = {}; transferable.gettransferdata("text/unicode", adata, adatalen); var data = adata.value; var datalen = adatalen.value; as you can see, after the call to gettransferdata(), the out values are then contained in the value properties of adata and adatalen. implementation w...
XPCOM category image-sniffing-services
types would not be correctly displayed. in firefox 3, a new xpcom category was added in bug 391667 to allow "third-party" xpcom components to identify images based on their content. if mozilla's built-in image code cannot identify an image, then any xpcom components implementing the nsicontentsniffer interface may register under the "image-sniffing-services" category, and will be queried to determine the mime type of the image being downloaded. note: this category was removed. see bug 813787 - remove support for image-sniffing-services. ...
wrappedJSObject
calling queryinterface on the wrapper works, because it is defined in the nsisupports interface, and the wrapper knows the underlying object implements nsisupports: > comp.queryinterface(components.interfaces.nsihelloworld); [xpconnect wrapped (nsisupports, nsihelloworld)] as you can see, the queryinterface call also made the wrapper know about the other interface our component supports. assuming the nsihelloworld interface defines the hello method, we can now call it: > comp.hello() hello world! while this behavior is nice for production code as it forces you to clearly define the interfaces that should be used to access the component, it's inconvenient to write the interfaces (and recompile each time you change them) when working on a prototype of the component. meet wrappedjsobjec...
Generating xpt on Windows
in order to generate an .xpt file from an .idl file in recent versions of the gecko \ xul runner sdk in windows, you need to use the typelib.py script. ...
XPIDL Syntax
Mozilla › Tech › XPIDL › Syntax
r expr /= ["-" / "+" / "~"] (scoped_name / literal / "(" expr ")" ) ; numeric literals: quite frankly, i'm sure you know how these kinds of ; literals work, and these are annoying to specify in abnf. literal = octal_literal / decimal_literal / hex_literal / floating_literal literal /= string_literal / char_literal literal /= "true" / "false" ; in regex: /"[^"\n]*["\n]/. yes, newline terminates. string_literal = 1*(%x22 *(any char except %x22 or %x0a) (%x22 / %x0a)) ; same as above, but s/"/'/g char_literal = 1*(%x27 *(any char except %x27 or %x0a) (%x27 / %x0a)) type_spec = "float" / "double" / "string" / "wstring" type_spec /= ["unsigned"] ("short" / "long" / "long" "long") type_spec /= "char" / "wchar" / "boolean" / "octet" type_spec /= scoped_name prop_list = "[" *(p...
Mozilla technologies
icity stream is a mozilla-hosted activity stream generated by a user's application usage. 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. it is not meant as a general application messaging system. toolkit apithe mozilla toolkit is a set of programming interfaces (apis) built on top of gecko which provide advanced services to xul applications. 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 ...
Account Provisioner
ing thunderbird. the account provisioner gives the user the chance to search for and order a vanity email account from a list of partner providers. if the user already has an email account, the user can switch to the original account setup wizard. debugging the account provisioner dialog logs most if not all of its activities, which is useful for debugging. logs can either be dumped to the terminal via dump, or to the error console. to have logs dumped to the terminal, create a string preference called mail.provider.logging.dump and set its value to all. to have logs dumped to the error console, create a string preference called mail.provider.logging.console and set its value to all. a mozillazine article on how to set preferences in thunderbird. ...
Buddy icons in mail
f this article may be out of date. it was imported from mozilla.org and last updated in 2003. seth spitzer mozilla is now able to show icons in the message header area and the addressbook card pane. 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. (see this document for info about that.) for the addressbook card pane, the icon will show is on disk at: <profile home>/nim/<value of pref aim.session.screenname>/picture/<screenname for card>.gif if aim.session.screenname is not set, the icon will not appear. if there is no card matching the ...
DB Views (message lists)
(external reference) are. these are the values filed in nsidbfolderinfo to remember the view settings for the folder. view interaction with nsitreeview the nsitreeview methods in nsmsgdbview.cpp control the appearance of the thread pane. properties these nsmsgdbview methods set properties, nsitreeview.getrowproperties (implementation) nsitreeview.getcellpropreties (implementation) theming the theme uses these properties to style the thread pane. see the tutorial for information about styling trees using css, and the thunderbird source for some example css. text nsitreeview.getcelltext (implementation) tells the nsitreeview what text to display for a particular row and text column. ...
Gloda examples
this content covers features introduced in thunderbird 3 this page provides some examples for using gloda. see creating a gloda message query for more examples. ...
MailNews Filters
e.g., imap, pop3. ...
MailNews Protocols
imap pop3 nntp smtp mailbox rss these are all implemented in c++, except for rss. rss is implemented in js and doesn't follow the same pattern as the c++ protocols. imap,pop3, and nntp are "incoming" protocols, i.e., we retrieve messages from a server, and represent them as folders to the user. those protocols all have the following, defined in the corresponding protocol subdirectory of mailnews (i.e., mailnews/imap, mailnews/local (for pop3), mailnews/news): an incoming server class, which implements nsimsgincomingserver and inherits from mailnews/base/util/nsmsgincomingserver, i.e.., nspop3incomingserver, nsimapincomingserver, nsnntpincomingserver. a folder class, which implements nsimsgfolder, and inherits from nsmsgdbfolder. most commands/operations go through the folder object. ...
Mail and RDF
ork.com/inbox#1 | +-- http://home.netscape.com/nc-rdf#messagechild --> | mailbox_message://alecf@pop.mywork.com/inbox#2 | etc... there are of course many more properties that are exposed via rdf, but this should give you a feel for it. datasources we have a few primary datasources used in mail: nsmsgaccountdatasource - answers queries about arcs coming out of msgaccounts:/. if you ask it for #child nodes out of msgaccounts:/, it returns the root uris of all servers in the account manager. note that it does not actually know anything about the servers who's uris it returns. nsmsgfolderdatasource - answer queries about any mail folders, including toplevel server folders. if asked about a folder along the #child arc, it will return resources for...
Main Windows
or an expanded view basemenuoverlay.xul contains the contents of most of the menus (i.e. file, edit, view, etc). osx only: macmenuoverlay.xul a special overlay for osx that adds a few items to the window menu. customizetoolbar.xul and customizetoolbarsheet.xul these are two old files from when the original customizable toolbars were ported from firefox (phoenix at the time) to thunderbird (minotaur at the time). customizetoolbar.xul looks and acts a whole lot like the toolkit's customizetoolbar.xul. items have the same id’s, and contain the same structure. a few odd pieces are missing though. for instance, the “add new toolbar” buttons from toolkit aren’t in the thunderbird version. customizetoolbarsheet.xul is a similar implementation written for osx to give a more native appe...
Thunderbird Binaries
owards a release? many developers prefer to work on areas of the code which are too risky to change when approaching a release. some of their changes may also take months to test and implement correctly. their changes will be made to the trunk so that they don't delay the release and will be picked up in future branches. 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". you should see a string that looks something like this: comm-central-1.9.2 branch: mozilla/5.0 (windows; u; windows nt 5.1; en-us; rv:1.9.2.2pre) gecko/20100308 lanikai/3.1b1pre comm-central-trunk: mozilla/5.0 (windows; u; windows nt 5.1; en-us; rv:1.9.3a1pre) gecko/20090826 shredder/3.1a1pre the...
Building a Thunderbird extension 1: introduction
ging (making a distribution package that contains the extension) distributing (from your own site or from http://addons.mozilla.org/) this tutorial is compatible with thunderbird versions 2,3 and 5. all thunderbird builds are available from the ftp site. references and resources tools and helper extensions there are many tools available that help with developing thunderbird extensions. at a minimum you will need: text editor: any editor that is capable of writing plain text can be used to write extensions. however, most developers use an editing program optimized for writing code (also known as an integrated development environment). these provide features like syntax highlighting and code coloration, indentation, auto-complete, etc. file archive utility: any utility that is capable...
Building a Thunderbird extension 2: extension file layout
a content/ folder sometimes contains the actual content files. ...
Building a Thunderbird extension 5: XUL
ed in a xul file called messenger.xul, which can be found in the chrome/messenger/content/messenger folder which is packaged inside the omni.ja archive. to view this xul file use the dom inspector extension (no longer supported) or look inside the omni.ja archive, which is located in the thunderbird program folder. omni.ja can be easily browsed by copying the file to a different location and renaming it to omni.zip. if you have trouble with one zip manager (like 7zip) try another (like winrar). in messenger.xul we find the status bar, which looks something like this.: <statusbar id="status-bar" ...> ... <statusbarpanel>s ... </statusbar> <statusbar id="status-bar"> is a "merge point" for a xul overlay. xul overlays are a way of attaching other ui widgets to a xul document at run time. a ...
Finding the code for a feature
i find out. there are two key tools that you need. the first is the dom inspector extension which i have routinely installed in all of my thunderbird installations. (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). the second is mozilla's source code search tool mxr. i keep two prominent links to this on my firefox toolbar, one to comm-central string search, and one to comm-central file search. so, how did i use those to figure out how to do this? i know there is a menu command "tag" to tag the message - how does it do it? using dom inspector, i find the tag menu item, and i see that it uses command "cmd_tag". then i use mxr and look for "cmd_tag". i see it occurs in mail3pan...
Add Option to Context Menu
assuming this on chrome.manifest: overlay chrome://messenger/content/mailwindowoverlay.xul chrome://myext/content/thunderbird-overlay.xul add the next in thunderbird-overlay.xul. for thunderbird 2 <?xml version="1.0"?> <overlay id="sample" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <menupopup id="messagepanecontext"> <menuitem id="my_option" label="my option concise and cool label" oncommand="alert('hi')"/> </menupopup> </overlay> for thunderbird 3 <?xml version="1.0"?> <overlay id="sample" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <popup id="mailcontext"> <menuitem id="my_option" label="my option concis...
Styling the Folder Pane
since thunderbird 3, the folder pane is designed in a more modular and extensible fashion. it is now possible to place non-mail entities in the folder pane. treeview row/cell properties css property equivalent call explanation foldernamecol -- a property for indicating that a column is the folder name column. hasunreadmessages-true afolder.getnumunread(false) > 0 indicates that the folder (but not subfolders) has unread messages. ...
Tips and Tricks from the newsgroups
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 message repeat image display using cs...
Working with ArrayBuffers
nt8clampedarray view for an arraybuffer. the following codeblock provides a basic example of getting and setting uint8clampedarray and arraybuffer of imagedata: // context is a canvasrenderingcontext2d of some canvas var imagedata = context.getimagedata(x, y, w, h); var array = imagedata.data; // array is a uint8clampedarray var buffer = imagedata.data.buffer; // buffer is a arraybuffer // incomingbuffer is a typedarray var imagedata2 = context.createimagedata(w, h); imagedata2.data.set(incomingbuffer); further, if you have a byte array pixelbuffer, and you need to create imagedata from it. the data property holds an array of bytes. we start with the following: // pixelbuffer is a pointer to a rgba pixel buffer of 400x400 image. pixelbuffer.tostring(); // "ctypes.uint8_t.ptr(ctypes.uin...
ABI
a calling convention is an implementation-level (low-level) scheme regarding how subroutines receive parameters from their caller and how they revert. http://en.wikipedia.org/wiki/x86_calling_conventions abi abi stands for "application binary interface". http://en.wikipedia.org/wiki/application_binary_interface os specific windows https://msdn.microsoft.com/en-us/library/k2b2ssfy.aspx https://msdn.microsoft.com/en-us/library/9b372w95.aspx details with respect to js-ctypes this explains how to use it in the js-ctypes scope. ...
ArrayType
d was called. cdata addressofelement( idx ); parameters idx a numeric value indicating the offset into the array of the element just to return a pointer. if this value isn't a valid javascript number that's also a valid index into the array, a typeerror exception is thrown. return value a new cdata object pointing to the specified element. the type of the returned object will be determined by ctypes.pointertype(thearraytype.constructor.elementtype)). see also ctype cdata type conversion ...
CType
is the same value as the c sizeof. read only. note: ctypes.void_t.size is undefined. methods available on all ctype objects array() returns a new ctype representing an array of elements of the type on which it was called. ctype array( [n] }; parameters n optional the number of elements in the declared array type. if this parameter is left out, the array's size is indeterminate. return value a ctype representing the data type "array of this type". this is the same as calling ctypes.arraytype(the_type[, n]). tosource() returns a javascript expression that evaluates to a ctype describing the same c type as this object. string tosource(); parameters none. return value a javascript expression that evaluates to a ctype describing the same c type as this object.
PointerType
ied length. value object the javascript equivalent of the cdata object's value. this will throw a typeerror exception if the value can't be converted. pointertype cdata method_overview bool isnull() methods inherited from cdata cdata address() string tosource() string tostring() pointertype cdata methods isnull() determines whether or not the pointer's value is null. bool isnull(); parameters none. return value true if the pointer's value is null, otherwise false. see also ctype cdata type conversion ...
ctypes
ings. these are unicode characters. special c types these types represent c types that have special meanings. type description void_t the special c type void. this can only be used as a return value type. note: you must use void_t, not void, since void is a keyword in javascript. voidptr_t the c type void *. this is a pointer to an indeterminate type of data. large integer types because javascript doesn't support large (64-bit) integers, js-ctypes provides two data types allowing access to 64-bit integer data. type description int64 a javascript object representing a 64-bit signed integer. uint64 a javascript object representing a 64-bit unsigned integer. methods cast() casts the s...
Flash Activation: Browser Comparison - Plugins
s 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. instead, the plugin object should call into a javascript function upon creation. that function can then issue the call into the plugin, knowing that everything is set up and ready to go. first, set your up your html with a callback that calls the javascript function plugincreat...
Constants - Plugins
blems. npres_user_break 2 user canceled stream directly by clicking the stop button or indirectly by some action such as deleting the instance or initiating higher-priority network operations. plug-in version constants constant value description np_version_major 0 major version number; changes with major code release number. np_version_minor 22 minor version number; changes with point release number. version feature constants npvers constant: version feature information value description npvers_has_streamoutput 8 streaming data. npvers_has_notification 9 notification of completion. npvers_has_liveconnect 9 liveconnect. npvers_win16_has_liveconnect ...
Initialization and Destruction - Plugins
mbed or np_full. np_embed means that the instance was created by an embed and shares the browser window with other content. np_full means that the instance was created by a separate file and is the primary content in the window. the next three parameters pass parameters from the embed element that called the plug-in. the argc parameter is the number of html arguments in the element. it determines the number of attributes in the arrays specified by the argn and argv parameters. the arguments in the embed element are name-value pairs made up of the attribute name (for example, align) and its value (for example, top). the argn array contains the attribute names; the argv array contains the attribute values. the browser ignores any nonstandard attributes in an embed element, so the web pa...
Plug-in Side Plug-in API - Plugins
information about the plug-in. npp_setwindow tells the plug-in when a window is created, moved, sized, or destroyed. np_shutdown provides global deinitialization for a plug-in. npp_streamasfile provides a local file name for the data from a stream. npp_urlnotify notifies the instance of the completion of a url request. npp_write delivers data to a plug-in instance. npp_writeready determines maximum number of bytes that the plug-in can consume. « previousnext » ...
3D view - Firefox Developer Tools
de; in this mode, you can see your page presented in a 3d view in which nested blocks of html are increasingly "tall," projecting outward from the bottom of the page. this view makes it easy to visualize the nesting of your content. by clicking and dragging the view, you can rotate and re-orient the 3d presentation of the dom hierarchy of your page to see it from different angles, to better examine its structure. off-screen elements become visible, so that you can see where your elements are located in relation to the visible content. you can click on elements to see their html in the html panel or the style panel. conversely, you can click on elements in the breadcrumb bar to change which element is selected in the 3d view. if you do not see the 3d button in the page inspector, it is pos...
DOM Inspector internals - Firefox Developer Tools
nd keyboard shortcuts with host-integration overlays. dom inspector explicitly supports several mozilla project applications by providing its own host-integration overlays. ...
Add-ons - Firefox Developer Tools
developer tools that are not built into firefox, but ship as separate add-ons. websocket monitor examine the data exchanged in a websocket connection. this add-on is no longer available, as it requires older versions of firefox. you might give websocket sniffer a try. it's not as detailed but may help. ...
Browser Toolbox - Firefox Developer Tools
one content tab, and one with two: debugging popups it's hard to debug popups, because the browser hides them as soon as you click outside them. there is a way to disable this behavior. click the toolbox menu and select disable popup auto-hide. now when you open any popup, it will stay open until you press the esc key. you can use the inspector's node picker to select that panel, and examine and modify its content: you can use the same technique to debug popups created by add-ons. note: this change is not persistent across browser restarts. when you close the browser toolbox, the setting will be cleared. ...
Use a source map - Firefox Developer Tools
javascript running in a page is often machine-generated, as when compiled from a language like coffeescript or typescript. in these situations, it's much easier to debug the original source, rather than the source in the transformed state that the browser has downloaded. ...
Set an XHR breakpoint - Firefox Developer Tools
you can break on all requests or on those that include a specific url. 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. note: if you enter a key word instead of a url, code execution will pause on any call to a url that contains that keyword. ...
Debugger.Environment - Firefox Developer Tools
nment’s bindings are the properties of an object. the global object and dom elements appear in the chain of environments via object environments. (note that with statements have their own environment type.) “with”, indicating that the environment was introduced by a with statement. parent the environment that encloses this one (the “outer” environment, in ecmascript terminology), or null if this is the outermost environment. object a debugger.object instance referring to the object whose properties this environment reflects. if this is a declarative environment record, this accessor throws a typeerror (since declarative environment records have no such object). both "object" and "with" environments have object properties that provide the object whose properties t...
Tutorial: Set a breakpoint - Firefox Developer Tools
ts debuggee, and then sets a new breakpoint. when you click on the div element, both debuggers’ breakpoints are hit, and both handlers run. this shows how any number of debugger-based tools can observe a single web page simultaneously. in fact, you can use the browser content toolbox’s debugger panel to set its own breakpoint in report, and it will trigger along with the first two. keep in mind, however, that when multiple debuggers share a debuggee, the order in which their handlers run is not specified. if more than one tool tries to influence the debuggee’s behavior, their combined behavior could be unpredictable. close the web page and the browser content toolbox. since both the scratchpad’s global object and the debuggee window are now gone, the debugger instances wil...
The Firefox JavaScript Debugger - Firefox Developer Tools
the javascript debugger enables you to step through javascript code and examine or modify its state to help track down bugs. you can use it to debug code running locally in firefox or running remotely, for example on an android device running firefox for android. see remote debugging to learn how to connect the debugger to a remote target. to find your way around the debugger, here's a quick tour of the ui. how to to find out what you can do with the debugger, refer to the following how-to guides. open the debugger pretty-print a minified file search use a source map pause execution you probably want to pause the execution of your code, in order to see what is going on at various points. there are multiple ways to tell the debugger how and when to pause: set a breakpoint...
Basic operations - Firefox Developer Tools
reed between the two snapshots. to create a diff, click the button that looks like a venn diagram next to the camera icon (before firefox 47, this looked like a "+/-" icon): you'll be prompted to select the snapshot to use as a baseline, then the snapshot to compare. the tool then shows you the differences between the two snapshots: when you're looking at a comparison, you can't use the dominators view or the tree map view. recording call stacks the memory tool can tell you exactly where in your code you are allocating memory. however, recording this information has a run-time cost, so you must ask the tool to record memory calls before the memory is allocated, if you want to see memory call sites in the snapshot. to do this, check "record call stacks" (before firefox 49 this was l...
Edit fonts - Firefox Developer Tools
s setting toggles between italic and normal values for the font-style css property. note: as you change settings, firefox applies inline styles to the element to make the changes instantly visible on the page. all fonts on page the remaining area, at the bottom of the fonts tab, shows an expandable list of all of the fonts in use on the page. the list is useful because you can easily determine whether a font is a web font or a font hosted on your system. each font listed in this section shows you: the font-family identifier and full name of the font. the url to the font file in the case of web fonts not available on your system, or "system" in the case of fonts loaded from your computer (either default system fonts, or web fonts that you've also got installed on your system). you...
Call Tree - Firefox Developer Tools
owser calls. this can be useful information too. if your site is making the browser work hard, this might not show up as samples recorded in your code, but it is still your problem. in our example, there are 679 samples assigned to gecko - the second-largest group after bubblesort(). let's expand that: this result is telling us that 614 of those samples, or about 20% of the total cost, are coming from our sort() call. if we look at the code for sort(), it should be fairly obvious that the high platform data cost is coming from repeated calls to console.log(): function sort(unsorted) { console.log(bubblesort(unsorted)); console.log(selectionsort(unsorted)); console.log(quicksort(unsorted)); } it would certainly be worthwhile considering more efficient ways of implementing this. o...
Flame Chart - Firefox Developer Tools
from 1435ms to a little past 1465ms. along the y-axis are the functions on the call stack at that point in time, with the top-level at the top, and the leaf function at the bottom. functions are color-coded to make them easier to distinguish. this gives you a way to know exactly which function was executing at any point during the recording, how long it ran for, and where it was called from. zooming and panning to work effectively with the flame chart, you'll need to be able to navigate it. there are two main controls you can use to navigate the flame chart: zoom: increase/decrease the selected portion of the complete profile that's displayed in the flame chart 1) mouse wheel up/down in the flame chart. 2) trackpad 2 fingers up/down in the flame chart. p...
Frame rate - Firefox Developer Tools
event. the frame rate graph in the performance tool shows you the frame rate over the course of a recording. it gives you a quick indication of where your site might be having problems, enabling you to use the other tools for a more in-depth analysis. frame rate and responsiveness frame rate is the rate at which a video device can produce images (or frames). it's most familiar from film and gaming, but is now widely used as a performance measure for websites and web apps. in web performance, a frame encapsulates the work the browser needs to do in order to update and repaint the screen. frame rate is most obviously applicable to animations: if the frame rate is too low, an animation will have a jerky appearance, while a faster frame rate will be smoother. but frame rate is also useful as...
Intensive JavaScript - Firefox Developer Tools
ress "do pointless computations!" two or three times stop recording the profile exactly what you see will vary from one machine to another, but it will be something like this: the top half of this is the waterfall overview. it gives us a compressed view of the waterfall, which tells us what kinds of operations the browser is doing during the recording. the pink says that we are mostly performing css calculations and possibly reflow: this is the css animation that's running throughout the profile. then there are three solid blocks of orange, representing javascript execution, one for each time we pressed the button. the bottom half, which is correlated with the timeline summary in time, shows frame rate. we can see that frame rate is pretty healthy for most of the recording, but collaps...
Rulers - Firefox Developer Tools
orner of the viewport. to be able to toggle rulers for a page, you first need to enable the button by going to the settings page for the developer tools and checking "toggle rulers for the page" under available toolbox buttons. once enabled, the "toggle rulers for the page" button appears at the top right of the toolbox, in the same place as the settings/options button. behavior to keep in mind when using rulers: the rulers command must be reapplied in new tabs and after each page refresh. the command isn't permanent. ...
Style Editor - Firefox Developer Tools
he page. this makes it easy to experiment with, revise, and test changes. once you're satisfied with your changes, you can save a copy locally by clicking the save button on the sheet's entry in the style sheet pane. the editor provides line numbers and syntax highlighting to help make it easier to read your css. it also supports a number of keyboard shortcuts. the style editor automatically de-minimizes style sheets that it detects, without affecting the original. this makes it much easier to work on pages that have been optimized. the style editor supports autocomplete. just start typing, and it will offer you a list of suggestions. you can switch autocomplete off in the style editor settings. the media sidebar the style editor displays a sidebar on the right-hand side whenever the cu...
about:debugging - Firefox Developer Tools
her workers, including chrome workers and dedicated workers you can connect the developer tools to each worker, and send push notifications to service workers. service worker state the list of service workers shows the state of the service worker in its lifecycle. three states are possible: registering: this covers all states between the service worker's initial registration, and its assuming control of pages. that is, it subsumes the installing, activating, and waiting states. running: the service worker is currently running. it's installed and activated, and is currently handling events. stopped: the service worker is installed and activated, but has been terminated after being idle. this section uses a simple serviceworker demo, hosted at https://serviceworke.rs/push-simple/...
AddressErrors.addressLine - Web APIs
if an error occurred during validation of the address due to one of the strings in the addressline array having an invalid value, this property is set to a domstring providing a human-readable error message explaining the validation error. the text should also include, when possible, advice about how to go about correcting the error. if the paymentaddress object's addressline property was determined to be valid, this property is not included in the addresserrors dictionary. specifications specification status comment payment request apithe definition of 'addresserrors.addressline' in that specification. candidate recommendation initial definition. ...
AddressErrors.country - Web APIs
an object based on addresserrors includes a country property if during validation of the address the specified value of country was determined to be invalid. the value is a string describing the error and should offer suggestions for how to correct it. syntax var countryerror = addresserrors.country; value if an error occurred during validation of the address due to the country property having an invalid value, this property is set to a domstring providing a human-readable error message explaining the validation error. the text should also include, when possible, advice about how to go about correcting the error. if the paymentaddress object's country property was determined to be valid, this property is not included in the dictionary. specifications specification status ...
AddressErrors - Web APIs
properties these properties have been removed from the specification and should no longer be used. languagecode a domstring which, if present, indicates that the languagecode property of the paymentaddress could not be validated. the contents of the string provide a human-readable explanation of the validation failure, and ideally suggestions to correct the problem. usage notes keep in mind that some violation errors may be outside the ability of the user to fix. try to avoid asking the user to make corrections to things they can't change, and there may be situations in which you need to allow validation errors to be accepted anyway (for example, if you validate addresses against a postal service database and a new home has been built and its address is not yet in the database). e...
AesGcmParams - Web APIs
the decrypt() call does not match the original data, the decryption will throw an exception. this gives you a way to authenticate associated data without having to encrypt it. the bit length of additionaldata must be ≤ 264-1. the additionaldata property is optional and may be omitted without compromising the security of the encryption operation. taglength optional a number. this determines the size in bits of the authentication tag generated in the encryption operation and used for authentication in the corresponding decryption. according to the web crypto specification this must have one of the following values: 32, 64, 96, 104, 112, 120, or 128. the aes-gcm specification recommends that it should be 96, 104, 112, 120 or 128, although 32 or 64 bits may be acceptable in some ap...
AmbientLightSensor.AmbientLightSensor() - Web APIs
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. ...
Ambient Light Sensor API - Web APIs
interfaces ambientlightsensor returns an interface for accessing ambientlightsensorreadings. ...
AnalyserNode.AnalyserNode() - Web APIs
new analysernode(context, ?options); parameters inherits parameters from the audionodeoptions dictionary. context a reference to an audiocontext or offlineaudiocontext. options optional fftsize: the desired initial size of the fft for frequency-domain analysis. the default is 2048. maxdecibels: the desired initial maximum power in db for fft analysis. the default is -30. mindecibels: the desired initial minimum power in db for fft analysis. the default is -100. smoothingtimeconstant: the desired initial smoothing constant for the fft analysis. the default is 0.8. return value a new analysernode object instance. specifications specification status comment web audio apithe definition of 'analysernode() constructor' in that specific...
AnalyserNode.fftSize - Web APIs
syntax var curvalue = analysernode.fftsize; analysernode.fftsize = newvalue; value an unsigned integer, representing the window size of the fft, given in number of samples. a higher value will result in more details in the frequency domain but fewer details in the time domain. must be a power of 2 between 252^5 and 2152^15, so one of: 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, and 32768. defaults to 2048. ...
AnalyserNode.frequencyBinCount - Web APIs
uestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); analyser.mindecibels = -90; analyser.maxdecibels = -10; ... analyser.fftsize = 256; var bufferlength = analyser.frequencybincount; console.log(bufferlength); var dataarray = new uint8array(bufferlength); canvasctx.clearrect(0, 0, width, height); function draw() { drawvisual = requestanimationframe(draw); analyser.getbytefrequencydata(dataarray); canvasctx.fillstyle = 'rgb(0, 0, 0)'; canvasctx.
AnalyserNode.smoothingTimeConstant - Web APIs
atic demo (see app.js lines 128–205 for relevant code). if you are curious about the effect the smoothingtimeconstant() has, try cloning the above example and setting analyser.smoothingtimeconstant = 0; instead. you'll notice that the value changes are much more jarring. var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); analyser.mindecibels = -90; analyser.maxdecibels = -10; analyser.smoothingtimeconstant = 0.85; ... analyser.fftsize = 256; var bufferlength = analyser.frequencybincount; console.log(bufferlength); var dataarray = new uint8array(bufferlength); canvasctx.clearrect(0, 0, width, height); function draw() { drawvisual = requestanimationframe(draw); analyser.getbytefrequencydata(dataarray); canvasctx.f...
Animation.currentTime - Web APIs
r representing the current time in milliseconds, or null to deactivate the animation. examples in the drink me/eat me game, alice's height is animated so it can go from small to large or large to small. at the start of the game, her height is set between the two extremes by setting her animation's currenttime to half her keyframeeffect's duration: alicechange.currenttime = alicechange.effect.timing.duration / 2; a more generic means of seeking to the 50% mark of an animation would be: animation.currenttime = animation.effect.getcomputedtiming().delay + animation.effect.getcomputedtiming().activeduration / 2; reduced time precision to offer protection against timing attacks and fingerprinting, the precision of animation.currenttime might get rounded depending on browser settings. i...
Animation.onfinish - Web APIs
nt handler is set. examples animation.onfinish is used several times in the alice in web animations api land growing/shrinking alice game. here is one instance where we add pointer events back to an element after its opacity animation has faded it in: // add an animation to the game's ending credits var endingui = document.getelementbyid("ending-ui"); var bringui = endingui.animate(keysfade, timingfade); // pause said animation's credits bringui.pause(); // this function removes pointer events on the credits. hide(endingui); // when the credits are later faded in, // we re-add the pointer events when they're done bringui.onfinish = function() { endingui.style.pointerevents = 'auto'; }; specifications specification status comment web animationsthe definition ...
Animation.timeline - Web APIs
nimation interface returns or sets the timeline associated with this animation. a timeline is a source of time values for synchronization purposes, and is an animationtimeline-based object. by default, the animation's timeline and the document's timeline are the same. syntax var animationstimeline = animation.timeline; animation.timeline = newtimeline; value a timeline object to use as the timing source for the animation, or null to use the default, which is the document's timeline. examples here we set the animation's timeline to be the same as the document's timeline (this is the default timeline for all animations, by the way): animation.timeline = document.timeline; specifications specification status comment web animationsthe definition of 'animation.ti...
AnimationEffect - Web APIs
the animationeffect interface of the web animations api defines current and future animation effects like keyframeeffect, which can be passed to animation objects for playing, and keyframeeffectreadonly (which is used by css animations and transitions). methods animationeffect.gettiming() returns the effecttiming object associated with the animation containing all the animation's timing values. animationeffect.getcomputedtiming() returns the calculated timing properties for this animationeffect. animationeffect.updatetiming() updates the specified timing properties of this animationeffect. specifications specification status comment web animationsthe definition of 'animationeffect' in that specification. working draft editor's draft. ...
AnimationPlaybackEvent.currentTime - Web APIs
the currenttime read-only property of the animationplaybackevent interface represents the current time of the animation that generated the event at the moment the event is queued. this will be unresolved if the animation was idle at the time the event was generated. value a number representing the current time in milliseconds, or null. reduced time precision to offer protection against timing attacks and fingerprinting, the precision of playbackevent.currenttime might get rounded depending on browser settings. in firefox, the privacy.reducetimerprecision preference is enabled by default and defaults to 20us in firefox 59; in 60 it will be 2ms. // reduced time precision (2ms) in firefox 60 playbackevent.currenttime; // 23.404 // 24.192 // 25.514 // ... // reduced time precision wit...
AnimationTimeline.currentTime - Web APIs
rrenttime read-only property of the web animations api's animationtimeline interface returns the timeline's current time in milliseconds, or null if the timeline is inactive. syntax var currenttime = animationtimeline.currenttime; value a number representing the timeline's current time in milliseconds, or null if the timeline is inactive. reduced time precision to offer protection against timing attacks and fingerprinting, the precision of animationtimeline.currenttime might get rounded depending on browser settings. in firefox, the privacy.reducetimerprecision preference is enabled by default and defaults to 20us in firefox 59; in 60 it will be 2ms. // reduced time precision (2ms) in firefox 60 animationtimeline.currenttime; // 23.404 // 24.192 // 25.514 // ... // reduced time prec...
Attr.namespaceURI - Web APIs
Web › API › Attr › namespaceURI
the attr.namespaceuri read-only property returns the namespace uri of the attribute, or null if the element is not in a namespace. before dom4 this api was defined within the node interface. syntax namespace = attribute.namespaceuri example in this snippet, an attribute is being examined for its localname and its namespaceuri. if the namespaceuri returns the xul namespace and the localname returns "browser", then the node is understood to be a xul <browser/>. if (attribute.localname == "value" && attribute.namespaceuri == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul") { // this is a xul value } notes this is not a computed value that is the result of a namespace lookup based on an examination of the namespace declarations in scope. the namespace uri of an at...
AudioBuffer - Web APIs
uffer(). once put into an audiobuffer, the audio can then be played by being passed into an audiobuffersourcenode. objects of these types are designed to hold small audio snippets, typically less than 45 s. for longer sounds, objects implementing the mediaelementaudiosourcenode are more suitable. the buffer contains data in the following format: non-interleaved ieee754 32-bit linear pcm with a nominal range between -1 and +1, that is, 32bits floating point buffer, with each samples between -1.0 and 1.0. if the audiobuffer has multiple channels, they are stored in separate buffer. constructor audiobuffer() creates and returns a new audiobuffer object instance. properties audiobuffer.samplerate read only returns a float representing the sample rate, in samples per second, of the pc...
AudioBufferSourceNode.playbackRate - Web APIs
ta() function is used to decode an audio track, and put it into an audiobuffersourcenode. buttons are provided to play and stop the audio playback, and a slider control is used to change the playbackrate property value on the fly. you can run the example live (or view the source.) play the song and alter the playback rate for some fun results. ...
AudioContext.createJavaScriptNode() - Web APIs
the audiocontext.createjavascriptnode() method creates a javascriptnode which is used for directly manipulating audio data with javascript. important: this method is obsolete, and has been renamed to audiocontext.createscriptprocessor(). see also scriptprocessornode. syntax var jsnode = audioctx.createjavascriptnode(buffersize, numinputchannels, numoutputchannels); parameters buffersize the buffer size must be in units of sample frames, i.e., one of: 256, 512, 1024, 2048, 4096, 8192, or 16384. it controls the frequency of callbacks asking for a buffer refill. smaller sizes allow for lower latency and higher for better overall quality. numinputchannels the number of input channels in the audio stream. numoutputchannels the number of output channels in the audio stream. ex...
AudioContext.createMediaStreamTrackSource() - Web APIs
to the user's microphone. 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. the output from the microphone is then routed into the new biquad filter, and the filter's output is in turn routed to the audio context's destination. navigator.mediadevices.getusermedia ({audio: true, video: false}) .then(function(stream) { audio.srcobject = stream; audio.onloadedmetadata = function(e) { audio.play(); audio.muted = true; }; let audioctx = new...
AudioContextLatencyCategory - Web APIs
ive elements, such as responding to user actions or needing to coincide with visual cues such as a video or game action. the user agent should select the lowest possible latency that doesn't cause glitches in the audio. this is likely to require increased power consumption. this is the default value. "playback" the user agent should select a latency that will maximize playback time by minimizing power consumption at the expense of latency. useful for non-interactive playback, such as playing music. specifications specification status comment web audio apithe definition of 'audiocontextlatencycategory' in that specification. working draft initial definition. ...
AudioContextOptions.latencyHint - Web APIs
encycategory. in fact, the default value of latencyhint is "interactive" (meaning the browser should try to use the lowest possible and reliable latency it can). the value can also be specified as a double-precision floating-point value, specifying the preferred maximum latency in seconds. this provides more precise control over the balance between audio latency and device energy usage. to determine the actual latency of the context after creating it, check the value of the context's baselatency property. specifications specification status comment web audio apithe definition of 'audiocontextoptions.latencyhint' in that specification. working draft initial definition. ...
AudioDestinationNode.maxChannelCount - Web APIs
specifications specification status comment web audio apithe definition of 'maxchannelcount' in that specification. working draft ...
AudioDestinationNode - Web APIs
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. specifications specification status comment web audio apithe definition of 'audiodestinationnode' in that specification. working draft ...
AudioListener.speedOfSound - Web APIs
the speedofsound property of the audiolistener interface is a double value representing the speed of sound, in meters per second. the speedofsound property's default value is 343.3 m/s and is used to calculate the doppler shift appropriate for the speed the panner is travelling at (as defined by pannernode.setvelocity.) note: bear in mind that no propagation delay is automatically applied to a sound far from the listener. syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.speedofsound = 343.3; value a double. example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation. generally you will define the position in 3d space that your audio l...
AudioNode.channelCount - Web APIs
channelcount's usage and precise definition depend on the value of audionode.channelcountmode: it is ignored if the channelcountmode value is max. it is used as a maximum value if the channelcountmode value is clamped-max. it is used as the exact value if the channelcountmode value is explicit. syntax var oscillator = audioctx.createoscillator(); var channels = oscillator.channelcount; value an integer. ...
AudioNode.disconnect() - Web APIs
nections are disconnected. destination optional an audionode or audioparam specifying the node or nodes to disconnect from. if this value is an audionode, a single node is disconnected from, with any other, optional, parameters (output and/or input) further limiting which inputs and/or outputs should be disconnected. if this value is an audioparam, then the connection to that audioparam is terminated, and the node's contributions to that computed parameter become 0 going forward once the change takes effect. if no matching connection is found, an invalidaccesserror exception is thrown. output optional an index describing which output from the current audionode is to be disconnected. the index numbers are defined according to the number of output channels (see audio channels). if this pa...
AudioNode.numberOfInputs - Web APIs
the numberofinputs property of the audionode interface returns the number of inputs feeding the node. source nodes are defined as nodes having a numberofinputs property with a value of 0. syntax var numinputs = audionode.numberofinputs; value an integer ≥ 0. example const audioctx = new audiocontext(); const oscillator = audioctx.createoscillator(); const gainnode = audioctx.creategain(); oscillator.connect(gainnode).connect(audioctx.destination); console.log(oscillator.numberofinputs); // 0 console.log(gainnode.numberofinputs); // 1 console.log(audioctx.destination.numberofinputs); // 1 specifications specification status comment web audio apithe definition of 'numberofinputs' in that specification. working draft ...
AudioNode.numberOfOutputs - Web APIs
destination nodes — like audiodestinationnode — have a value of 0 for this attribute. syntax var numoutputs = audionode.numberofoutputs; value an integer ≥ 0. ...
AudioNodeOptions - Web APIs
ing new audionode objects. audionodeoptions is inherited from by the option objects of the different types of audio node constructors. see for example analysernode.analysernode or gainnode.gainnode. syntax var audionodeoptions = { "channelcount" : 2, "channelcountmode" : "max", "channelinterpretation" : "discrete" } properties channelcount optional represents an integer used to determine how many channels are used when up-mixing and down-mixing connections to any inputs to the node. (see audionode.channelcount for more information.) its usage and precise definition depend on the value of audionodeoptions.channelcountmode. channelcountmode optional represents an enumerated value describing the way channels must be matched between the node's inputs and outputs. (see audionode.ch...
AudioParam.value - Web APIs
Web › API › AudioParam › value
the value is set to audioparam.defaultvalue. setting value has the same effect as calling audioparam.setvalueattime with the time returned by the audiocontext's currenttime property.. syntax var curvalue = audioparam.value; audioparam.value = newvalue; value a floating-point number indicating the parameter's value as of the current time. this value will be between the values specified by the minvalue and maxvalue properties. usage notes value precision and variation the data type used internally to store value is a single-precision (32-bit) floating point number, while javascript uses 64-bit double-precision floating point numbers. as a result, the value you read from the value property may not always exactly equal what you set it to. consider this example: const source = new audiob...
AudioParam - Web APIs
e to happen at very precise times, using arbitrary timelime-based automation curves. the time used is the one defined in audiocontext.currenttime. properties audioparam.defaultvalue read only represents the initial volume of the attribute as defined by the specific audionode creating the audioparam. audioparam.maxvalue read only represents the maximum possible value for the parameter's nominal (effective) range. audioparam.minvalue read only represents the minimum possible value for the parameter's nominal (effective) range. audioparam.value represents the parameter's current value as of the current time; initially set to the value of defaultvalue. methods audioparam.setvalueattime() schedules an instant change to the value of the audioparam at a precise time, as measure...
AudioScheduledSourceNode: ended event - Web APIs
the ended event of the audioscheduledsourcenode interface is fired when the source node has stopped playing. bubbles no cancelable no interface event event handler property audioscheduledsourcenode.onended usage notes this event occurs when a audioscheduledsourcenode 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. 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 us...
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. ...
AudioScheduledSourceNode.start() - Web APIs
rt playback immediately. offset optional a floating-point number indicating the offset, in seconds, into the audio buffer where playback should begin. if 0 is passed then the playback will start from the beginning. duration optional a floating-point number indicating the duration, in seconds, to be played. if no value is passed then the duration will be equal to the length of the audio buffer minus the offset value return value undefined exceptions invalidstatenode the node has already been started. this error occurs even if the node is no longer running because of a prior call to stop(). rangeerror the value specified for when is negative. example this example demonstrates how to create an oscillatornode which is scheduled to start playing in 2 seconds and stop playing 1 sec...
AudioScheduledSourceNode.stop() - Web APIs
0, or passing a negative value causes the sound to stop playback immediately. return value undefined exceptions invalidstatenode the node has not been started by calling start(). rangeerror the value specified for when is negative. example this example demonstrates starting an oscillator node, scheduled to begin playing at once and to stop playing in one second. the stop time is determined by taking the audio context's current time from audiocontext.currenttime and adding 1 second. context = new audiocontext(); osc = context.createoscillator(); osc.connect(context.destination); /* let's play a sine wave for one second. */ osc.start(); osc.stop(context.currenttime + 1); specifications specification status comment web audio apithe definition of 'stop()'...
AudioScheduledSourceNode - Web APIs
ed, the node begins playing immediately. stop() schedules the node to stop playing at the specified time. if no time is specified, the node stops playing at once. 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. specification specification status comment web audio apithe definition of 'audioscheduledsourcenode' in that specification. working draft ...
AudioTrack.kind - Web APIs
Web › API › AudioTrack › kind
see audio track kind strings for a list of the kinds available for audio tracks. syntax var trackkind = audiotrack.kind; value a domstring specifying the type of content the media represents. the string is one of those found in audio track kind strings below. ...
AudioWorkletNode.parameters - Web APIs
le. we expand the processor by adding a static parameterdescriptors getter. it will be used internally by the audioworkletnode constructor to populate its parameters with instantiated audioparam objects. ...
AudioWorkletProcessor() - Web APIs
ing its initial value. processoroptions optional any additional data that can be used for custom initialization of the underlying audioworkletprocessor. note that there are default values for the first two properties, so even if there are no options object passed to the audioworkletnode constructor, the options object passed by the node to the audioworkletprocessor constructor will exist and at minimum have numberofinputs and numberofoutputs. return value the newly constructed audioworkletprocessor instance. example in this example we pass custom options to the audioworkletnode constructor and observe how a structured clone of them gets passed to our audioworkletprocessor constructor. first, we need to define a custom audioworkletprocessor and register it. note that this should be don...
BaseAudioContext.createDelay() - Web APIs
syntax var delaynode = audioctx.createdelay(maxdelaytime); parameters maxdelaytime optional the maximum amount of time, in seconds, that the audio signal can be delayed by. must be less than 180 seconds, and defaults to 1 second if not specified. returns a delaynode. the default delaynode.delaytime is 0 seconds. example we have created a simple example that allows you to play three different samples on a constant loop — see create-delay (you can also view the source code). ...
BaseAudioContext.createIIRFilter() - Web APIs
filter. syntax var iirfilter = audiocontext.createiirfilter(feedforward, feedback); parameters feedforward an array of floating-point values specifying the feedforward (numerator) coefficients for the transfer function of the iir filter. the maximum length of this array is 20, and at least one value must be nonzero. feedback an array of floating-point values specifying the feedback (denominator) coefficients for the transfer function of the iir filter. this array may have up to 20 members, the first of which must not be zero. return value an iirfilternode implementing the filter with the specified feedback and feedforward coefficient arrays. exceptions invalidstateerror all of the feedforward coefficients are 0, and/or the first feedback coefficient is 0. notsupportederror ...
BaseAudioContext.createOscillator() - Web APIs
method of the baseaudiocontext interface creates an oscillatornode, a source representing a periodic waveform. it basically generates a constant tone. syntax var oscillatornode = audioctx.createoscillator(); returns an oscillatornode. example the following example shows basic usage of an audiocontext to create an oscillator node. for applied examples/information, check out our violent theremin demo (see app.js for relevant code); also see our oscillatornode page for more information. // create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.setvalueattime(3000, audioctx.currenttime); // value in hertz oscillator.conne...
BaseAudioContext.createPanner() - Web APIs
the panner node is spatialized in relation to the audiocontext's audiolistener (defined by the audiocontext.listener attribute), which represents the position and orientation of the person listening to the audio. syntax baseaudioctx.createpanner(); returns a pannernode. example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation. ...
BaseAudioContext.createStereoPanner() - Web APIs
syntax baseaudiocontext.createstereopanner(); returns a stereopannernode. example in our stereopannernode example (see source code) html we have a simple <audio> element along with a slider <input> to increase and decrease pan value. ...
BaseAudioContext.currentTime - Web APIs
an be used for scheduling audio playback, visualizing timelines, etc. it starts at 0. syntax var curtime = baseaudiocontext.currenttime; example var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // older webkit/blink browsers require a prefix ... console.log(audioctx.currenttime); reduced time precision to offer protection against timing attacks and fingerprinting, the precision of audioctx.currenttime might get rounded depending on browser settings. in firefox, the privacy.reducetimerprecision preference is enabled by default and defaults to 20us in firefox 59; in 60 it will be 2ms. // reduced time precision (2ms) in firefox 60 audioctx.currenttime; // 23.404 // 24.192 // 25.514 // ... // reduced time precision with `priva...
BatteryManager.chargingTime - Web APIs
syntax var time = battery.chargingtime on return, time is the remaining time in seconds until the battery, which is a batterymanager object, is fully charged, or 0 if the battery is already fully charged. if the battery is currently discharging, this value is infinity. ...
BatteryManager.dischargingTime - Web APIs
syntax var time = battery.dischargingtime on return, time is the remaining time in seconds until the battery, which is a batterymanager object, is fully discharged and the system will suspend. ...
BatteryManager.level - Web APIs
ween 0.0 and 1.0. syntax var level = battery.level on return, level is a number representing the system's battery charge level scaled to a value between 0.0 and 1.0. a value of 0 means the battery, which is a batterymanager object, is empty and the system is about to be suspended. a value of 1.0 means the battery is full. a value of 1.0 is also returned if the implementation isn't able to determine the battery charge level or if the system is not battery-powered. example html content <div id="level">(battery level unknown)</div> javascript content navigator.getbattery().then(function(battery) { var level = battery.level; document.queryselector('#level').textcontent = level; }); specifications specification status comment battery status api ...
Battery Status API - Web APIs
e battery status api extends window.navigator with a navigator.getbattery() method returning a battery promise, which is resolved in a batterymanager object providing also some new events you can handle to monitor the battery status. example in this example, we watch for changes both to the charging status (whether or not we're plugged in and charging) and for changes to the battery level and timing. this is done by listening for the chargingchange, levelchange, chargingtimechange, dischargingtimechange events. navigator.getbattery().then(function(battery) { function updateallbatteryinfo(){ updatechargeinfo(); updatelevelinfo(); updatecharginginfo(); updatedischarginginfo(); } updateallbatteryinfo(); battery.addeventlistener('chargingchange', function(){ update...
BiquadFilterNode.Q - Web APIs
syntax var audioctx = new audiocontext(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.q.value = 100; note: though the audioparam returned is read-only, the value it represents is not. value an audioparam. example the following example shows basic usage of an audiocontext to create a biquad filter node. ...
BiquadFilterNode.frequency - Web APIs
syntax var audioctx = new audiocontext(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.frequency.value = 3000; note: though the audioparam returned is read-only, the value it represents is not. value an audioparam. ...
BiquadFilterNode.gain - Web APIs
the gain property of the biquadfilternode interface is a a-rate audioparam, a double representing the gain used in the current filtering algorithm. when it takes a positive value it is a real gain, when negative it is an attenuation. it is expressed in db, has a default value of 0 and can take a value in a nominal range of -40 to 40. syntax var audioctx = new audiocontext(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.gain.value = 25; note: though the audioparam returned is read-only, the value it represents is not. value an audioparam. example the following example shows basic usage of an audiocontext to create a biquad filter node. for a complete working example, check out our voice-change-o-matic demo (look at the source code too). var audioctx = new (wind...
Blob.type - Web APIs
Web › API › Blob › type
example this example asks the user to select a number of files, then checks each file to make sure it's one of a given set of image file types. ...
Blob - Web APIs
Web › API › Blob
ject url is created. click the link to see the decoded object url.</p> javascript the main piece of this code for example purposes is the typedarraytourl() function, which creates a blob from the given typed array and returns an object url for it. having converted the data into an object url, it can be used in a number of ways, including as the value of the <img> element's src attribute (assuming the data contains an image, of course). function typedarraytourl(typedarray, mimetype) { return url.createobjecturl(new blob([typedarray.buffer], {type: mimetype})) } const bytes = new uint8array(59); for(let i = 0; i < 59; i++) { bytes[i] = 32 + i; } const url = typedarraytourl(bytes, 'text/plain'); const link = document.createelement('a'); link.href = url; link.innertext = 'open the a...
BroadcastChannel.close() - Web APIs
this is a necessary step to perform as there is no other way for a browser to know that this channel is not needed anymore. note: this feature is available in web workers. syntax var str = channel.close(); example // connect to a channel var bc = new broadcastchannel('test_channel'); // more operations (like postmessage, …) // when done, disconnect from the channel bc.close(); specifications specification status comment html living standardthe definition of 'broadcastchannel.close()' in that specification. ...
CSS numeric factory functions - Web APIs
unit being the name of the method used. these functions create new numeric values less verbosely than using the cssunitvalue.cssunitvalue() constructor. ...
CSSImageValue - Web APIs
ckground-image, list-style-image, or border-image-source. the cssimagevalue object represents an <image> that involves an url, such as url() or image(), but not linear-gradient() or element() . properties none. methods none. examples we create an element <button>magic wand</button> we add some css, including a background image requesting a binary file: button { display: inline-block; min-height: 100px; min-width: 100px; background: no-repeat 5% center url(https://mdn.mozillademos.org/files/16793/magicwand.png) aqua; } we get the element's style map. we then get() the background-image from the stylemap and stringify it: // get the element const button = document.queryselector( 'button' ); // retrieve all computed styles with computedstylemap() const allcomputedstyles = button...
CSSMathSum - Web APIs
hen the stylepropertymapreadonly.get() method is used on a css property whosevalue is created with a calc() function. constructor cssmathsum.cssmathsum() creates a new cssmathsum object. properties cssmathsum.values returns a cssnumericarray object which contains one or more cssnumericvalue objects. event handlers no methods none. 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. <div>has width</div> we assign a width div { width: calc(30% - 20px); } we add the javascript const stylemap = document.queryselector('div').computedstylemap(); console.log( stylemap.get('width') ); // cssmathsum {values: cssnumericarray, operator: "sum"} console.log( st...
CSSMathValue.operator - Web APIs
tor read-only property of the cssmathvalue interface indicates the operator that the current subtype represents. for example, if the current cssmathvalue subtype is cssmathsum, this property will return the string "sum". syntax var astring = cssmathvalue.operator; value a string. 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. <div>my width has a <code>calc()</code> function</div> we assign a width with a calculation div { width: calc(50% - 0.5vw); } we ad...
CSSMathValue - Web APIs
the cssmathvalue interface of the css typed object model api a base class for classes representing complex numeric values. interfaces based on cssmathvalue below is a list of interfaces based on the cssmathvalue interface. cssmathinvert cssmathmax cssmathmin cssmathnegate cssmathproduct cssmathsum properties cssmathvalue.operator indicates the operator that the current subtype represents. event handlers no methods none. examples we create an element with a width determined using a calc() function, then console.log() the operator. <div>has width</div> we assign a width with a calculation div { width: calc(30% - 20px); } we add the javascript const stylemap = document.queryselector('div').computedstylemap(); console.log( stylemap.get('width') ); ...
CSSStyleSheet - Web APIs
accessed from its owner object (node or cssimportrule), if any. a cssstylesheet object is created and inserted into the document's document.stylesheets list automatically by the browser, when a stylesheet is loaded for a document. as the stylesheet list cannot be modified directly, there's no useful way to create a new cssstylesheet object manually (although constructable stylesheet objects is coming to the web platform soon and is already supported in blink). to create a new stylesheet, insert a <style> or <link> element into the document. a (possibly incomplete) list of ways a stylesheet can be associated with a document follows: reason for the style sheet to be associated with the document appears in document. stylesheets list getting the owner element/rule given the ...
CSS Typed Object Model API - Web APIs
senting operations that all numeric values can perform, including: cssnumericvalue.add - adds supplied numbers to the cssnumericvalue. cssnumericvalue.sub - subtracts supplied numbers to the cssnumericvalue. cssnumericvalue.mul - multiplies supplied numbers to the cssnumericvalue. cssnumericvalue.div - divides a supplied number by other numbers, throwing an error if 0. cssnumericvalue.min - returns the minimum value passed cssnumericvalue.max - returns the maximum value passed cssnumericvalue.equals - returns true if all the values are the exact same type and value, in the same order. otherwise, false cssnumericvalue.to - converts value into another one with the specified unit. cssnumericvalue.tosum cssnumericvalue.type cssnumericvalue.parse - returns a number parsed f...
Cache.delete() - Web APIs
Web › API › Cache › delete
u are looking to delete. this can be a request object or a url. options optional an object whose properties control how matching is done in the delete operation. the available options are: ignoresearch: a boolean that specifies whether the matching process should ignore the query string in the url. if set to true, the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match. it defaults to false. ignoremethod: a boolean that, when set to true, prevents matching operations from validating the request http method (normally only get and head are allowed.) it defaults to false. ignorevary: a boolean that, when set to true, tells the matching operation not to perform vary header matching. in other words, if the url matches you will get a match regardless of...
Cache.keys() - Web APIs
Web › API › Cache › keys
a specific key is desired. this can be a request object or a url. options optional an object whose properties control how matching is done in the keys operation. the available options are: ignoresearch: a boolean that specifies whether the matching process should ignore the query string in the url. if set to true, the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match. it defaults to false. ignoremethod: a boolean that, when set to true, prevents matching operations from validating the request http method (normally only get and head are allowed.) it defaults to false. ignorevary: a boolean that, when set to true, tells the matching operation not to perform vary header matching. in other words, if the url matches you will get a match regardless of...
Cache.match() - Web APIs
Web › API › Cache › match
uest for which you are attempting to find responses in the cache. this can be a request object or a url. options optional an object that sets options for the match operation. the available options are: ignoresearch: a boolean that specifies whether to ignore the query string in the url. for example, if set to true the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match. it defaults to false. ignoremethod: a boolean that, when set to true, prevents matching operations from validating the request http method (normally only get and head are allowed.) it defaults to false. ignorevary: a boolean that when set to true tells the matching operation not to perform vary header matching — i.e. if the url matches you will get a match regardless of whether th...
Cache.matchAll() - Web APIs
Web › API › Cache › matchAll
, you will get a copy of all responses in this cache. options optional an options object allowing you to set specific control options for the matching performed. the available options are: ignoresearch: a boolean that specifies whether the matching process should ignore the query string in the url. if set to true, the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match. it defaults to false. ignoremethod: a boolean that, when set to true, prevents matching operations from validating the request http method (normally only get and head are allowed.) it defaults to false. ignorevary: a boolean that when set to true tells the matching operation not to perform vary header matching — i.e. if the url matches you will get a match regardless of the respon...
CacheStorage.match() - Web APIs
ch. this can be a request object or a url string. options optional an object whose properties control how matching is done in the match operation. the available options are: ignoresearch: a boolean that specifies whether the matching process should ignore the query string in the url. for example, if set to true, the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match. it defaults to false. ignoremethod: a boolean that, when set to true, prevents matching operations from validating the request http method (normally only get and head are allowed.) it defaults to false. ignorevary: a boolean that, when set to true, tells the matching operation not to perform vary header matching. in other words, if the url matches you will get a match regardless of ...
CanvasCaptureMediaStreamTrack.requestFrame() - Web APIs
to prevent automatic capture of frames, so that frames are only captured when requestframe() is called, specify a value of 0 for the capturestream() method when creating the stream. ...
CanvasRenderingContext2D.arcTo() - Web APIs
ent.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(180, 90); ctx.arcto(180,130, 110,130, 130); ctx.lineto(110, 130); ctx.stroke(); result live demo more sophisticated demo of the method. you can play around with range input to see how arc changes. ...
CanvasRenderingContext2D.clip() - Web APIs
e: be aware that the clipping region is only constructed from shapes added to the path. it doesn't work with shape primitives drawn directly to the canvas, such as fillrect(). instead, you'd have to use rect() to add a rectangular shape to the path before calling clip(). syntax void ctx.clip([fillrule]); void ctx.clip(path [, fillrule]); parameters fillrule the algorithm by which to determine if a point is inside or outside the clipping region. possible values: "nonzero": the non-zero winding rule. default rule. "evenodd": the even-odd winding rule. path a path2d path to use as the clipping region. examples a simple clipping region this example uses the clip() method to create a clipping region according to the shape of a circular arc. two rectangles are then drawn; o...
CanvasRenderingContext2D.drawImage() - Web APIs
aling of the drawn image. if not specified, the image is not scaled in height when drawn. exceptions thrown index_size_err if the canvas or source rectangle width or height is zero. invalid_state_err the image has no image data. type_mismatch_err the specified source element isn't supported. ns_error_not_available the image is not loaded yet. use .complete === true and .onload to determine when it is ready. examples drawing an image to the canvas this example draws an image to the canvas using the drawimage() method. html <canvas id="canvas"></canvas> <div style="display:none;"> <img id="source" src="https://udn.realityripple.com/samples/db/f374e9c6fc.jpg" width="300" height="227"> </div> javascript the source image is taken from the coordinates (33, 71), ...
CanvasRenderingContext2D.ellipse() - Web APIs
y) with the radii radiusx and radiusy. the path starts at startangle and ends at endangle, and travels in the direction given by anticlockwise (defaulting to clockwise). parameters x the x-axis (horizontal) coordinate of the ellipse's center. y the y-axis (vertical) coordinate of the ellipse's center. radiusx the ellipse's major-axis radius. must be non-negative. radiusy the ellipse's minor-axis radius. must be non-negative. rotation the rotation of the ellipse, expressed in radians. startangle the angle at which the ellipse starts, measured clockwise from the positive x-axis and expressed in radians. endangle the angle at which the ellipse ends, measured clockwise from the positive x-axis and expressed in radians. anticlockwise optional an optional boolean which, if true,...
CanvasRenderingContext2D.fill() - Web APIs
possible values: "nonzero": the non-zero winding rule. default rule. "evenodd": the even-odd winding rule. path a path2d path to fill. examples filling a rectangle this example fills a rectangle with the fill() method. ...
CanvasRenderingContext2D.fillRect() - Web APIs
t is filled according to the current fillstyle. this method draws directly to the canvas without modifying the current path, so any subsequent fill() or stroke() calls will have no effect on it. syntax void ctx.fillrect(x, y, width, height); the fillrect() method draws a filled rectangle whose starting point is at (x, y) and whose size is specified by width and height. the fill style is determined by the current fillstyle attribute. parameters x the x-axis coordinate of the rectangle's starting point. y the y-axis coordinate of the rectangle's starting point. width the rectangle's width. positive values are to the right, and negative to the left. height the rectangle's height. positive values are down, and negative are up. examples a simple filled rectangle this example dr...
CanvasRenderingContext2D.imageSmoothingEnabled - Web APIs
on getting the imagesmoothingenabled property, the last value it was set to is returned. this property is useful for games and other apps that use pixel art. when enlarging images, the default resizing algorithm will blur the pixels. set this property to false to retain the pixels' sharpness. note: you can adjust the smoothing quality with the imagesmoothingquality property. syntax ctx.imagesmoothingenabled = value; options value a boolean indicating whether to smooth scaled images or not. ...
CanvasRenderingContext2D.isPointInPath() - Web APIs
point is contained in the current path. syntax ctx.ispointinpath(x, y [, fillrule]); ctx.ispointinpath(path, x, y [, fillrule]); parameters x the x-axis coordinate of the point to check, unaffected by the current transformation of the context. y the y-axis coordinate of the point to check, unaffected by the current transformation of the context. fillrule the algorithm by which to determine if a point is inside or outside the path. possible values: "nonzero": the non-zero winding rule. default rule. "evenodd": the even-odd winding rule. path a path2d path to check against. if unspecified, the current path is used. return value boolean a boolean, which is true if the specified point is contained in the current or specified path, otherwise false. examples checki...
CanvasRenderingContext2D.lineCap - Web APIs
note: lines can be drawn with the stroke(), strokerect(), and stroketext() methods. syntax ctx.linecap = "butt" || "round" || "square"; options "butt" the ends of lines are squared off at the endpoints. default value. "round" the ends of lines are rounded. "square" the ends of lines are squared off by adding a box with an equal width and half the height of the line's thickness. examples changing the shape of line caps this example rounds the end caps of a straight line. ...
CanvasRenderingContext2D.lineJoin - Web APIs
this property has no effect wherever two connected segments have the same direction, because no joining area will be added in this case. degenerate segments with a length of zero (i.e., with all endpoints and control points at the exact same position) are also ignored. note: lines can be drawn with the stroke(), strokerect(), and stroketext() methods. syntax ctx.linejoin = "bevel" || "round" || "miter"; options there are three possible values for this property: "round", "bevel", and "miter". the default is "miter". ...
CanvasRenderingContext2D.scrollPathIntoView() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.fillrect(10, 10, 30, 30); ctx.scrollpathintoview(); edit the code below to see your changes update live in the canvas: playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"> <input id="button" type="range" min="1" max="12"> </canvas> <div class="playable-buttons"> <input id="edit" type="button" value="edit" /> <input id="reset" type="button" value="reset" /> </div> <textarea id="code" class="playable-code"> ctx.beginpath(); ctx.rect(10, 10, 30, 30); ctx.scrollpathintoview();</textarea> var canvas = document.getelementbyid("canvas"); var ctx = canvas.getcontext("2d"); var textarea = document.getel...
CanvasRenderingContext2D.stroke() - Web APIs
in this example, the square on the left is drawn with the stroke on top of the fill. the square on the right is drawn with the fill on top of the stroke. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.linewidth = 16; ctx.strokestyle = 'red'; // stroke on top of fill ctx.beginpath(); ctx.re...
Advanced animations - Web APIs
...
Basic usage of canvas - Web APIs
<canvas>. scripts can also check for support programmatically by simply testing for the presence of the getcontext() method. our code snippet from above becomes something like this: var canvas = document.getelementbyid('tutorial'); if (canvas.getcontext) { var ctx = canvas.getcontext('2d'); // drawing code here } else { // canvas-unsupported code here } a skeleton template here is a minimalistic template, which we'll be using as a starting point for later examples. note: it is not good practice to embed a script inside html. we do it here to keep the example concise. <!doctype html> <html> <head> <meta charset="utf-8"/> <title>canvas tutorial</title> <script type="text/javascript"> function draw() { var canvas = document.getelementbyid('tutorial')...
Finale - Web APIs
Web › API › Canvas API › Tutorial › Finale
« previous congratulations! you finished the canvas tutorial! this knowledge will help you to make great 2d graphics on the web. more examples and tutorials there are a variety of demos and further explanations about canvas on these sites: codepen.io front end developer playground & code editor in the browser. html5 canvas tutorials examples for most canvas apis. game development gaming is one of the most popular computer activities. new technologies are constantly arriving to make it possible to develop better and more powerful games that can be run in any standards-compliant web browser. other web apis these apis might be useful when working further with canvas and graphics: webgl advanced api for rendering complex graphics, including 3d. svg scalable vector graphics...
Optimizing canvas - Web APIs
gate the need to render the background to the canvas on every tick. scaling canvas using css transforms css transforms are faster since they use the gpu. the best case is to not scale the canvas, or have a smaller canvas and scale up rather than a bigger canvas and scale down. var scalex = window.innerwidth / canvas.width; var scaley = window.innerheight / canvas.height; var scaletofit = math.min(scalex, scaley); var scaletocover = math.max(scalex, scaley); stage.style.transformorigin = '0 0'; //scale from top left stage.style.transform = 'scale(' + scaletofit + ')'; turn off transparency if your application uses canvas and doesn’t need a transparent backdrop, set the alpha option to false when creating a drawing context with htmlcanvaselement.getcontext(). this information can be u...
Transformations - Web APIs
he current origin by the angle number of radians. the rotation center point is always the canvas origin. to change the center point, we will need to move the canvas by using the translate() method. a rotate example in this example, we'll use the rotate() method to first rotate a rectangle from the canvas origin and then from the center of the rectangle itself with the help of translate(). reminder: angles are in radians, not degrees. to convert, we are using: radians = (math.pi/180)*degrees. function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); // left rectangles, rotate from canvas origin ctx.save(); // blue rect ctx.fillstyle = '#0095dd'; ctx.fillrect(30, 30, 100, 100); ctx.rotate((math.pi / 180) * 25); // grey rect ctx.fillstyle = '#4d4e...
Canvas API - Web APIs
ucators, and beginners. paper.js is an open-source vector graphics scripting framework that runs on top of the html5 canvas. phaser is a fast, free and fun open source framework for canvas and webgl powered browser games. processing.js is a port of the processing visualization language. pts.js is a library for creative coding and visualization in canvas and svg. rekapi is an animation key-framing api for canvas. scrawl-canvas is an open-source javascript library for creating and manipulating 2d canvas elements. the zim framework provides conveniences, components, and controls for coding creativity on the canvas — includes accessibility and hundreds of colorful tutorials. note: see the webgl api for 2d and 3d libaries that use webgl. specifications specification stat...
ChannelMergerNode - Web APIs
the channelmergernode interface, often used in conjunction with its opposite, channelsplitternode, reunites different mono inputs into a single output. each input is used to fill a channel of the output. this is useful for accessing each channels separately, e.g. for performing channel mixing where gain must be separately controlled on each channel. if channelmergernode has one single output, but as many inputs as there are channels to merge; the number of inputs is defined as a parameter of its constructor and the call to audiocontext.createchannelmerger. in the case that no value is given, it will default to 6. using a channelmergernode, it is possible to create outputs with more channels than the rendering hardware is able to process. in that case, when the signal is sent to the audio...
ChannelSplitterNode - Web APIs
if your channelsplitternode always has one single input, the amount of outputs is defined by a parameter on its constructor and the call to audiocontext.createchannelsplitter(). ...
Using channel messaging - Web APIs
l by calling messageport.postmessage on messagechannel.port2 that was initially transferred to the iframe. receiving the confirmation in the main page returning to the main page, let's now look at the onmessage handler function. // handle messages received on port1 function onmessage(e) { output.innerhtml = e.data; input.value = ''; } when a message is received back from the iframe confirming that the original message was received successfully, this simply outputs the confirmation to a paragraph and empties the text input ready for the next message to be sent. specifications specification status comment html living standardthe definition of 'channel messaging' in that specification. living standard ...
ChildNode.after() - Web APIs
Web › API › ChildNode › after
d=document; if(p!==null){ while(i<l){ e=m[i]; if(e instanceof n){ t=t.nextsibling; if(t!==null){ p.insertbefore(e,t); }else{ p.appendchild(e); }; }else{ p.appendchild(d.createtextnode(s(e))); }; ++i; }; }; }; }; })(element); /* minified: (function(x){ var o=x.prototype; o.after||(o.after=function(){var e,m=arguments,l=m.length,i=0,t=this,p=t.parentnode,n=node,s=string,d=document;if(p!==null){while(i<l){((e=m[i]) instanceof n)?(((t=t.nextsibling )!==null)?p.insertbefore(e,t):p.appendchild(e)):p.appendchild(d.createtextnode(s(e)));++i;}}}); }(element)); */ specification specification status comment ...
Clipboard - Web APIs
Web › API › Clipboard
mpleted. the promise is rejected if clipboard access is denied. the clipboard is a data buffer that is used for short-term, data storage and/or data transfers, this can be between documents or applications it is usually implemented as an anonymous, temporary data buffer, sometimes called the paste buffer, that can be accessed from most or all programs within the environment via defined programming interfaces. a typical application accesses clipboard functionality by mapping user input such as keybindings, menu selections, etc. to these interfaces. methods clipboard is based on the eventtarget interface, and includes its methods. read() requests arbitrary data (such as images) from the clipboard, returning a promise. when the data has been retrieved, the promise is resolved with a ...
Console API - Web APIs
concepts and usage the console api started as a largely proprietary api, with different browsers implementing it, albeit it in inconsistent ways. the console api spec was created to define consistent behavior, and all modern browsers eventually settled on implementing this behavior — although some implementations still have their own additional proprietary functions. ...
ConstantSourceNode - Web APIs
in addition, it can be used like a constructible audioparam by automating the value of its offset or by connecting another node to it; see controlling multiple parameters with constantsourcenode. a constantsourcenode has no inputs and exactly one monaural (one-channel) output. ...
ContentIndexEvent.id - Web APIs
ntation of the deleted content index id. examples this example listens for the contentdelete event and logs the removed content index id. the contentindexevent is only available to the {domxref('serviceworkerglobalscope','global scope')}} of a serviceworker. self.addeventlistener('contentdelete', (event) => { console.log(event.id); // logs content index id, which can then be used to determine what content to delete from your cache }); specifications specification status comment unknownthe definition of 'id' in that specification. unknown initial definition. ...
ContentIndexEvent - Web APIs
thods while contentindexevent offers no methods of its own, it inherits any specified by its parent interface, extendableevent. examples this example shows the sevice worker script listening for the contentdelete event and logs the removed content index id. self.addeventlistener('contentdelete', (event) => { console.log(event.id); // logs content index id, which can then be used to determine what content to delete from your cache }); specifications specification status comment unknownthe definition of 'contentindexevent' in that specification. unknown initial definition. ...
CredentialsContainer.preventSilentAccess() - Web APIs
entialscontainer interface sets a flag that specifies whether automatic log in is allowed for future visits to the current origin, then returns an empty promise. for example, you might call this, after a user signs out of a website to ensure that he/she isn't automatically signed in on the next site visit. mediation varies by origin, and is an added check point of browser stored credentials, informing a user of an account login status. this method is typically called after a user signs out of a website, ensuring this user's login information is not automatically passed on the next site visit. earlier versions of the spec called this method requireusermediation(). see browser compatibility for support details. syntax var promise = credentialscontainer.preventsilentaccess() parameters none...
DOMParser - Web APIs
Web › API › DOMParser
w domparser()​​ methods domparser.parsefromstring() syntax let doc = domparser.parsefromstring(string, mimetype) return either document or xmldocument depending on the mimetype argument. parameters this method has 2 parameters (both required): string the domstring to be parsed. it must contain either html, xml, xhtml+xml, or svg document. mimetype a domstring. this string determines a class of the the method's return value. the possible values are the following: mimetype doc.constructor text/html document text/xml xmldocument application/xml xmldocument application/xhtml+xml xmldocument image/svg+xml xmldocument examples parsing xml once you have created a...
DOMPointInit.x - Web APIs
Web › API › DOMPointInit › x
syntax var dompointinit = { x: xpos }; dompointinit.x = xpos; var xpos = dompointinit.x; value a double-precision floating-point value indicating the point's x coordinate. ...
DOMPointInit.y - Web APIs
Web › API › DOMPointInit › y
this may change if transforms have been applied causing the axes' orientation to change. ...
DOMPointInit - Web APIs
s 0. dompointinit.y an unrestricted floating-point number providing the point's y-coordinate. this is the vertical coordinate, and barring any transforms applied to the coordinate system, positive values are downward and negative values upward toward the top of the screen. the default is 0. dompointinit.z an unrestricted floating-point value which gives the point's z-coordinate, which is (assuming no transformations that alter the situation) the depth coordinate; positive values are closer to the user and negative values retreat back into the screen. the default value is 0. dompointinit.w the point's w perspective value, given as an unrestricted floating-point number. the default is 1. example this example creates a new dompoint representing the top-left corner of the current window,...
DOMPointReadOnly.x - Web APIs
the dompointreadonly interface's x property holds the horizontal coordinate, x, for a read-only point in space. this property cannot be changed by javascript code in this read-only version of the dompoint object. in general, positive values x mean to the right, and negative values of x means to the left, assuming no transforms have resulted in a reversal. syntax const xpos = somedompointreadonly.x; value a double-precision floating-point value indicating the x coordinate's value for the point. this value is unrestricted, meaning that it is allowed to be infinite or invalid (that is, its value may be nan or ±infinity). specifications specification status comment geometry interfaces module level 1the definition of 'x' in that specification. candidate reco...
DOMPointReadOnly.y - Web APIs
the dompointreadonly interface's y property holds the vertical coordinate, y, for a read-only point in space. if your script needs to be able to change the value of this property, you should instead use the dompoint object. in general, positive values of y mean downward, and negative values of y mean upward, assuming no transforms have resulted in a reversal. syntax const ypos = somedompointreadonly.y; value a double-precision floating-point value indicating the y coordinate's value for the point. this value is unrestricted, meaning that it is allowed to be infinite or invalid (that is, its value may be nan or ±infinity). specifications specification status comment geometry interfaces module level 1the definition of 'y' in that specification. candidate ...
DOMPointReadOnly.z - Web APIs
the dompointreadonly interface's z property holds the depth coordinate, z, for a read-only point in space. if your script needs to be able to change the value of this property, you should instead use the dompoint object. in general, positive values of z mean toward the user (out from the screen), and negative values of z mean away from the user (into the screen), assuming no transforms have resulted in a reversal. syntax const zpos = somedompointreadonly.z; value a double-precision floating-point value indicating the z coordinate's value for the point. this value is unrestricted, meaning that it is allowed to be infinite or invalid (that is, its value may be nan or ±infinity). specifications specification status comment geometry interfaces module level 1th...
DOMTokenList.supports() - Web APIs
if a given token is in the associated attribute's supported tokens. this method is intended to support feature detection. syntax let trueorfalse = element.supports(token) parameters token a domstring containing the token to query for. returns a boolean indicating whether the token was found. ...
DOMTokenList - Web APIs
tokenlist using element.classlist, add a class using domtokenlist.add(), and then update the node.textcontent of the <p> to equal the domtokenlist. first, the html: <p class="a b c"></p> now the javascript: let para = document.queryselector("p"); let classes = para.classlist; para.classlist.add("d"); para.textcontent = `paragraph classlist is "${classes}"`; the output looks like this: trimming of whitespace and removal of duplicates methods that modify the domtokenlist (such as domtokenlist.add()) automatically trim any excess whitespace and remove duplicate values from the list. for example: <span class=" d d e f"></span> let span = document.queryselector("span"); let classes = span.classlist; span.classlist.add("x"); span.textcontent = `span classlist is "${classes}"`; the ...
DataTransfer.dropEffect - Web APIs
ransfer object is created, dropeffect is set to a string value. on getting, it returns its current value. on setting, if the new value is one of the values listed below, then the property's current value will be set to the new value and other values will be ignored. for the dragenter and dragover events, dropeffect will be initialized based on what action the user is requesting. how this is determined is platform specific, but typically the user can press modifier keys such as the alt key to adjust the desired action. within event handlers for dragenter and dragover events, dropeffect should be modified if a different action is desired than the action that the user is requesting. for the drop and dragend events, dropeffect will be set to the action that was desired, which will be the value...
DataTransfer.effectAllowed - Web APIs
n is used to indicate that some form of relationship or connection will be created between the source and drop locations. this property should be set in the dragstart event to set the desired drag effect for the drag source. within the dragenter and dragover event handlers, this property will be set to whatever value was assigned during the dragstart event, thus effectallowed may be used to determine which effect is permitted. assigning a value to effectallowed in events other than dragstart has no effect. syntax datatransfer.effectallowed; values a domstring representing the drag operation that is allowed. the possible values are: none the item may not be dropped. copy a copy of the source item may be made at the new location. copylink a copy or link operation is permitted. c...
DataTransfer.mozClearDataAt() - Web APIs
if the format argument is not provided, then the data associated with all formats is removed. if the format is not found, then this method has no effect. if the last format for the item is removed, the entire item is removed, reducing mozitemcount by one. removing the last format for a particular index removes that item entirely, shifting the remaining items down and changing their indices. ...
DataTransfer.mozGetDataAt() - Web APIs
note: this method is gecko-specific. syntax nsivariant datatransfer.mozgetdataat([type], index); arguments type a string representing the type of the drag data to retrieve from the drag data object. ...
DataTransfer.mozSourceNode - Web APIs
for external drags or if the calling function cannot reach the node, null is returned. note: this property is gecko-specific. this property is read only . syntax datatransfer.mozsourcenode; return value a node representing node where the drag originated. returns null for external drags or if the node cannot be accessed. example this example shows the use of the mozsourcenode property in the dragend event handler. ...
DataTransfer.mozTypesAt() - Web APIs
the datatransfer.moztypesat() method returns a list of the format types that are stored for an item at the specified index. if the index is not in the range from 0 to the number of items minus one, an empty string list is returned. note: this method is gecko-specific. syntax nsivariant datatransfer.moztypesat(index); arguments index a unsigned long that is the index of the data for which to retrieve the types. return value nsivariant a list of data formats (which are strings). if the index is not in the range from 0 to the number of items minus one, an empty string list is returned. example this example shows the use of the moztypesat() method in a drop event handler. function drop_handler(event) { var dt = event.datatransfer; var count = dt.mozitemcount; output("...
DataTransfer.mozUserCancelled - Web APIs
if the user canceled the event, the property returns true and returns false otherwise. this property only applies to the dragend event. note: this property is gecko-specific. this property is read only . syntax datatransfer.mozusercancelled; return value a boolean representing true if the user canceled the drag event and returns false otherwise. example this example shows the use of the mozusercancelled property in the dragend event handler. ...
DedicatedWorkerGlobalScope.close() - Web APIs
ffectively closing this particular scope. syntax self.close(); example if you want to close your worker instance from inside the worker itself, you can call the following: close(); close() and self.close() are effectively equivalent — both represent close() being called from inside the worker's inner scope. note: there is also a way to stop the worker from the main thread: the worker.terminate method. specifications specification status comment html living standardthe definition of 'close()' in that specification. living standard ...
DelayNode.delayTime - Web APIs
syntax var audioctx = new audiocontext(); var mydelay = audioctx.createdelay(5.0); mydelay.delaytime.value = 3.0; note: though the audioparam returned is read-only, the value it represents is not. value an audioparam. ...
DeviceMotionEvent.interval - Web APIs
returns the interval, in milliseconds, at which data is obtained from the underlaying hardware. you can use this to determine the granularity of motion events. syntax var interval = devicemotionevent.interval; specifications specification status comment deviceorientation event specification editor's draft initial definition. ...
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. see orientation and motion data explained for details. syntax var absolute = instanceofdeviceorientationevent.absolute; on return, absolute is true if the orientation data in instanceofdeviceorientationevent is provided as the difference between the earth's coordinate frame and the device's coordinate frame, or false if the orientation data is being provided in reference to some arbitrary, device-determined coordinate frame. specifications specification status comment deviceorientation event specification editor's draft initial specification. ...
DirectoryEntrySync - Web APIs
ad entries from this directory. directoryreadersync createreader ( ) raises (fileexception); returns directoryreadersync represents a directory in a file system. parameter none exceptions this method can raise a fileexception with the following codes: exception description not_found_err the directory does not exist. security_err the browser determined that it was not safe to look up the metadata. [ todo: explain why ] getfile() depending on how you've set the options parameter, the method either creates a file or looks up an existing file. void getfile ( in domstring path, in optional flags options ) raises (fileexception); parameter path either an absolute path or a relative path from the directory to the file to be looked u...
DirectoryReaderSync - Web APIs
rysync readentries ( ) raises (fileexception); returns parameter none exceptions this method can raise a fileexception with the following codes: exception description not_found_err the directory does not exist. invalid_state_err the directory has been modified since the first call to readentries was processed. security_err the browser determined that it was not safe to look up the metadata. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox for androidopera for...
Document.cookie - Web APIs
Web › API › Document › cookie
steal-cookie.php?cookie=" + document.cookie; the httponly cookie attribute can help to mitigate this attack by preventing access to cookie value through javascript. read more about cookies and security. notes starting with firefox 2, a better mechanism for client-side storage is available - whatwg dom storage. you can delete a cookie by simply updating its expiration time to zero. keep in mind that the more cookies you have, the more data will be transferred between the server and the client for each request. this will make each request slower. it is highly recommended for you to use whatwg dom storage if you are going to keep "client-only" data. rfc 2965 (section 5.3, "implementation limits") specifies that there should be no maximum length of a cookie's key or value size, and encou...
Document.createDocumentFragment() - Web APIs
ragments could result in better performance. you can also use the documentfragment constructor to create a new fragment: let fragment = new documentfragment(); example this example creates a list of major web browsers in a documentfragment, then adds the new dom subtree to the document to be displayed. ...
Document.createEvent() - Web APIs
ine that the event name is 'build'. event.initevent('build', true, true); // listen for the event. elem.addeventlistener('build', function (e) { // e.target matches elem }, false); // target can be any element or other eventtarget. elem.dispatchevent(event); notes event type strings suitable for passing to createevent() are listed in the dom standard — see the table in step 2. bear in mind that most event objects now have constructors, which are the modern recommended way to create event object instances. gecko supports some non-standard event object aliases, which are listed below. event module standard event object gecko also supports text event module textevent textevents keyboard event module keyboardevent keyevents basic...
Document.createNodeIterator() - Web APIs
r the document tree. nodefilter.show_processing_instruction 64 shows processinginstruction nodes. nodefilter.show_text 4 shows text nodes. filter optional an object implementing the nodefilter interface. its acceptnode() method will be called for each node in the subtree based at root which is accepted as included by the whattoshow flag to determine whether or not to include it in the list of iterable nodes (a simple callback function may also be used instead). the method should return one of nodefilter.filter_accept, nodefilter.filter_reject, or nodefilter.filter_skip. see the example. note: prior to gecko 12.0 (firefox 12.0 / thunderbird 12.0 / seamonkey 2.9), this method accepted an optional fourth parameter (entityreferenceexpansion) ...
Document.createTreeWalker() - Web APIs
al. since entities are not part of the document tree, they do not appear when traversing over the document tree. nodefilter.show_processing_instruction 64 shows processinginstruction nodes. nodefilter.show_text 4 shows text nodes. filter optional a nodefilter, that is an object with a method acceptnode, which is called by the treewalker to determine whether or not to accept a node that has passed the whattoshow check. entityreferenceexpansion optional a boolean flag indicating if when discarding an entityreference its whole sub-tree must be discarded at the same time. return value a new treewalker object. example the following example goes through all nodes in the body, reduces the set of nodes to elements, simply passes through as...
Document.documentURIObject - Web APIs
al meaning and can be used just like any other custom property. privileged code must be careful not to try getting or setting this property on a non-wrapped content object (e.g., on a wrappedjsobject of an xpcnativewrapper). see bug 324464's comments for details. syntax var uri = document.documenturiobject; example // check that the uri scheme of the current tab in firefox is 'http', // assuming this code runs in context of browser.xul let uriobj = content.document.documenturiobject; let uriport = uriobj.port; if (uriobj.schemeis('http')) { ... } specifications not part of any specification. ...
Document.execCommand() - Web APIs
ion credentials from the cache. contentreadonly makes the content document either read-only or editable. this requires a boolean true/false as the value argument. (not supported by internet explorer.) copy copies the current selection to the clipboard. conditions of having this behavior enabled vary from one browser to another, and have evolved over time. check the compatibility table to determine if you can use it in your case. createlink creates an hyperlink from the selection, but only if there is a selection. requires a uri string as a value argument for the hyperlink's href. the uri must contain at least a single character, which may be whitespace. (internet explorer will create a link with a null value.) cut removes the current selection and copies it to the clipboard. when this...
Document.hasFocus() - Web APIs
Web › API › Document › hasFocus
when viewing a document, an element with focus is always the active element in the document, but an active element does not necessarily have focus. for example, an active element within a popup window that is not the foreground doesn't have focus. ...
Document.implementation - Web APIs
modname, modver ); alert( "dom " + modname + " " + modver + " supported?: " + conformtest ); // alerts with: "dom html 2.0 supported?: true" if dom level 2 html module is supported. a list of module names (e.g., core, html, xml, etc.) is available in the dom level 2 conformance section. notes the w3c's dom level 1 recommendation only specified the hasfeature method, which is one way to determine if a dom module is supported by a browser (see example above and what does your user agent claim to support?). if available, other domimplementation methods provide services for controlling things outside of a single document. for example, the domimplementation interface includes a createdocumenttype method with which dtds can be created for one or more documents managed by the implementation. ...
Document.lastModified - Web APIs
the lastmodified property of the document interface returns a string containing the date and time on which the current document was last modified. syntax var string = document.lastmodified; examples simple usage this example alerts the value of lastmodified. alert(document.lastmodified); // returns: tuesday, december 16, 2017 11:09:42 transforming lastmodified into a date object this example transforms lastmodified into a date object. let olastmodif = new date(document.lastmodified); transforming lastmodified into milliseconds this example transforms lastmodified into the number of milliseconds since january 1, 1970, 00:00:00, local time. let nlastmodif = date.parse(document.lastmodified); notes note that as a string, lastmodified cannot easily be used for comparing the mod...
Document.ononline - Web APIs
Web › API › Document › ononline
window.navigator.online returns boolean true if the browser is online and false if it is definitely offline (disconnected from the network). ...
Document: pointercancel event - Web APIs
bubbles yes cancelable no interface pointerevent event handler property onpointercancel some examples of situations that will trigger a pointercancel event: a hardware event occurs that cancels the pointer activities. this may include, for example, the user switching applications using an application switcher interface or the "home" button on a mobile device. the device's screen orientation is changed while the pointer is active. ...
Document.preferredStyleSheetSet - Web APIs
the preferredstylesheetset property returns the preferred style sheet set as set by the page author. syntax preferredstylesheetset = document.preferredstylesheetset on return, preferredstylesheetset indicates the author's preferred style sheet set. this is determined from the order of style sheet declarations and the default-style http header. if there isn't a preferred style sheet set defined by the author, the empty string ("") is returned. example if (document.preferredstylesheetset) { console.log("the preferred style sheet set is: " + document.preferredstylesheetset); } else { console.log("there is no preferred style sheet."); } ...
Document.queryCommandEnabled() - Web APIs
return value returns a boolean which is true if the command is enabled and false if the command isn't. notes for 'cut' and 'copy' commands the method only returns true when called from a user-initiated thread. ...
Document.queryCommandState() - Web APIs
of the 'bold' command</button> javascript function makebold() { var state = document.querycommandstate("bold"); switch (state) { case true: alert("the bold formatting will be removed from the selected text."); break; case false: alert("the selected text will be displayed in bold."); break; case null: alert("the state of the 'bold' command is indeterminable."); break; } document.execcommand('bold'); } result specifications specification status comment execcommand ...
Document.queryCommandSupported() - Web APIs
return value returns a boolean which is true if the command is supported and false if the command isn't. ...
Document.querySelectorAll() - Web APIs
if the array is empty (that is, its length property is 0), then no matches were found. otherwise, you can simply use standard array notation to access the contents of the list. you can use any common looping statement, such as: var highlighteditems = userlist.queryselectorall(".highlighted"); highlighteditems.foreach(function(useritem) { deleteuser(useritem); }); us...
Document.requestStorageAccess() - Web APIs
rules that the browser has. examples: allow lists, block lists, on-device classification, user settings, anti-clickjacking heuristics, or prompting the user for explicit permission. reject if some rule is not fulfilled. grant the document access to cookies and other site storage and store that fact for the purposes of future calls to document.hasstorageaccess() and requeststorageaccess(). assuming all of the requirements above are satisfied, firefox will automatically grant storage access to the requesting origin on up to a threshold number of first-party origins in the current session for the duration of user’s session, up to a maximum of 24 hours. after the requesting origin has exceeded the maximum allowable number of storage access grants, any future call to requeststorageaccess() d...
Document.xmlEncoding - Web APIs
should be null if unspecified or unknown. warning: do not use this attribute; it has been removed from the dom level 4 specification and is no longer supported in gecko 10.0 (firefox 10.0 / thunderbird 10.0 / seamonkey 2.7). ...
DocumentTimeline.DocumentTimeline() - Web APIs
that group of animations via their shared timeline. this bit of code would start all the cats animating 500 milliseconds into their animations: var cats = document.queryselectorall('.sharedtimelinecat'); cats = array.prototype.slice.call(cats); var sharedtimeline = new documenttimeline({ origintime: 500 }); cats.foreach(function(cat) { var catkeyframes = new keyframeeffect(cat, keyframes, timing); var catanimation = new animation(catkeyframes, sharedtimeline); catanimation.play(); }); specifications specification status comment web animationsthe definition of 'documenttimeline()' in that specification. working draft editor's draft. ...
DocumentTimeline - Web APIs
ns, thus allowing us to manipulate just that group of animations via their shared timeline. this bit of code would start all the cats animating 500 milliseconds into their animations: const cats = document.queryselectorall('.sharedtimelinecat'); const sharedtimeline = new documenttimeline({ origintime: 500 }); for (const cat of cats) { const catkeyframes = new keyframeeffect(cat, keyframes, timing); const catanimation = new animation(catkeyframes, sharedtimeline); catanimation.play(); } specifications specification status comment web animationsthe definition of 'documenttimeline' in that specification. working draft editor's draft. ...
Locating DOM elements using selectors - Web APIs
om are not reflected in the collection. this is different from other dom querying methods that return live node lists. you may find examples and details by reading the documentation for the element.queryselector() and element.queryselectorall() methods, as well as in the article code snippets for queryselector. selectors the selector methods accept one or more comma-separated selectors to determine what element or elements should be returned. for example, to select all paragraph (p) elements in a document whose css class is either warning or note, you can do the following: var special = document.queryselectorall( "p.warning, p.note" ); you can also query by id. for example: var el = document.queryselector( "#main, #basic, #exclamation" ); after executing the above code, el contains the...
Document Object Model (DOM) - Web APIs
usually, that means javascript, although modeling html, svg, or xml documents as objects are not part of the core javascript language, as such. the dom represents a document with a logical tree. each branch of the tree ends in a node, and each node contains objects. dom methods allow programmatic access to the tree. with them, you can change the document's structure, style, or content. nodes can also have event handlers attached to them. once an event is triggered, the event handlers get executed. ...
Element: DOMMouseScroll event - Web APIs
ed events are never sent with a value of 0 for detail. trusted events are never fired with 0. 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. if that element's font size is smaller than mousewheel.min_line_scroll_amount, that preference's value is used as the line height. ...
Element: MSManipulationStateChanged event - Web APIs
it is a proprietary event specific to microsoft edge and internet explorer. bubbles unknown cancelable unknown interface msmanipulationevent event handler property unknown get manipulation states using the laststate and currentstate properties. ...
Element.classList - Web APIs
Web › API › Element › classList
le object (an object whose properties cannot be directly modified). in ie9, however, it is possible through extending the prototype, freezing the visible object, and overwritting native property methods. however, such actions would not work in ie6-ie8 and, in ie9, slow the performance of the entire webpage to a snail's crawl, making these modifications completely impractical for this polyfill. a minor note is that in ie6-7, this polyfill uses the window[" ucl"] property on the window object for communicating with the css expressions, the x-uclp css property on all elements, and the element[" ucl"] property on all elements to allow garbage collection and boost performance. in all polyfilled browsers (ie6-9), an additional element[" uclp"] property is added to element to ensure standards compl...
Element.clientLeft - Web APIs
value to an integer. if you need a fractional value, use element.getboundingclientrect(). note: when an element has display: inline, clientleft returns 0 regardless of the element's border. syntax var left = element.clientleft; example padding-top lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. padding-bottom left top right bottom margin-top margin-bottom border-top border-bottom s...
Element.clientTop - Web APIs
Web › API › Element › clientTop
client area is show in white. (the segments labeled "top", "right", etc. have no significance regarding the client area.) the clienttop value is the distance from where the margin (yellow) area ends and the padding and content areas (white) begin. padding-top lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. padding-bottom left top right bottom margin-top margin-bottom border-top border-bottom n...
Element.namespaceURI - Web APIs
the element.namespaceuri read-only property returns the namespace uri of the element, or null if the element is not in a namespace. before dom4 this api was defined within the node interface. syntax namespace = element.namespaceuri example in this snippet, an element is being examined for its localname and its namespaceuri. if the namespaceuri returns the xul namespace and the localname returns "browser", then the node is understood to be a xul <browser/>. if (element.localname == "browser" && element.namespaceuri == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul") { // this is a xul browser } notes this is not a computed value that is the result of a namespace lookup based on an examination of the namespace declarations in scope. the namespace uri of a node i...
Element.onfullscreenchange - Web APIs
event that is fired when the element has transitioned into or out of full-screen mode. syntax targetdocument.onfullscreenchange = fullscreenchangehandler; value an event handler for the fullscreenchange event, indicating that the element has changed in or out of full-screen mode. example this example establishes a fullscreenchange event handler, handlefullscreenchange(). this function determines which element it was called on by checking the value of event.target, then compares the document's fullscreenelement value to the element to see if they're the same node. this gives us a value, isfullscreen, which we pass into a function called adjustmycontrols(), which we imagine to be a function that makes adjustments to the app's user interface to present itself optimally when it's in full-...
Element.querySelector() - Web APIs
endant element of baseelement which matches the specified group of selectors. the entire hierarchy of elements is considered when matching, including those outside the set of elements including baseelement and its descendants; in other words, selectors is first applied to the whole document, not the baseelement, to generate an initial list of potential elements. the resulting elements are then examined to see if they are descendants of baseelement. the first match of those remaining elements is returned by the queryselector() method. if no matches are found, the returned value is null. exceptions syntaxerror the specified selectors are invalid. examples let's consider a few examples. find a specific element with specific values of an attribute in this first example, the first <styl...
Element.querySelectorAll() - Web APIs
if the array is empty (that is, its length property is 0), then no matches were found. otherwise, you can simply use standard array notation to access the contents of the list. you can use any common looping statement, such as: var highlighteditems = userlist.queryselectorall(".highlighted"); highlighteditems.foreach(function(useritem) { deleteuser(useritem); }); n...
Element.requestFullscreen() - Web APIs
mall number of simple requirements: it must be one of the standard html elements or <svg> or <math>. it is not a <dialog> element. it must either be located within the top-level document or in an <iframe> which has the allowfullscreen attribute applied to it. additionally, of course, the feature policy "fullscreen" permission must be granted. 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. to learn when other code has toggled full-screen mode on and off, you should establish listeners for the fullscreenchange event on the document. it's also important to listen for fullscreenchange to be aware when, for example, the user manua...
Element.scrollTop - Web APIs
Web › API › Element › scrollTop
0. scrolltop doesn't respond to negative values; instead, it sets itself back to 0. if set to a value greater than the maximum available for the element, scrolltop settles itself to the maximum value. example padding-top if you can see this, scrolltop = 0 lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. if you can see this, scrolltop is > 0 duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. if you can see this, scrolltop is maxed-out padding-...
Element.toggleAttribute() - Web APIs
emoving it if it is present and adding it if it is not present) on the given element. syntax element.toggleattribute(name [, force]); parameters name a domstring specifying the name of the attribute to be toggled. the attribute name is automatically converted to all lower-case when toggleattribute() is called on an html element in an html document. force optional a boolean value to determine whether the attribute should be added or removed, no matter whether the attribute is present or not at the moment. return value true if attribute name is eventually present, and false otherwise. exceptions invalidcharactererror the specified attribute name contains one or more characters which are not valid in attribute names. example in the following example, toggleattribute() is use...
Event.cancelable - Web APIs
Web › API › Event › cancelable
// the event can be canceled, so we do so. event.preventdefault(); } else { // the event cannot be canceled, so it is not safe // to call preventdefault() on it. console.warn(`the following event couldn't be canceled:`); console.dir(event); } } document.addeventlistener('wheel', preventscrollwheel); notes whether an event can be canceled or not is something that's determined when that event is initialized. to cancel an event, call the preventdefault() method on the event. this keeps the implementation from executing the default action that is associated with the event. specifications specification status comment domthe definition of 'event.cancelable' in that specification. living standard document object model (dom) l...
Event.composed - Web APIs
Web › API › Event › composed
d (click/touch/mouseover/copy/paste, etc.). most other types of events are not composed, and so will return false. for example, this includes synthetic events that are created without their composed option wil set to true. propagation only occurs if the bubbles property is also true. however, capturing only composed events are also handled at host as if they were in at_target phase. you can determine the path the event will follow through the shadow root to the dom root by calling composedpath(). if this value is false, the shadow root will be the last node to be offered the event. examples in our composed-composed-path example (see it live), we define two trivial custom elements, <open-shadow> and <closed-shadow>, both of which take the contents of their text attribute and insert them in...
Event.preventDefault() - Web APIs
the event interface's preventdefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. the event continues to propagate as usual, unless one of its event listeners calls stoppropagation() or stopimmediatepropagation(), either of which terminates propagation at once. as noted below, calling preventdefault() for a non-cancelable event, such as one dispatched via eventtarget.dispatchevent(), without specifying cancelable: true has no effect. syntax event.preventdefault(); examples blocking default click handling toggling a checkbox is the default action of clicking on a checkbox. this example demonstrates how to prevent that from happening: javascript document.queryselector("#id-checkbox").ad...
Event.timeStamp - Web APIs
Web › API › Event › timeStamp
l <p> focus this iframe and press any key to get the current timestamp for the keypress event. </p> <p>timestamp: <span id="time">-</span></p> javascript function gettime(event) { var time = document.getelementbyid("time"); time.firstchild.nodevalue = event.timestamp; } document.body.addeventlistener("keypress", gettime); result reduced time precision to offer protection against timing attacks and fingerprinting, the precision of event.timestamp might get rounded depending on browser settings. in firefox, the privacy.reducetimerprecision preference is enabled by default and defaults to 20us in firefox 59; in 60 it will be 2ms. // reduced time precision (2ms) in firefox 60 event.timestamp; // 1519211809934 // 1519211810362 // 1519211811670 // ... // reduced time precision w...
EventSource.onmessage - Web APIs
event objects of onmessage event handers are of type messageevent. 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. ...
EventTarget.dispatchEvent() - Web APIs
get, (synchronously) invoking the affected eventlisteners in the appropriate order. the normal event processing rules (including the capturing and optional bubbling phase) also apply to events dispatched manually with dispatchevent(). syntax cancelled = !target.dispatchevent(event) parameter event is the event object to be dispatched. target is used to initialize the event.target and determine which event listeners to invoke. return value the return value is false if event is cancelable and at least one of the event handlers which received event called event.preventdefault(). otherwise it returns true. the dispatchevent() method throws unspecified_event_type_err if the event's type was not specified by initializing the event before the method was called, or if the event's type ...
ExtendableEvent.waitUntil() - Web APIs
the install events in service workers use waituntil() to hold the service worker in the installing phase until tasks complete. ...
FetchEvent() - Web APIs
options are as follows: clientid read only the client that the current service worker is controlling. ...
FetchEvent.replacesClientId - Web APIs
hen navigating from page a to page b replacesclientid is the id of the client associated with page a. it can be an empty string when navigating from about:blank to another page, as about:blank's client will be reused, rather than be replaced. additionally, if the fetch isn't a navigation, replacesclientid will be an empty string. this could be used to access/communicate with a client that will imminently be replaced, right before a navigation. syntax var myreplacedclientid = fetchevent.replacesclientid; value a domstring. example self.addeventlistener('fetch', function(event) { console.log(event.replacesclientid); }); specifications specification status comment service workersthe definition of 'replacesclientid' in that specification. working draft ini...
FetchEvent - Web APIs
d only the request the browser intends to make. methods inherits methods from its parent, extendableevent. fetchevent.respondwith() prevent the browser's default fetch handling, and provide (a promise for) a response yourself. extendableevent.waituntil() extends the lifetime of the event. used to notify the browser of tasks that extend beyond the returning of a response, such as streaming and caching. examples this fetch event uses the browser default for non-get requests. for get requests it tries to return a match in the cache, and falls back to the network. if it finds a match in the cache, it asynchronously updates the cache for next time. self.addeventlistener('fetch', event => { // let the browser do its default thing // for non-get requests. if (event.request.m...
Using Fetch - Web APIs
arraybuffer() blob() json() text() formdata() this makes usage of non-textual data much easier than it was with xhr. request bodies can be set by passing body parameters: const form = new formdata(document.getelementbyid('login-form')); fetch('/login', { method: 'post', body: form }); both request and response (and by extension the fetch() function), will try to intelligently determine the content type. a request will also automatically set a content-type header if none is set in the dictionary. feature detection fetch api support can be detected by checking for the existence of headers, request, response or fetch() on the window or worker scope. for example: if (window.fetch) { // run my fetch request here } else { // do something with xmlhttprequest? } polyfill to ...
Fetch API - Web APIs
Web › API › Fetch API
se objects (and other things involved with network requests). this will allow them to be used wherever they are needed in the future, whether it’s for service workers, cache api, and other similar things that handle or modify requests and responses, or any kind of use case that might require you to generate your responses programmatically (that is, the use of computer program or personal programming instructions). it also defines related concepts such as cors and the http origin header semantics, supplanting their separate definitions elsewhere. for making a request and fetching a resource, use the windoworworkerglobalscope.fetch() method. it is implemented in multiple interfaces, specifically window and workerglobalscope. this makes it available in pretty much any context you might want ...
File.lastModified - Web APIs
Web › API › File › lastModified
urrent time from date.now() at the moment the file object gets created. const filewithdate = new file([], 'file.bin', { lastmodified: new date(2017, 1, 1), }); console.log(filewithdate.lastmodified); //returns 1485903600000 const filewithoutdate = new file([], 'file.bin'); console.log(filewithoutdate.lastmodified); //returns current time reduced time precision to offer protection against timing attacks and fingerprinting, the precision of somefile.lastmodified might get rounded depending on browser settings. in firefox, the privacy.reducetimerprecision preference is enabled by default and defaults to 20us in firefox 59; in 60 it will be 2ms. // reduced time precision (2ms) in firefox 60 somefile.lastmodified; // 1519211809934 // 1519211810362 // 1519211811670 // ... // reduced tim...
File.lastModifiedDate - Web APIs
in firefox, the privacy.reducetimerprecision preference is enabled by default and defaults to 20us in firefox 59; in 60 it will be 2ms. // reduced time precision (2ms) in firefox 60 somefile.lastmodifieddate.gettime(); // 1519211809934 // 1519211810362 // 151921181...
File.type - Web APIs
Web › API › File › type
it is assumed based on the file extension; a png image file renamed to .txt would give "text/plain" and not "image/png". moreover, file.type is generally reliable only for common file types like images, html documents, audio and video. uncommon file extensions would return an empty string. client configuration (for instance, the windows registry) may result in unexpected values e...
FileRequest.onprogress - Web APIs
filerequest object and function is the javascript function to execute. each time the function callback is called, it gets an object as its first parameter. those objects contain two properties: loaded a number representing the current amount of bytes processed by the operation. total a number representing the total amount of bytes that will be processed by the operation. example // assuming 'request' which is a filerequest object request.onprogress = function (status) { var progress = document.queryselector('progress'); progress.value = status.loaded; progress.max = status.total; } specification not part of any current specification. ...
FileSystemDirectoryReader - Web APIs
the filesystemdirectoryreader interface of the file and directory entries api lets you access the fileentry-based objects (generally filesystemfileentry or filesystemdirectoryentry) representing each entry in a directory. because this is a non-standard api, whose specification is not currently on a standards track, it's important to keep in mind that not all browsers implement it, and those that do may implement only small portions of it. check the browser compatibility section for details. methods readentries() returns an array containing some number of the directory's entries. each item in the array is an object based on filesystementry—typically either filesystemfileentry or filesystemdirectoryentry. specifications specification status comment fi...
FileSystemEntry.copyTo() - Web APIs
lback which is executed if an error occurs while copying the items. there's a single parameter: a fileerror describing what went wrong. return value undefined. errors fileerror.invalid_modification_err the requested operation involves an impossible change, such as moving a directory inside itself or one of its own child directories, or copying an item within the same directory without renaming it. fileerror.quota_exceeded_err the operation exceeded the user's storage quota, or there isn't enough storage space left to complete the operation. example this example shows how a temporary log file might be moved into a more permanent "log" directory. workingdirectory.getfile("tmp/log.txt", {}, function(fileentry) { workingdirectory.getdirectory("log", {}, function(direntry) { fi...
FileSystemEntry.isDirectory - Web APIs
the read-only isdirectory property of the filesystementry interface is true if the entry represents a directory (meaning it's a filesystemdirectoryentry) and false if it's not. you can also use isfile to determine if the entry is a file. you should not assume that any entry which isn't a directory is a file or vice-versa. there are other types of file descriptors on many operating systems. be sure to use both isdirectory and isfile as needed to ensure that the entry is something you know how to work with. syntax var isdirectory = filesystementry.isdirectory; value a boolean indicating whether or not the filesystementry is a directory. example this example shows how this property might be used to determine whether to process the entry as a directory or file. if the entry is neithe...
FileSystemEntry.isFile - Web APIs
the read-only isfile property of the filesystementry interface is true if the entry represents a file (meaning it's a filesystemfileentry) and false if it's not. you can also use isdirectory to determine if the entry is a directory. you should not assume that any entry which isn't a file is a directory or vice-versa. there are other types of file descriptors on many operating systems. be sure to use both isdirectory and isfile as needed to ensure that the entry is something you know how to work with. syntax var isfile = filesystementry.isfile; value a boolean indicating whether or not the filesystementry is a file. example this example shows how this property might be used to determine whether to process the entry as a directory or file. if the entry is neither, an error handler ...
FileSystemEntry.moveTo() - Web APIs
llback which is executed if an error occurs while moving the items. there's a single parameter: a fileerror describing what went wrong. return value undefined. errors fileerror.invalid_modification_err the requested operation involves an impossible change, such as moving a directory inside itself or one of its own child directories, or copying an item within the same directory without renaming it. fileerror.quota_exceeded_err the operation exceeded the user's storage quota, or there isn't enough storage space left to complete the operation. example this example shows how a temporary log file might be moved into a more permanent "log" directory when it exceeds a megabyte in size. workingdirectory.getfile("tmp/log.txt", {}, function(fileentry) { fileentry.getmetadata(function(me...
FileSystemEntry.toURL() - Web APIs
ry file system that contains an image file named awesomesauce.jpg, the url returned by tourl() might be (depending on the browser's implementation) something like "filesystem:http://my-awesome-website.woot/temporary/awesomesauce.jpg". code that makes use of this might look like this: let img = document.createelement("img"); img.src = imagefileentry.tourl(); document.body.appendchild(img); assuming the scenario mentioned before the code, the result would be html that looks like this being appended to the end of the document: <img src="filesystem:http://my-awesome-website.woot/temporary/awesomesauce.jpg"> browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-co...
FileSystemEntry - Web APIs
ectories are represented by the directoryentry interface). it includes methods for working with files—including copying, moving, removing, and reading files—as well as information about a file it points to—including the file name and its path from the root to the entry. because this is a non-standard api, whose specification is not currently on a standards track, it's important to keep in mind that not all browsers implement it, and those that do may implement only small portions of it. check the browser compatibility section for details. basic concepts you don't create filesystementry objects directly. instead, you will receive an object based on this interface through other apis. this interface serves as a base class for the filesystemfileentry and filesystemdirectoryentry interf...
FileSystemEntrySync - Web APIs
tate_err the filesystemsync is no longer valid for some reason besides being deleted. moveto() move an entry to a different location on the file system. moving a file over an existing file replaces that existing file. moving a directory over an existing empty directory replaces that directory. [todo: what if the directory is not empty? ] [todo: verify ] this is the same method for renaming files. you can keep it in the same location and then define the newname parameter. you cannot do the following: move a directory inside itself or to any child at any depth move an entry into its parent if a name different from its current one isn't provided move a file to a path occupied by a directory or move a directory to a path occupied by a file move any element to a path occupied by...
FileSystemFlags.exclusive - Web APIs
syntax filesystemflags.exclusive = booleanvalue values the table below describes the result of each possible combination of these flags depending on whether or not the target file or directory path already exists. ...
FileHandle API - Web APIs
discussions on public-webapps led to the conclusion that the api would behave poorly in the case of different entities writing concurrently to the same file. the outcome of this discussion is the filehandle api with its lockedfile and transaction mechanism. specifications a formal specification draft is being written. as it does not fully match the current imple...
File and Directory Entries API - Web APIs
the file and directory entries api simulates a local file system that web apps can navigate within and access files in. you can develop apps which read, write, and create files and/or directories in a virtual, sandboxed file system. because this is a non-standard api, whose specification is not currently on a standards track, it's important to keep in mind that not all browsers implement it, and those that do may implement only small portions of it. check the browser compatibility section for details. two very similar apis exist depending on whether you desire asynchronous or synchronous behavior. the synchronous api is intended to be used inside a worker and will return the values you desire. the asynchronous api will not block and functions and the api will not return values; instead...
FontFace.display - Web APIs
Web › API › FontFace › display
this property is equivalent to the css font-display descriptor. when this property is used, font loading has a timeline with three periods. the lengths of the first two periods depend on the value of the property and the user agent. (see below.) block period the browser invisibly prepares a fallback font. if the font face loads during this time, it's used to display the text and display is complete. swap period if the font face is still not loaded, the fallback font will be shown. when the font face loads, the fallback will be swaped for the downloaded font. ...
FontFace - Web APIs
Web › API › FontFace
f the font face, being a url to an external resource, or a buffer; it also allows control of when the font face is loaded and its current status. constructor fontface() constructs and returns a new fontface object, built from an external resource described by an url or from an arraybuffer. properties this interface doesn't inherit any property. fontface.display a cssomstring that determines how a font face is displayed based on whether and when it is downloaded and ready to use. fontface.family a cssomstring that retrieves or sets the family of the font. it is equivalent to the font-family descriptor. fontface.featuresettings a cssomstring that retrieves or sets infrequently used font features that are not available from a font's variant properties. it is equivalent to the fon...
Force Touch events - Web APIs
he mouseup event. event properties the following property is known to be available on the webkitmouseforcewillbegin, mousedown, webkitmouseforcechanged, webkitmouseforcedown, webkitmouseforceup, mousemove, and mouseup event objects: mouseevent.webkitforce read only the amount of pressure currently being applied to the trackpad/touchscreen constants these constants are useful for determining the relative intensity of the pressure indicated by mouseevent.webkitforce: mouseevent.webkit_force_at_mouse_down read only minimum force necessary for a normal click mouseevent.webkit_force_at_force_mouse_down read only minimum force necessary for a force click specifications not part of any specification. apple has a description at the mac developer library. ...
FormData.append() - Web APIs
Web › API › FormData › append
xample 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. for example (and being compatible with php's naming conventions by adding [] to the name): formdata.append('userpic[]', myfileinput.files[0], 'chris1.jpg'); formdata.append('userpic[]', myfileinput.files[1], 'chris2.jpg'); this technique makes it simpler to process multi-file uploads because the resultant data structure is more conducive to looping. if the sent value is different than string or blob it will be automatically converted to string...
Fullscreen API - Web APIs
ace element.requestfullscreen() asks the user agent to place the specified element (and, by extension, its descendants) into full-screen mode, removing all of the browser's ui elements as well as all other applications from the screen. returns a promise which is resolved once full-screen mode has been activated. 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. documentorshadowroot.fullscreenelement the fullscreenelement property tells you the element that's currently being displayed in full-screen mode on the dom (or shadow dom). if this is null, the document is not in full-screen mode. document.fullscreenenabled the fu...
GainNode() - Web APIs
Web › API › GainNode › GainNode
resents a change in volume. note: you should typically call audiocontext.creategain() to create a gain node. syntax var gainnode = new gainnode(context, options) parameters inherits parameters from the audionodeoptions dictionary. context a reference to an audiocontext. options optional options are as follows: gain: the amount of gain to apply. this parameter is a-rate and it's nominal range is (-∞,+∞). the default is 1. return value a new gainnode object instance. specifications specification status comment web audio apithe definition of 'gainnode()' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribu...
Gamepad.timestamp - Web APIs
Web › API › Gamepad › timestamp
the gamepad.timestamp property of the gamepad interface returns a domhighrestimestamp representing the last time the data for this gamepad was updated. the idea behind this is to allow developers to determine if the axes and button data have been updated from the hardware. the value must be relative to the navigationstart attribute of the performancetiming interface. values are monotonically increasing, meaning that they can be compared to determine the ordering of updates, as newer values will always be greater than or equal to older values. note: this property is not currently supported anywhere. syntax readonly attribute domhighrestimestamp timestamp; example var gp = navigator.getgamepads()[0]; console.log(gp.timestamp); value a domhighrestimestamp. specifications ...
Geolocation - Web APIs
web page tries to access location information, the user is notified and asked to grant permission. be aware that each browser has its own policies and methods for requesting this permission. properties the geolocation interface neither implements, nor inherits any property. methods the geolocation interface doesn't inherit any method. geolocation.getcurrentposition() secure context determines the device's current location and gives back a geolocationposition object with the data. geolocation.watchposition() secure context returns a long value representing the newly established callback function to be invoked whenever the device location changes. geolocation.clearwatch() secure context removes the particular handler previously installed using watchposition(). specifications ...
GeolocationCoordinates.heading - Web APIs
if geolocationcoordinates.speed is 0, heading is nan. ...
GeolocationCoordinates.longitude - Web APIs
ent listener is established by calling addeventlistener() on the <button> element. when the user clicks the button, we'll fetch and display the location information. upon receiving a click event, we call getcurrentposition() to request the device's current position. this is an asynchronous request, so we provide a callback which receives as in put a geolocationposition object describing the determined position. 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. the two <span> elements are updated to display the corresponding values after being converted to a value with two decimal places. html the html used to present the results looks like this: <p> yo...
GeolocationCoordinates - Web APIs
t returns a double representing the accuracy of the altitude expressed in meters. this value can be null. geolocationcoordinates.heading read only secure context returns a double representing the direction towards which the device is facing. this value, specified in degrees, indicates how far off from heading true north the device is. 0 degrees represents true north, and the direction is determined clockwise (which means that east is 90 degrees and west is 270 degrees). if speed is 0, heading is nan. if the device is unable to provide heading information, this value is null. geolocationcoordinates.speed read only secure context returns a double representing the velocity of the device in meters per second. this value can be null. methods the geolocationcoordinates interface neither i...
GlobalEventHandlers.onanimationcancel - Web APIs
onname + "</code> at time " + event.elapsedtime.tofixed(2) + " seconds."; } logbox.innerhtml += "\n"; }; then we set up the handlecancelevent() function, which is called in response to the animationcancel event, as set up in the html above. all we do here is log information to the console, but you might find other use cases, such as starting a new animation or effect, or terminating some dependent operation. function handlecancelevent(event) { log("animation canceled", event); }; then we add a method to handle toggle display between "flex" and "none" and establish it as the handler for a click event on the "hide/show" the box button: document.getelementbyid('togglebox').addeventlistener('click', function() { if (box.style.display == "none") { box.style.displ...
GlobalEventHandlers.ongotpointercapture - Web APIs
the ongotpointercapture property of the globaleventhandlers mixin is an eventhandler that processes gotpointercapture events. syntax target.ongotpointercapture = functionref; value functionref is a function name or a function expression. the function receives a pointerevent object as its sole argument. example function overhandler(event) { // determine the target event's gotpointercapture handler let gotcapturehandler = event.target.ongotpointercapture; } function init() { let el = document.getelementbyid('target'); el.ongotpointercapture = overhandler; } specifications specification status comment pointer events – level 2the definition of 'ongotpointercapture' in that specification. recommendation ...
GlobalEventHandlers.onlostpointercapture - Web APIs
the onlostpointercapture property of the globaleventhandlers mixin is an eventhandler that processes lostpointercapture events. syntax target.onlostpointercapture = functionref; value functionref is a function name or a function expression. the function receives a pointerevent object as its sole argument. example function overhandler(event) { // determine the target event's lostpointercapture handler let lostcapturehandler = event.target.onlostpointercapture; } function init() { let el = document.getelementbyid('target'); el.onlostpointercapture = overhandler; } specifications specification status comment pointer events – level 2the definition of 'onlostpointercapture' in that specification. recommendation ...
GlobalEventHandlers.onpointerdown - Web APIs
action = "touching"; break; default: action = "interacting with"; break; } targetbox.innerhtml = "<strong>thanks for " + action + " me!</strong>"; evt.preventdefault(); } this simply uses onpointerdown to establish the function handledown() as the event handler for pointer down events. the handledown() function, in turn, looks at the value of pointertype to determine what kind of pointing device was used, then uses that information to customize a string to replace the contents of the target box. 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. we also have a handler for pointerup...
GlobalEventHandlers.ontransitioncancel - Web APIs
box:hover { background-color: #ffcccc; color: #000000; width: 200px; height: 200px; -webkit-transform: rotate(180deg); transform: rotate(180deg); } javascript next, we need to establish our event handlers to change the text content of the box when the transition begins and ends. ...
GlobalEventHandlers.ontransitionend - Web APIs
olor 2s, transform 2s, color 2s; } .box:hover { background-color: #ffcccc; color: #000000; width: 200px; height: 200px; transform: rotate(180deg); } javascript next, we need to establish our event handlers to change the text content of the box when the transition begins and ends. let box = document.queryselector(".box"); box.ontransitionrun = function(event) { box.innerhtml = "zooming..."; } box.ontransitionend = function(event) { box.innerhtml = "done!"; } result the resulting content looks like this: notice what happens when you hover your mouse cursor over the box, then move it away. specification specification status comment css transitionsthe definition of 'ontransitionend' in that specification. working draft ...
HTMLAnchorElement.download - Web APIs
y is a domstring indicating that the linked resource is intended to be downloaded rather than displayed in the browser. the value, if any, specifies the default file name for use in labeling the resource in a local file system. if the name is not a valid file name in the underlying os, the browser will adjust it. note: this value might not be used for download. this value cannot be used to determine whether the download will occur. syntax var dnload = anchorelt.download; anchorelt.download = dnload; specifications specification status comment html living standardthe definition of 'download' in that specification. living standard initial definition. ...
Audio() - Web APIs
w object's preload property is set to auto and its src property is set to the specified url or null if no url is given. if a url is specified, the browser begins to asynchronously load the media resource before returning the new object. usage notes you can also use other element-creation methods, such as the document object's createelement() method, to construct a new htmlaudioelement. determining when playback can begin there are three ways you can tell when enough of the audio file has loaded to allow playback to begin: check the value of the readystate property. if it's htmlmediaelement.have_future_data, there's enough data available to begin playback and play for at least a short time. if it's htmlmediaelement.have_enough_data, then there's enough data available that, given the ...
HTMLCollection - Web APIs
usage in javascript htmlcollection also exposes its members directly as properties by both name and index. html ids may contain : and . as valid characters, which would necessitate using bracket notation for property access. currently htmlcollections does not recognize purely numeric ids, which would cause conflict with the array-style access, though html5 does permit these. ...
HTMLDetailsElement: toggle event - Web APIs
mplaints against fortune. her very nature is caprice. </details> <details id="ch2"> <summary>chapter ii</summary> philosophy in fortune's name replies to boethius' reproaches, and proves that the gifts of fortune are hers to give and to take away. </details> <details id="ch3"> <summary>chapter iii</summary> boethius falls back upon his present sense of misery. philosophy reminds him of the brilliancy of his former fortunes. </details> </section> css body { display: flex; flex-direction: row-reverse; } #log { flex-shrink: 0; padding-left: 3em; } #summaries { flex-grow: 1; } javascript function logitem(e) { const item = document.queryselector(`[data-id=${e.target.id}]`); item.toggleattribute('hidden'); } const chapters = document.queryselectorall('...
HTMLElement.forceSpellCheck() - Web APIs
syntax element.forcespellcheck() ...
HTMLElement: pointercancel event - Web APIs
bubbles yes cancelable no interface pointerevent event handler property onpointercancel some examples of situations that will trigger a pointercancel event: a hardware event occurs that cancels the pointer activities. this may include, for example, the user switching applications using an application switcher interface or the "home" button on a mobile device. the device's screen orientation is changed while the pointer is active. ...
HTMLImageElement.complete - Web APIs
oaded; otherwise, the value is false. the image is considered completely loaded if any of the following are true: neither the src nor the srcset attribute is specified. the srcset attribute is absent and the src attribute, while specified, is the empty string (""). the image resource has been fully fetched and has been queued for rendering/compositing. the image element has previously determined that the image is fully available and ready for use. the image is "broken;" that is, the image failed to load due to an error or because image loading is disabled. it's worth noting that due to the image potentially being received asynchronously, the value of complete may change while your script is running. examples consider a photo library app that provides the ability to open images int...
HTMLImageElement.currentSrc - Web APIs
mage which is currently presented in the <img> element it represents. syntax let currentsource = htmlimageelement.currentsrc; value a usvstring indicating the full url of the image currently visible in the <img> element represented by the htmlimageelement. this is useful when you provide multiple image options using the sizes and/or htmlimageelement.srcset properties. currentsrc lets you determine which image from the set of provided images was selected by the browser. example in this example, two different sizes are provided for an image of a clock. one is 200px wide and the other is 400px wide. the sizes attribute is provided to indicate that the image should be drawn at 50% of the document width if the viewport is under 400px wide; otherwise, the image is drawn at 90% width of the do...
HTMLImageElement.height - Web APIs
at a width of 200px; otherwise, it's drawn at 300px. <p>image height: <span class="size">?</span>px (resize to update)</p> <img src="/files/17373/clock-demo-200px.png" alt="clock" srcset="/files/17373/clock-demo-200px.png 200w, /files/17374/clock-demo-400px.png 400w" sizes="(max-width: 400px) 200px, 300px"> javascript the javascript code looks at the height to determine the height of the image given the width at which it's currently drawn. var clockimage = document.queryselector("img"); let output = document.queryselector(".size"); const updateheight = event => { output.innertext = clockimage.height; }; window.addeventlistener("load", updateheight); window.addeventlistener("resize", updateheight); result this example may be easier to try out in its own ...
HTMLImageElement.naturalHeight - Web APIs
`${image.naturalheight} pixels<br>`; output.innerhtml += `displayed size: ${image.width} x ` + `${image.height} pixels`; }); the javascript code simply dumps the natural and as-displayed sizes into the <div> with the class output. this is done in response to the window's load event handler, in order to ensure that the image is available before attempting to examine its width and height. result specifications specification status comment html living standardthe definition of 'htmlimageelement.naturalheight' in that specification. living standard browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.
HTMLImageElement.naturalWidth - Web APIs
`${image.naturalheight} pixels<br>`; output.innerhtml += `displayed size: ${image.width} x ` + `${image.height} pixels`; }); the javascript code simply dumps the natural and as-displayed sizes into the <div> with the class output. this is done in response to the window's load event handler, in order to ensure that the image is available before attempting to examine its width and height. result specifications specification status comment html living standardthe definition of 'htmlimageelement.naturalwidth' in that specification. living standard browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.c...
HTMLImageElement.srcset - Web APIs
long with the sizes property, are a crucial component in designing responsive web sites, as they can be used together to make pages that use appropriate images for the rendering situation. syntax htmlimageelement.srcset = imagecandidatestrings; let srcset = htmlimageelement.srcset; value a usvstring containing a comma-separated list of one or more image candidate strings to be used when determining which image resource to present inside the <img> element represented by the htmlimageelement. each image candidate string must begin with a valid url referencing a non-interactive graphic resource. this is followed by a comma (,) character and then a condition descriptor that indicates the circumstances in which the indicated image should be used. space characters, other than the whitespace s...
HTMLImageElement.width - Web APIs
wn at a width of 200px; otherwise, it's drawn at 400px. <p>image width: <span class="size">?</span>px (resize to update)</p> <img src="/files/16864/clock-demo-200px.png" alt="clock" srcset="/files/16864/clock-demo-200px.png 200w, /files/16797/clock-demo-400px.png 400w" sizes="(max-width: 400px) 200px, 400px"> javascript the javascript code looks at the width to determine the width of the image at the moment. this is done in the window's load and resize event handlers, in order to always provide this information. var clockimage = document.queryselector("img"); let output = document.queryselector(".size"); const updatewidth = event => { output.innertext = clockimage.width; }; window.addeventlistener("load", updatewidth); window.addeventlistener("resize", update...
HTMLInputElement: invalid event - Web APIs
n blur. examples if a form is submitted with an invalid value, the submittable elements are checked and, if an error is found, the invalid event will fire on the invalid element. in this example, when an invalid event fires because of an invalid value in the input, the invalid value is logged. ...
HTMLMediaElement.canPlayType() - Web APIs
rvideo.canplaytype(mediatype); parameters mediatype a domstring containing the mime type of the media. return value a domstring indicating how likely it is that the media can be played. the string will be one of the following values: probably media of the type indicated by the mediatype parameter is probably playable on this device. maybe not enough information is available to determine for sure whether or not the media will play until playback is actually attempted. "" (empty string) media of the given type definitely can't be played on the current device. example var obj = document.createelement('video'); console.log(obj.canplaytype('video/mp4')); // "maybe" specifications specification status comment html living standardthe definition of 'canp...
HTMLMediaElement.currentTime - Web APIs
the given time, if the media is available. for media without a known duration—such as media being streamed live—it's possible that the browser may not be able to obtain parts of the media that have expired from the media buffer. also, media whose timeline doesn't begin at 0 seconds cannot be seeked to a time before its timeline's earliest time. the length of the media in seconds can be determined using the duration property. example var video = document.createelement('video'); console.log(video.currenttime); usage notes reduced time precision to offer protection against timing attacks and fingerprinting, browsers may round or otherwise adjust the value returned by currenttime. specifications specification status comment html living standardthe definition ...
HTMLMediaElement.disableRemotePlayback - Web APIs
syntax var remoteplaybackdisabled ​= element.disableremoteplayback; value a boolean indicating whether the media element may have a remote playback ui. (false means "not disabled", which means "enabled") example var obj = document.createelement('audio'); obj.disableremoteplayback = true; specifications specification status comment remote playback apithe definition of 'disableremoteplayback' in that specification. ...
HTMLMediaElement: ended event - Web APIs
this event occurs based upon htmlmediaelement (<audio> and <video>) fire ended when playback of the media reaches the end of the media. ...
HTMLMediaElement.error - Web APIs
syntax var myerror = htmlmediaelement.error; value a mediaerror object describing the most recent error to occur on the media element or null if no errors have occurred. example this example establishes a video element and adds an error handler to it; the error handler simply logs the details to console. ...
HTMLMediaElement.load() - Web APIs
the htmlmediaelement method load() resets the media element to its initial state and begins the process of selecting a media source and loading the media in preparation for playback to begin at the beginning. the amount of media data that is prefetched is determined by the value of the element's preload attribute. this method is generally only useful when you've made dynamic changes to the set of sources available for the media element, either by changing the element's src attribute or by adding or removing <source> elements nested within the media element itself. load() will reset the element and rescan the available sources, thereby causing the changes to take effect. syntax mediaelement.load(); parameters none. return value undefined. usage notes calling load() aborts all ongoing...
HTMLMediaElement: stalled event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onstalled specification html5 media examples these examples add an event listener for the htmlmediaelement's stalled event, then post a message when that event handler has reacted to the event firing. ...
HTMLMediaElement: timeupdate event - Web APIs
user agents are encouraged to vary the frequency of the event based on the system load and the average cost of processing the event each time, so that the ui updates are not any more frequent than the user agent can comfortably handle while decoding the video. ...
HTMLMeterElement.labels - Web APIs
the htmlmeterelement.labels read-only property returns a nodelist of the <label> elements associated with the <meter> element. syntax var labelelements = meter.labels; return value a nodelist containing the <label> elements associated with the <meter> element. ...
HTMLOrForeignElement.nonce - Web APIs
in later implementations, elements only expose their nonce attribute to scripts (and not to side-channels like css attribute selectors). ...
HTMLOrForeignElement - Web APIs
actually create an object of type htmlorforeignelement. propertiesdataset read only the dataset read-only property of the htmlorforeignelement interface provides read/write access to all the custom data attributes (data-*) set on the element.nonce the nonce property of the htmlorforeignelement interface returns the cryptographic number used once that is used by content security policy to determine whether a given fetch will be allowed to proceed.tabindexthe tabindex property of the htmlorforeignelement interface represents the tab order of the current element.methodsblur()the htmlelement.blur() method removes keyboard focus from the current element.focus()the htmlelement.focus() method sets focus on the specified element, if it can be focused. the focused element is the element which will...
HTMLTrackElement.src - Web APIs
the htmltrackelement.src property reflects the value of the <track> element's src attribute, which indicates the url of the text track's data. syntax var texttrackurl = htmltrackelement.src; value a domstring object containing the url of the text track data. example // coming soon specifications specification status comment html living standardthe definition of 'htmltrackelement.src' in that specification. living standard no change from html5 html5the definition of 'htmltrackelement.src' in that specification. recommendation initial definition. ...
HTMLVideoElement.msIsStereo3D - Web APIs
msisstereo3d is a read-only property which determines whether the system considers the loaded video source to be stereo 3-d or not. this proprietary property is specific to internet explorer and microsoft edge. syntax htmlvideoelement.msisstereo3d: boolean; value boolean value set to true indicates that the video source is stereo 3d. this uses metadata set in mp4 or mpeg-2 file containers and h.264 supplemental enhancement information (sei) messages to determine the stereo capability of the source. ...
HTMLVideoElement.msZoom - Web APIs
the black bars on either the left and right of the video or the top and bottom of the video. when the mszoom attribute is set to true, the rendered video is trimmed to fit the dimensions of the video object. either the top and bottom of the video is trimmed or the left and right of the video is trimmed. for instance, if the layout space for the video tag is a 4:3 aspect ratio, but the stream coming in is in 16:9 aspect ratio, the mszoom option can be used to render the 16:9 video in 4:3 aspect ratio. the rendered video will then take up the full space of the video object. example this examples gets a video object and sets the mszoom property to true. var myvideo = document.getelementbyid("videotag1"); myvideo.mszoom = true; myvideo.play(); see also htmlvideoelemen...
The HTML DOM API - Web APIs
ort for accessing various information provided by the http headers when loading the page, such as the location from which the document was loaded, cookies, modification date, referring site, and so forth. access to lists of elements in the document's <head> block and body, as well as lists of the images, links, scripts, etc. contained in the document. support for interacting with the user by examining focus and by executing commands on editable content. event handlers for document events defined by the html standard to allow access to mouse and keyboard events, drag and drop, media control, and more. event handlers for events that can be delivered to both elements and documents; these presently include only copy, cut, and paste actions. html element interfaces the element interface has...
Recommended Drag Types - Web APIs
rn a frozen array of domstrings rather than a domstringlist (this is supported in firefox 52 and above). as a result, the contains method no longer works; the includes method should be used instead to check if a specific type of data is provided, using code like the following: if ([...event.datatransfer.types].includes('text/html')) { // do something } you could use feature detection to determine which method is supported on types, then run code as appropriate. dragging images direct image dragging is not common. in fact, mozilla does not support direct image dragging on mac or linux. instead, images are usually dragged only by their urls. to do this, use the text/uri-list type as with other urls. the data should be the url of the image, or a data: uri if the image is not stored on a w...
History.back() - Web APIs
Web › API › History › back
syntax history.back() examples the following short example causes a button on the page to navigate back one entry in the session history. ...
History.forward() - Web APIs
Web › API › History › forward
syntax history.forward() examples the following examples create a button that moves forward one step in the session history. ...
History.go() - Web APIs
Web › API › History › go
syntax history.go([delta]) parameters delta optional the position in the history to which you want to move, relative to the current page. a negative value moves backwards, a positive value moves forwards. ...
Working with the History API - Web APIs
alling history.back() normally behaves the same way as clicking the back button. but there is one important exception: after using history.pushstate(), calling history.back() does not raise a popstate event. clicking the browser's back button (still) does. the pushstate() method pushstate() takes three parameters: a state object; a title (currently ignored); and (optionally), a url. let's examine each of these three parameters in more detail. state object the state object is a javascript object which is associated with the new history entry created by pushstate(). whenever the user navigates to the new state, a popstate event is fired, and the state property of the event contains a copy of the history entry's state object. the state object can be anything that can be serialized. be...
History API - Web APIs
ove forward a page, just like calling forward(): window.history.go(1) similarly, you can move forward 2 pages by passing 2, and so forth. another use for the go() method is to refresh the current page by either passing 0, or by invoking it without an argument: // the following statements // both have the effect of // refreshing the page window.history.go(0) window.history.go() you can determine the number of pages in the history stack by looking at the value of the length property: let numberofentries = window.history.length interfaces history allows manipulation of the browser session history (that is, the pages visited in the tab or frame that the current page is loaded in). examples the following example assigns a listener to the onpopstate property. and then illustrates s...
IDBCursor.continuePrimaryKey() - Web APIs
a previous cursor has been closed, without having to compare the keys one by one. calling this method more than once before new cursor data has been loaded - for example, calling continueprimarykey() twice from the same onsuccess handler - results in an invalidstateerror being thrown on the second call because the cursor’s got value flag has been unset. this method is only valid for cursors coming from an index. using it for cursors coming from an object store will throw an error. note: this feature is available in web workers. syntax cursor.continueprimarykey(key, primarykey); parameters key the key to position the cursor at. primarykey the primary key to position the cursor at. exceptions this method may raise a domexception of one of the following types: exceptio...
IDBDatabase.createObjectStore() - Web APIs
db = event.target.result; db.onerror = function(event) { note.innerhtml += "<li>error loading database.</li>"; }; // 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 }); objectstore.createindex("day", "day", { unique: false }); objectstore.createindex("month", "month", { unique: false }); objectstore.createindex("year", "year", { unique: false }); objectstore.createindex("notified", "notified", { unique: false }); note.innerhtml += "<li>object store created.</li>"; }; specification specification stat...
IDBDatabase.onabort - Web APIs
pening database.</li>'; }; db.onabort = function() { note.innerhtml += '<li>database opening aborted!</li>'; }; // 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 }); objectstore.createindex("day", "day", { unique: false }); objectstore.createindex("month", "month", { unique: false }); objectstore.createindex("year", "year", { unique: false }); objectstore.createindex("notified", "notified", { unique: false }); note.innerhtml += '<li>object store created.</li>'; }; specifications specification stat...
IDBDatabase.onerror - Web APIs
g database.</li>'; }; db.onabort = function(event) { note.innerhtml += '<li>database opening aborted!</li>'; }; // 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 }); objectstore.createindex("day", "day", { unique: false }); objectstore.createindex("month", "month", { unique: false }); objectstore.createindex("year", "year", { unique: false }); objectstore.createindex("notified", "notified", { unique: false }); note.innerhtml += '<li>object store created.</li>'; }; specifications specification stat...
IDBDatabase.onversionchange - Web APIs
g database.</li>'; }; db.onabort = function(event) { note.innerhtml += '<li>database opening aborted!</li>'; }; // 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 }); objectstore.createindex("day", "day", { unique: false }); objectstore.createindex("month", "month", { unique: false }); objectstore.createindex("year", "year", { unique: false }); objectstore.createindex("notified", "notified", { unique: false }); note.innerhtml += '<li>object store created.</li>'; db.onversionchange = function(event) { note...
IDBDatabaseException - Web APIs
attributes attribute type description code unsigned short the most appropriate error code for the condition. message domstring error message describing the exception raised. ...
IDBFactory.cmp() - Web APIs
Web › API › IDBFactory › cmp
note: this feature is available in web workers. note: do not use this method for comparing arbitrary javascript values, because many javascript values are either not valid indexeddb keys (booleans and objects, for example) or are treated as equivalent indexeddb keys (for example, since indexeddb ignores arrays with non-numeric properties and treats them as empty arrays, so any non-numeric arrays are treated as equivalent). this throws an exception if either of the values is not a valid key. ...
IDBIndex.name - Web APIs
Web › API › IDBIndex › name
opera ? safari ? webview android full support ...
IDBLocaleAwareKeyRange - Web APIs
t it is intended for use with idbindex objects when the original index had a locale value specified upon its creation (see createindex()'s optionalparameters) — that is, it has locale aware sorting enabled. methods this interface inherits all the methods of its parent interface, idbkeyrange. properties this interface inherits all the properties of its parent interface, idbkeyrange. bear in mind however that idblocaleawarekeyrange has its own implementation of idbkeyrange.bound. this is because when you use bound(), it checks if lower bound < upper bound, and throws an exception if that’s not the case. with locale-aware indexes, the meaning of < depends on the locale, so for example in lithuanian y is sorted between i and k. the only difference between idbkeyrange and idblocaleawareke...
IDBObjectStore.autoIncrement - Web APIs
event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBObjectStore.delete() - Web APIs
the delete() method of the idbobjectstore interface returns an idbrequest object, and, in a separate thread, deletes the specified record or records. either a key or an idbkeyrange can be passed, allowing one or multiple records to be deleted from a store. to delete all records in a store, use idbobjectstore.clear. 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. note: this feature is available in web workers. syntax var request = objectstore.delete(key); var request = objectstore.delete(keyrange); parameters key the key of the record to be deleted, or an idbkeyrange to delete all records with keys in range. return value an idbreq...
IDBObjectStore.deleteIndex() - Web APIs
var db = this.result; db.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; // 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 }); objectstore.createindex("day", "day", { unique: false }); objectstore.createindex("month", "month", { unique: false }); objectstore.createindex("year", "year", { unique: false }); objectstore.createindex("notified", "notified", { unique: false }); objectstore.deleteindex("seconds"); objectstore.deleteindex("contact"); }; specifications ...
IDBObjectStore.indexNames - Web APIs
function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBObjectStore.keyPath - Web APIs
event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBObjectStore.openCursor() - Web APIs
note: this feature is available in web workers. ...
IDBObjectStore.openKeyCursor() - Web APIs
the openkeycursor() method of the idbobjectstore interface returns an idbrequest object whose result will be set to an idbcursor that can be used to iterate through matching results. used for iterating through the keys of an object store with a cursor. to determine if the add operation has completed successfully, listen for the results’s success event. syntax var request = objectstore.openkeycursor(); var request = objectstore.openkeycursor(query); var request = objectstore.openkeycursor(query, direction); parameters query optional the key range to be queried. if a single valid key is passed, this will default to a range containing only that key. if nothing is passed, this will default to a key range that selects all the records in this object store. direction optional an idbc...
IDBObjectStore.put() - Web APIs
store when the transaction's mode is readwrite. if the record is successfully stored, then a success event is fired on the returned request object with the result set to the key for the stored record, and the transaction set to the transaction in which this object store is opened. the put method is an update or insert method. see the idbobjectstore.add method for an insert only method. 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(). doing so makes it clear that an existing record will be updated, instead of a new record being inserted. note: this feature is available in web workers. syntax let request = objectstore.put(item); let request = objectstore.put(item, key); parameters ...
IDBObjectStore.transaction - Web APIs
event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBTransaction.abort() - Web APIs
t) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBTransaction.db - Web APIs
Web › API › IDBTransaction › db
note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBTransaction.error - Web APIs
note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBTransaction.mode - Web APIs
note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBTransaction.objectStore() - Web APIs
note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBTransaction.onabort - Web APIs
note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBTransaction.oncomplete - Web APIs
note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBTransaction.onerror - Web APIs
note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
IdleDeadline.didTimeout - Web APIs
method will return approximately 0. idle callbacks support the concept of a timeout in order to ensure that whatever task they're meant to perform actually happens, even if the user agent never has enough idle time available. your callback will typically check the value of didtimeout if it needs to perform an action even if the browser is too busy to grant you the time; you should react by performing the needed task or, ideally, a minimal amount of work that can be done to keep things moving along, then schedule a new callback to try again to get the rest of the work done. syntax var timedout = idledeadline.didtimeout; value a boolean which is true if the callback is running due to the callback's timeout period elapsing or false if the callback is running because the user agent is idle a...
IdleDeadline.timeRemaining() - Web APIs
for example, if the callback finishes a task and has another one to begin, it can call timeremaining() to see if there's enough time to complete the next task. if there isn't, the callback can just return immediately, or look for other work to do with the remaining time. ...
ImageCapture() constructor - Web APIs
return value a new imagecapture object which can be used to capture still frames from the specified video track. ...
ImageCapture.getPhotoCapabilities() - Web APIs
e="range"]'); var imagecapture; navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); return imagecapture.getphotocapabilities(); }) .then(photocapabilities => { const settings = imagecapture.track.getsettings(); input.min = photocapabilities.imagewidth.min; input.max = photocapabilities.imagewidth.max; input.step = photocapabilities.imagewidth.step; return imagecapture.getphotosettings(); }) .then(photosettings => { input.value = photosettings.imagewidth; }) .catch(error => console.log('argh!', error.name || error)); specifications specification status comment mediastream image c...
ImageCapture.getPhotoSettings() - Web APIs
e="range"]'); var imagecapture; navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); return imagecapture.getphotocapabilities(); }) .then(photocapabilities => { const settings = imagecapture.track.getsettings(); input.min = photocapabilities.imagewidth.min; input.max = photocapabilities.imagewidth.max; input.step = photocapabilities.imagewidth.step; return imagecapture.getphotosettings(); }) .then(photosettings => { input.value = photosettings.imagewidth; }) .catch(error => console.log('argh!', error.name || error)); specifications specification status comment mediastream image c...
ImageCapture - Web APIs
b => createimagebitmap(blob)) .then(imagebitmap => { const canvas = document.queryselector('#takephotocanvas'); drawcanvas(canvas, imagebitmap); }) .catch(error => console.log(error)); } /* utils */ function drawcanvas(canvas, img) { canvas.width = getcomputedstyle(canvas).width.split('px')[0]; canvas.height = getcomputedstyle(canvas).height.split('px')[0]; let ratio = math.min(canvas.width / img.width, canvas.height / img.height); let x = (canvas.width - img.width * ratio) / 2; let y = (canvas.height - img.height * ratio) / 2; canvas.getcontext('2d').clearrect(0, 0, canvas.width, canvas.height); canvas.getcontext('2d').drawimage(img, 0, 0, img.width, img.height, x, y, img.width * ratio, img.height * ratio); } document.queryselector('video').addeventliste...
install - Web APIs
ray xpilist [, function callbackfunc ] ) parameters the install method has the following parameters: xpilist an array of files to be installed (see example below). callbackfunc an optional callback function invoked when the installation is complete (see example below). firefox 3 note in firefox 3 the callback is no longer invoked unless the website performing the installation is whitelisted. returns install returns true if the function succeeded and false if it did not, but these values are not always reliable as a determinant of the success of the operation. to surface detail about the status of the installation, use the optional callback function and its status parameter, as in the example below. description in the example below, a special ja...
IntersectionObserver.IntersectionObserver() - Web APIs
ty, it's set to the array [0.0]. syntax var observer = new intersectionobserver(callback[, options]); parameters callback a function which is called when the percentage of the target element is visible crosses a threshold. the callback receives as input two parameters: entries an array of intersectionobserverentry objects, each representing one threshold which was crossed, either becoming more or less visible than the percentage specified by that threshold. observer the intersectionobserver for which the callback is being invoked. options optional an optional object which customizes the observer. if options isn't specified, the observer uses the document's viewport as the root, with no margin, and a 0% threshold (meaning that even a one-pixel change is enough to trigger...
IntersectionObserver.root - Web APIs
property identifies the element or document whose bounds are treated as the bounding box of the viewport for the element which is the observer's target. if the root is null, then the bounds of the actual document viewport are used. syntax var root = intersectionobserver.root; value a element or document object whose bounding box is used as the bounds of the viewport for the purposes of determining how much of the target element is visible. the intersection of this bounding rectangle, offset by any margins specified in the options passed to the intersectionobserver() constructor, the target element's bounds, minus the bounds of every element or other object which overlaps the target element, is considered to be the visible area of the target element. if root is null, then the owning doc...
IntersectionObserverEntry.intersectionRatio - Web APIs
is true or 0 if not. example in this simple example, an intersection callback sets each target element's opacity to the intersection ratio of that element with the root. function intersectioncallback(entries) { entries.foreach(function(entry) { entry.target.style.opacity = entry.intersectionratio; }); } to see a more concrete example, take a look at handling intersection changes in timing element visibility with the intersection observer api. specifications specification status comment intersection observerthe definition of 'intersectionobserverentry.intersectionratio' in that specification. working draft initial definition ...
IntersectionObserverEntry.isIntersecting - Web APIs
llback is used to update a counter of how many targeted elements are currently intersecting with the intersection root. function intersectioncallback(entries) { entries.foreach(function(entry) { if (entry.isintersecting) { intersectingcount += 1; } else { intersectingcount -= 1; } }); } to see a more concrete example, take a look at handling intersection changes in timing element visibility with the intersection observer api. specifications specification status comment intersection observerthe definition of 'intersectionobserverentry.isintersecting' in that specification. working draft initial definition ...
IntersectionObserverEntry.target - Web APIs
ersectionobserver.observe() experienced a change in intersection with the root. example in this simple example, each targeted element's opacity is set to its intersectionratio. function intersectioncallback(entries) { entries.foreach(function(entry) { entry.target.opacity = entry.intersectionratio; }); } to see a more concrete example, take a look at handling intersection changes in timing element visibility with the intersection observer api. specifications specification status comment intersection observerthe definition of 'intersectionobserverentry.target' in that specification. working draft initial definition ...
IntersectionObserverEntry.time - Web APIs
tersection change occurred relative to the time at which the document was created. syntax var time = intersectionobserverentry.time; value a domhighrestimestamp which indicates the time at which the target element experienced the intersection change described by the intersectionobserverentry. the time is specified in milliseconds since the creation of the containing document. example see timing element visibility with the intersection observer api for a complete example which uses the time property to track how long elements are visible to the user. specifications specification status comment intersection observerthe definition of 'intersectionobserverentry.time' in that specification. working draft initial definition ...
Keyboard.lock() - Web APIs
Web › API › Keyboard › lock
ked. a list of valid code values is found in the ui events keyboardevent code values spec. return value a promise. examples capturing all keys the following example captures all keypresses. navigator.keyboard.lock(); capturing specific keys the following example captures the "w", "a", "s", and "d" keys. it captures these keys regardless of which modifiers are used with the key press. assuming a standard us qwerty layout, registering "keyw" ensures that "w", shift+"w", control+"w", control+shift+"w", and all other key modifier combinations with "w" are sent to the app. the same applies to for "keya", "keys" and "keyd". navigator.keyboard.lock(["keyw", "keya", "keys", "keyd"]); specifications specification status comment keyboard lockthe definition of 'lock...
KeyboardEvent.keyIdentifier - Web APIs
its non-deprecated replacement is keyboardevent.key. specifications not part of any current specification. ...
KeyframeEffect.getKeyframes() - Web APIs
ifying start and end states in percentages in css stylesheets using @keyframes. this will be null if the keyframe is automatically spaced using keyframeeffect.spacing. computedoffset the computed offset for this keyframe, calculated when the list of computed keyframes was produced according to keyframeeffect.spacing. unlike offset, above, the computedoffset is never null. easing the timing function used from this keyframe until the next keyframe in the series. composite the keyframeeffect.composite operation used to combine the values specified in this keyframe with the underlying value. this will be absent if the composite operation specified on the effect is being used. examples in the red queen race example, we can inspect alice and the redqueen's animation to see it...
KeyframeEffect.setKeyframes() - Web APIs
s described below. the following special attributes may also be specified: offset the offset of the keyframe specified as a number between 0.0 and 1.0 inclusive or null. this is equivalent to specifying start and end states in percentages in css stylesheets using @keyframes. if this value is null or missing, the keyframe will be evenly spaced between adjacent keyframes. easing the timing function used from this keyframe until the next keyframe in the series. composite the keyframeeffect.composite operation used to combine the values specified in this keyframe with the underlying value. this will be auto if the composite operation specified on the effect is being used. return value void. exceptions exception explanation typeerror one or ...
KeyframeEffect.target - Web APIs
of a keyframeeffect interface represents the element or pseudo-element being animated. it may be null for animations that do not target a specific element. it performs as both a getter and a setter, except with animations and transitions generated by css. syntax var targetelement = document.getelementbyid("elementtoanimate"); var keyframes = new keyframeeffect( targetelement, keyframeblock, timingoptions ); // returns #elementtoanimate keyframes.target; // assigns keyframes a new target keyframes.target = newtargetelement; value an element, csspseudoelement, or null. examples in the follow the white rabbit example, whiterabbit sets the target element to be animated: var whiterabbit = document.getelementbyid("rabbit"); var rabbitdownkeyframes = new keyframeeffect( whiterabbit, ...
Location: ancestorOrigins - Web APIs
the ancestororigins read-only property of the location interface is a static domstringlist containing, in reverse order, the origins of all ancestor browsing contexts of the document associated with the given location object. you can use location.ancestororigins in the script for a document to determine, for example, whenever the document is being framed by a site which you don’t expect it to be framed by. you can also use it to vary the behavior of the document based on what site or list of sites is framing it. syntax const ancestors = location.ancestororigins; specifications specification status comment html living standardthe definition of 'ancestororigins ' in that specification. living standard ...
LockedFile.abort() - Web APIs
Web › API › LockedFile › abort
the behavior may change in the future. summary the abort method is used to release the lock on the lockedfile object, making it inactive: its active property is set to false and all ongoing operations are canceled. note: when an ongoing operation is canceled, there is no rollback (it is not a database transaction), therefore the file can be corrupted if the canceled operation was performing some writing. syntax var request = instanceoflockedfile.abort(); return a filerequest object to handle the success or failure of the operation. specifications specification status comment filesystem api editor's draft draft proposal ...
Long Tasks API - Web APIs
0; i < perfentries.length; i++) { // process long task notifications: // report back for analytics and monitoring // ... } }); // register observer for long task notifications observer.observe({entrytypes: ["longtask"]}); // long script execution after this will result in queueing // and receiving "longtask" entries in the observer. interfaces performancelongtasktiming reports instances of long tasks. taskattributiontiming returns information about the work involved in a long task and its associate frame context. specifications specification status comment long tasks api 1 working draft initial definition. ...
MSCandidateWindowShow - Web APIs
uages. syntax event property object.oncandidatewindowshow = handler; addeventlistener method object.addeventlistener("mscandidatewindowshow", handler, usecapture) parameters pevtobj [in] type: ihtmleventobj pointer to an ihtmleventobj interface for the current event. this event fires after the positioning information of the ime candidate window has been determined. 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. web applications need only register for this event once per element (the handler will remain valid for the lifetime of the element). example in ie11, developers can detect the opening of the ime candidate window by ...
MediaCapabilities - Web APIs
the mediacapabilities interface of the media capabilities api provides information about the decoding abilities of the device, system and browser. the api can be used to query the browser about the decoding abilities of the device based on codecs, profile, resolution, and bitrates. the information can be used to serve optimal media streams to the user and determine if playback should be smooth and power efficient. the information is accessed through the mediacapabilities property of the navigator interface. methods mediacapabilities.encodinginfo() when passed a valid media configuration, it returns a promise with information as to whether the media type is supported, and whether encoding such media would be smooth and power efficient. mediacapabilities.decodinginfo() when passed a...
MediaDevices.getDisplayMedia() - Web APIs
, preventing the sharing of the selected source. overconstrainederror after creating the stream, applying the specified constraints fails because no compatible stream could be generated. typeerror the specified constraints include constraints which are not permitted when calling getdisplaymedia(). these unsupported constraints are advanced and any constraints which in turn have a member named min or exact. usage notes privacy and security because getdisplaymedia() could be used in nefarious ways, it can be a source of significant privacy and security concerns. for that reason, the specification details measures browsers are required to take in order to fully support getdisplaymedia(). the specified constraints can't be used to limit the options available to the user. instead, they ...
MediaDevices - Web APIs
devicechange fired when a media input or output device is attached to or removed from the user's computer. also available via the ondevicechange property. methods inherits methods from its parent interface, eventtarget. enumeratedevices() obtains an array of information about the media input and output devices available on the system. getsupportedconstraints() returns an object conforming to mediatracksupportedconstraints indicating which constrainable properties are supported on the mediastreamtrack interface. see capabilities and constraints in media capture and streams api (media stream) to learn more about constraints and how to use them. getdisplaymedia() prompts the user to select a display or portion of a display (such as a window) to capture as a mediastream for sharing...
MediaError.code - Web APIs
Web › API › MediaError › code
ants name value description media_err_aborted 1 the fetching of the associated resource was aborted by the user's request. media_err_network 2 some kind of network error occurred which prevented the media from being successfully fetched, despite having previously been available. media_err_decode 3 despite having previously been determined to be usable, an error occurred while trying to decode the media resource, resulting in an error. media_err_src_not_supported 4 the associated resource or media provider object (such as a mediastream) has been found to be unsuitable. example this example creates a <video> element, establishes an error handler for it, and then sets the element's src attribute to the video ...
MediaError - Web APIs
lows: name value description media_err_aborted 1 the fetching of the associated resource was aborted by the user's request. media_err_network 2 some kind of network error occurred which prevented the media from being successfully fetched, despite having previously been available. media_err_decode 3 despite having previously been determined to be usable, an error occurred while trying to decode the media resource, resulting in an error. media_err_src_not_supported 4 the associated resource or media provider object (such as a mediastream) has been found to be unsuitable. mediaerror.message a domstring object containing a human-readable string which provides specific diagnostic information to help the reader u...
MediaImage - Web APIs
rties src the url from which user agent can fetch the image's data. sizes specifies the resource in multiple sizes so that user agent does not have to scale a single image. type the mime type hint for the user agant. note that it is just a hint so that user agent may ignore images of types it does not support; user agent still may use mime type sniffing after downloading the image to determine its type. specifications specification status comment media session standardthe definition of 'mediaimage' in that specification. draft initial definition. ...
expiration - Web APIs
this value may change during a session lifetime, such as when an action triggers the start of a window. ...
MediaKeySession - Web APIs
ignaling when a mediakeysession closes. this promise can only be fulfilled and is never rejected. closing a session means that licenses and keys associated with it are no longer valid for decrypting media data. mediakeysession.expiration read only the time after which the keys in the current session can no longer be used to decrypt media data, or nan if no such time exists. this value is determined by the cdm and measured in milliseconds since january 1, 1970, utc. this value may change during a session lifetime, such as when an action triggers the start of a window. mediakeysession.keystatuses read only contains a reference to a read-only mediakeystatusmap of the current session's keys and their statuses. mediakeysession.sessionid read only contains a unique string generated by the...
MediaList.mediaText - Web APIs
the mediatext property of the medialist interface is a stringifier that returns a domstring representing the medialist as text, and also allows you to set a new medialist. syntax medialistinstance.mediatext; medialistinstance.mediatext = string; value a domstring representing the media queries of a stylesheet. each one is separated by a comma, for example screen and (min-width: 480px), print. if you wish to set new media queries on the document, the string value must have the different queries separated by commas, e.g. screen, print. note that the medialist is a live list; updating the list via mediatext will immediately update the behavior of the document. also note that is you try to set mediatext to null, it will be treated as an empty string, i.e. the value will be set to "". exam...
MediaPositionState.duration - Web APIs
owing the currently playing media as well as standard pause, play, forward, reverse, and other controls. syntax let positionstate = { duration: durationinseconds }; let durationinseconds = positionstate.duration; value a floating-point value indicating the overall duration, in seconds, of the media being performed. this value should always be positive. to indicate media of unknown or indeterminate length, such as an ongoing live stream, specify a value of positive infinity (infinity). example in this example, an app performing a live stream provides information to the browser by preparing a mediapositionstate object and submitting it by calling navigator.mediasession.setpositionstate(). let positionstate = { duration: infinity; playbackrate: 1.0; position: 0.0; }; navigator.me...
MediaQueryList - Web APIs
mpatibility; if possible, you should generally use removeeventlistener() to remove change notification callbacks (which should have previously been added using addeventlistener()). events the following events are delivered to mediaquerylist objects: change sent to the mediaquerylist when the result of running the media query against the document changes. for example, if the media query is (min-width: 400px), the change event is fired any time the width of the document's viewport changes such that its width moves across the 400px boundary in either direction. also available using the onchange event handler property. examples this simple example creates a mediaquerylist and then sets up a listener to detect when the media query status changes, running a custom function when it does t...
MediaRecorder.onerror - Web APIs
rorevent, and its error property contains a domexception object that describes the error that occurred. syntax mediarecorder.onerror = errorhandlerfunction; value a function to be called whenever an error occurs during the recorder's lifetime. 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. invalidstateerror an attempt was made to stop or pause or an inactive recorder, start or resume an active recorder, or otherwise manipulate the mediarecorder while in the wrong state. this exception can also occur when a request is made on a source that has been deleted or removed. securityerror the mediastream is confi...
MediaRecorder.pause() - Web APIs
if not, continue to the next step. set mediarecorder.state to "paused". stop gathering data into the current blob, but keep it available so that recording can be resumed later on. ...
MediaRecorder.requestData() - Web APIs
ethod (part of the mediarecorder api) is used to raise a dataavailable event containing a blob object of the captured media as it was when the method was called. this can then be grabbed and manipulated as you wish. when the requestdata() method is invoked, the browser queues a task that runs the following steps: if mediarecorder.state is not "recording", raise a dom invalidstate error and terminate these steps. if mediarecorder.state is "recording", continue to the next step. raise a dataavailable event containing a blob of the currently captured data (the blob is available under the event's data attribute.) create a new blob and place subsequently captured data into it. syntax mediarecorder.requestdata() errors an invalidstate error is raised if the requestdata() method is called...
MediaRecorder.resume() - Web APIs
if mediarecorder.state is not "inactive", continue to the next step. set mediarecorder.state to "recording". continue gathering data into the current blob. ...
MediaRecorder.start() - Web APIs
media into one or more blob objects. you can record the entire duration of the media into a single blob (or until you call requestdata()), or you can specify the number of milliseconds to record at a time. then, each time that amount of media has been recorded, an event will be delivered to let you act upon the recorded media, while a new blob is created to record the next slice of the media assuming the mediarecorder's state is inactive, start() sets the state to recording, then begins capturing media from the input stream. a blob is created and the data is collected in it until the time slice period elapses or the source media ends. each time a blob is filled up to that point (the timeslice duration or the end-of-media, if no slice duration was provided), a dataavailable event is sent to ...
MediaRecorder.stop() - Web APIs
if the mediarecorder.state is not "inactive", continue on to the next step. set the mediarecorder.state to "inactive" and stop capturing media. raise a dataavailable event containing the blob of data that has been gathered. raise a stop event. ...
MediaRecorderErrorEvent() - Web APIs
ng the recording of media by the mediastream recording api. in general, you won't create these yourself; they are delivered to your implementation of mediarecorder.onerror when errors occur while recording media. syntax var errorevent = new mediarecordererrorevent(errorinfo) parameters errorinfo an object describing the error object to be created. it must contain the error property at a minimum. error a domexception that describes the error that occurred. this object's name property should indicate the name of the error that occurred. the other fields may or may not be present. some user agents add to the error object other properties that provide information such as stack dumps, the name of the javascript file and the line number where the error occurred, and other deb...
MediaSession.setPositionState() - Web APIs
r presentation by user's device in any kind of interface that provides details about ongoing media. this can be particularly useful if your code implements a player for type of media not directly supported by the browser. call this method on the navigator object's mediasession object. syntax navigator.mediasession.setpositionstate(statedict); parameters statedict optional an object conforming to the mediapositionstate dictionary, providing updated information about the playback position and speed of the document's ongoing media. if the object is empty, the existing playback state information is cleared. return value undefined. exceptions typeerror this error can occur in an array of circumstances: the specified mediapositionstate object's duration is missing, negative,...
MediaSessionActionDetails.seekTime - Web APIs
stime = mediasessionactiondetails.seektime; value a floating-point value indicating the absolute time in seconds into the media to which to move the current play position. usage notes to perform a "fast" seek (such as when issuing multiple seekto actions in sequence while handling a scrubbing operation, the details object's fastseek property's value is set to true, indicating that you should minimize or eliminate anything you do while handling the action that is only necessary at the final step. if the value of fastseek is false, or fastseek is missing, the action should be treated as the final action of the operation, and you should finalize any details that need to be handled. specifications specification status comment media session standardthe definition of...
MediaSettingsRange.step - Web APIs
syntax var step = mediasettingsrange.step value a double integer. ...
MediaSource.isTypeSupported() - Web APIs
s that it can probably play media of the specified type. this is not a guarantee, however, and your code must be prepared for the possibility that the media will not play correctly if at all. a value of false is a guarantee that media of the given type will not play, however. all web apis that work with media files use a "no/maybe/probably" approach (or, in this case, "no or probably") when determining if a media type can be used. this is because media files are complex, intricate constructs with far too many subtle variations to be absolutely certain of anything until you actually use the contents of the media. example the following snippet is from an example written by nick desaulniers (view the full demo live, or download the source for further investigation.) var asseturl = 'frag_bunn...
MediaStreamAudioSourceNode - Web APIs
or the stream specified by the mediastream parameter does not contain any audio tracks. usage notes typically, you should probably not use this type of node. it has been replaced with the more predictable mediastreamtrackaudiosourcenode, which has better-defined rules for how it chooses the track to output. if you do chooose to use mediastreamaudiosourcenode, you should keep the following in mind. track ordering for the purposes of the mediastreamtrackaudiosourcenode interface, the order of the audio tracks on the stream is determined by taking the tracks whose kind is audio, then sorting the tracks by their id property's values, in unicode code point order (essentially, in alphabetical or lexicographical order, for ids which are simple alphanumeric strings). the first track, then, is...
MediaStreamTrack.applyConstraints() - Web APIs
web app needs a width between 640 and 1280 and a height between 480 and 720, with the later number in each pair being preferred. the advanced property further specifies that an image size of 1920 by 1280 is the preferred or an aspect ratio of 1.333 if that is not available. note that these constraints also illustrate what the spec refers to as a backoff strategy. 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. }) .catch(...
MediaStreamTrack.enabled - Web APIs
have every sample's value set to 0. empty video frames have every pixel set to black. note: when implementing a mute/unmute feature, you should use the enabled property. usage notes if the mediastreamtrack represents the video input from a camera, disabling the track by setting enabled to false also updates device activity indicators to show that the camera is not currently recording or streaming. for example, the green "in use" light next to the camera in imac and macbook computers turns off while the track is muted in this way. example this example demonstrates a click event handler for a pause button. pausebutton.onclick = function(evt) { const newstate = !myaudiotrack.enabled; pausebutton.innerhtml = newstate ? "&#x25b6;&#xfe0f;" : "&#x23f8;&#xfe0f;"; myaudiotrack.enabled =...
MediaStreamTrack: ended event - Web APIs
bubbles no cancelable no interface event event handler property mediastreamtrack.onended usage notes ended events fire when the media stream track's source permanently stops sending data on the stream. there are various ways this can happen, including: there is no more data left to send. the user revoked the permissions needed for the data to be sent. the hardware generating the source data has been removed or ejected. ...
MediaStreamTrackAudioSourceNode - Web APIs
crophone or other audio sampling device, or might be received through a rtcpeerconnection, among other posible options. a mediastreamtrackaudiosourcenode has no inputs and exactly one output, and is created using the audiocontext.createmediastreamtracksource() method. this interface is similar to mediastreamaudiosourcenode, except it lets you specifically state the track to use, rather than assuming the first audio track on a stream. number of inputs 0 number of outputs 1 channel count defined by the first audio mediastreamtrack passed to the audiocontext.createmediastreamtracksource() method that created it. constructor new mediastreamtrackaudiosourcenode() creates a new mediastreamtrackaudiosourcenode object instance with the specified optio...
MediaTrackConstraints.autoGainControl - Web APIs
however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. ...
MediaTrackConstraints.echoCancellation - Web APIs
however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. ...
MediaTrackConstraints.facingMode - Web APIs
however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. ...
MediaTrackConstraints.logicalSurface - Web APIs
constraints placed upon the value of the logicalsurface constrainable property. this is used to specify whether or not getdisplaymedia() should allow the user to choose display surfaces which are not necessarily fully visible on the screen, such as occluded windows or the complete content of windows which are large enough to require scrolling to see their entire contents. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.logicalsurface as returned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var constraintsobject = { logicalsurface: constraint }; constraintsobject.logicalsurface = con...
MediaTrackConstraints.noiseSuppression - Web APIs
however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. ...
MediaTrackSettings.aspectRatio - Web APIs
the mediatracksettings dictionary's aspectratio property is a double-precision floating-point number indicating the aspect ratio of the mediastreamtrack as currently configured. this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.aspectratio property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.aspectratio as returned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var aspectratio = mediatrac...
MediaTrackSettings.channelCount - Web APIs
the mediatracksettings dictionary's channelcount property is an integer indicating how many audio channel the mediastreamtrack is currently configured to have. this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.channelcount property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.channelcount as returned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var channelcount = mediatracksettings.chann...
MediaTrackSettings.facingMode - Web APIs
the mediatracksettings dictionary's facingmode property is a domstring indicating the direction in which the camera producing the video track represented by the mediastreamtrack is currently facing. this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.facingmode property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.facingmode as returned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. because rtp does...
MediaTrackSettings.frameRate - Web APIs
the mediatracksettings dictionary's framerate property is a double-precision floating-point number indicating the frame rate, in frames per second, of the mediastreamtrack as currently configured. this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.framerate property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.framerate as returned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var framerat...
MediaTrackSettings.height - Web APIs
the mediatracksettings dictionary's height property is an integer indicating the number of pixels tall mediastreamtrack is currently configured to be. this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.height property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.height as returned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var height = mediatracksettings.height; value an integer valu...
MediaTrackSettings.latency - Web APIs
the mediatracksettings dictionary's latency property is a double-precision floating-point number indicating the estimated latency (specified in seconds) of the mediastreamtrack as currently configured. this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.latency property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). this is, of course, an approximation, since latency can vary for many reasons including cpu, transmission, and storage overhead. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.latency as returned by a call to mediadevices.getsupportedconstraints(). howe...
MediaTrackSettings.sampleRate - Web APIs
the mediatracksettings dictionary's samplerate property is an integer indicating how many audio samples per second the mediastreamtrack is currently configured for. this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.samplerate property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.samplerate as returned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var samplerate = mediatracksettings.sample...
MediaTrackSettings.sampleSize - Web APIs
the mediatracksettings dictionary's samplesize property is an integer indicating the linear sample size (in bits per sample) the mediastreamtrack is currently configured for. this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.samplesize property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.samplesize as returned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var samplesize = mediatracksetti...
MediaTrackSettings.volume - Web APIs
the mediatracksettings dictionary's volume property is a double-precision floating-point number indicating the volume of the mediastreamtrack as currently configured, as a value from 0.0 (silence) to 1.0 (maximum supported volume for the device). this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.volume property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.volume as returned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints ...
MediaTrackSettings.width - Web APIs
the mediatracksettings dictionary's width property is an integer indicating the number of pixels wide mediastreamtrack is currently configured to be. this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.width property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.width as returned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. syntax var width = mediatracksettings.width; value an integer value ind...
MediaTrackSupportedConstraints.frameRate - Web APIs
pports the framerate constraint. if the constraint isn't supported, it's not included in the list, so this value will never be false. the framerate constraint can be used to establish acceptable upper and lower bounds on the video frame rate for a new video track, or to specify an exact frame rate that must be provided for the request to succeed. checking the value of this property lets you determine if the user agent allows constraining the video track configuration by frame rate. see the example to see how this can be used. syntax framerateconstraintsupported = supportedconstraintsdictionary.framerate; value this property is present in the dictionary if the user agent supports the framerate constraint. if the property isn't present, the user agent doesn't allow specifying limits on the...
MediaTrackSupportedConstraints - Web APIs
because of the way interface definitions in webidl work, if a constraint is requested but not supported, no error will occur. ...
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. concepts and usage the api is based on the manipulation of a mediastream object representing a flux of audio- or video-related data. see an example in get the video. ...
MerchantValidationEvent - Web APIs
quests for the payment handler, such as https://apple.com/apple-pay. merchantvalidationevent.validationurl secure context a usvstring specifying a url from which the site or app can fetch payment handler specific validation information. once this data is retrieved, the data (or a promise resolving to the validation data) should be passed into complete() to validate that the payment request is coming from an authorized merchant. methods merchantvalidationevent.complete() secure context pass the data retrieved from the url specified by validationurl into complete() to complete the validation process for the paymentrequest. specifications specification status comment payment request apithe definition of 'merchantvalidationevent' in that specification. candid...
MouseEvent.WEBKIT_FORCE_AT_FORCE_MOUSE_DOWN - Web APIs
-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. mouseevent.webkit_force_at_force_mouse_down is a proprietary, webkit-specific, static numeric property whose value is the minimum force necessary for a force click. because webkit_force_at_force_mouse_down is a static property of mouseevent, you always use it as mouseevent.webkit_force_at_force_mouse_down, rather than as a property of a mouseevent instance. specifications not part of any specification. apple has a description at the mac developer library. ...
MouseEvent.WEBKIT_FORCE_AT_MOUSE_DOWN - Web APIs
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. mouseevent.webkit_force_at_mouse_down is a proprietary, webkit-specific, static numeric property whose value is the minimum force necessary for a normal click. because webkit_force_at_mouse_down is a static property of mouseevent, you always use it as mouseevent.webkit_force_at_mouse_down, rather than as a property of a mouseevent instance. specifications not part of any specification. apple has a description at the mac developer library. ...
MouseEvent.mozInputSource - Web APIs
not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the mouseevent.mozinputsource read-only property on mouseevent provides information indicating the type of device that generated the event. this lets you, for example, determine whether a mouse event was generated by an actual mouse or by a touch event (which might affect the degree of accuracy with which you interpret the coordinates associated with the event). syntax var source = instanceofmouseevent.mozinputsource; return value the following values are possible. constant name value desription moz_source_unknown 0 the input device is...
msRealTime - Web APIs
altime is a read/write property which specifies whether or not to enable low-latency playback on the media element. this proprietary property is specific to internet explorer and microsoft edge. syntax ptr = object.msrealtime; value boolean value set to true indicates that low-latency playback will be enabled on the media element. low-latency playback is useful in communication and some gaming scenarios, but is more demanding on power consumption and less reliable for smooth media playback. you must set the msrealtime before setting the src property in code. msrealtime should not be used in non-real-time or non-communication scenarios, such as audio and/or video playback, as this can affects playback startup latency of audio and video playback. ...
MutationObserverInit - Web APIs
otherwise, a typeerror exception will be thrown. subtree optional set to true to extend monitoring to the entire subtree of nodes rooted at target. ...
Navigator.mozIsLocallyAvailable() - Web APIs
note: security exceptions can occur if the requested uri is not from the same origin. syntax navigator.mozislocallyavailable(uri, ifoffline); parameters uri the uri of the resource whose availability is to be checked, as a string. ifoffline allows you to specify whether or not the offline resources cache should be checked; specify true to consider the offline resources cache. ...
Web-based protocol handlers - Web APIs
authors can use a mailto: link when they want to provide a convenient way for users to send an email, directly from the webpage. when the link is activated, the browser should launch the default desktop application for handling email. you can think of this as a desktop-based protocol handler. web-based protocol handlers allow web-based applications to participate in the process too. this is becoming more important as more types of applications migrate to the web. in fact, there are many web-based email handling applications that could process a mailto link. registering setting up a web application as a protocol handler is not a difficult process. basically, the web application uses registerprotocolhandler() to register itself with the browser as a potential handler for a given protocol. f...
Navigator.wakeLock - Web APIs
the wakelock read-only property returns a wakelock interface which allows a document to acquire a screen wake lock. while a screen wake lock is active, the user agent will try to prevent the device from dimming the screen, turning it off completely, or showing a screensaver. syntax const wakelock = navigator.wakelock; specifications specification status comment screen wake lock api editor's draft initial definition ...
Navigator.xr - Web APIs
Web › API › Navigator › xr
to present augmented and/or virtual reality imagery to the user. usage notes each window has its own instance of navigator, which can be accessed as window.navigator or simply as navigator. at the same time, a new xr instance is also created and attached to the navigator instance as navigator.xr. if the xr property exists and is non-null, you can use it to access the webxr device api. to determine if webxr is available, you can do something like this: if ("xr" in window.navigator) { /* webxr can be used! */ } else { /* webxr isn't available */ } specifications specification status comment webxr device apithe definition of 'navigator.xr' in that specification. working draft initial definition. ...
Navigator - Web APIs
Web › API › Navigator
returns mediasession object which can be used to provide metadata that can be used by the browser to present information about the currently-playing media to the user, such as in a global media controls ui. navigator.moznotification deprecated since gecko 22 ... navigator.wakelock read only returns a wakelock interface you can use to request screen wake locks and prevent screen from dimming, turning off, or showing a screen saver. navigator.webkitnotification returns a notification object you can use to deliver notifications to the user from your web application. navigator.oscpu returns a string that represents the current operating system. navigator.productsub returns the build number of the current browser (e.g., "20060909"). navigator.securitypolicy returns an em...
NavigatorID.userAgent - Web APIs
ia this field as possible. never assume that the value of this property will stay the same in future versions of the same browser. try not to use it at all, or only for current and past versions of a browser. 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. also keep in mind that users of a browser can change the value of this field if they want (ua spoofing). browser identification based on detecting the user agent string is unreliable and is not recommended, as the user agent string is user configurable. for example: in firefox, you can change the preference general.useragent.override in about:config. some firefox extensions do that; however, this only change...
Online and offline events - Web APIs
odetection was implemented in firefox 2. "online" and "offline" events firefox 3 introduces two new events: "online" and "offline". these two events are fired on the <body> of each page when the browser switches between online and offline mode. additionally, the events bubble up from document.body, to document, ending at window. both events are non-cancellable (you can't prevent the user from coming online, or going offline). firefox 41 fires these events when the os reports a change in network connectivity on windows, linux, and os x. 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: u...
Navigator.onLine - Web APIs
n true. so while you can assume that the browser is offline when it returns a false value, you cannot assume that a true value necessarily means that the browser can access the internet. you could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always "connected." therefore, if you really want to determine the online status of the browser, you should develop additional means for checking. to learn more, see the html5 rocks article, working off the grid. in firefox and internet explorer, switching the browser to offline mode sends a false value. until firefox 41, all other conditions return a true value; testing actual behavior on nightly 68 on windows shows that it only looks for lan connection ...
NavigatorStorage.storage - Web APIs
the navigatorstorage.storage read-only property returns the singleton storagemanager object used to access the overall storage capabilities of the browser for the current site or app. the returned object lets you examine and configure persistence of data stores and learn approximately how much more space your browser has available for local storage use. syntax var storagemanager = navigator.storage; value a storagemanager object you can use to maintain persistence for stored data, as well as to determine roughly how much room there is for data to be stored. specifications specification status comment storagethe definition of 'navigator.storage' in that specification. living standard initial definition. ...
NetworkInformation.downlink - Web APIs
the networkinformation interface returns the effective bandwidth estimate in megabits per second, rounded to the nearest multiple of 25 kilobits per seconds. this value is based on recently observed application layer throughput across recently active connections, excluding connections made to a private address space. in the absence of recent bandwidth measurement data, the attribute value is determined by the properties of the underlying connection technology. note that chrome-based browsers do not conform to the specification, and arbitrarily cap the reported downlink at a maximum of 10 mbps as an anti-fingerprinting measure. similar caps exist for the reported latency. syntax var downlink = networkinformation.downlink value a double. specifications specification status ...
NetworkInformation.effectiveType - Web APIs
syntax var effectivetype = networkinformation.effectivetype value a string containing one of 'slow-2g', '2g', '3g', or '4g'. ...
NetworkInformation - Web APIs
imate in megabits per second, rounded to the nearest multiple of 25 kilobits per seconds. networkinformation.downlinkmax read only returns the maximum downlink speed, in megabits per second (mbps), for the underlying connection technology. networkinformation.effectivetype read only returns the effective type of the connection meaning one of 'slow-2g', '2g', '3g', or '4g'. this value is determined using a combination of recently observed round-trip time and downlink values. networkinformation.rtt read only returns the estimated effective round-trip time of the current connection, rounded to the nearest multiple of 25 milliseconds. networkinformation.savedata read only returns true if the user has set a reduced data usage option on the user agent. networkinformation.type read only ...
Node.contains() - Web APIs
Web › API › Node › contains
the node.contains() method returns a boolean value indicating whether a node is a descendant of a given node, i.e. the node itself, one of its direct children (childnodes), one of the children's direct children, and so on. syntax node.contains( othernode ) example this function checks to see if an element is in the page's body. as contains is inclusive and determining if the body contains itself isn't the intention of isinpage this case explicitly returns false. function isinpage(node) { return (node === document.body) ? false : document.body.contains(node); } specifications specification status comment domthe definition of 'node.contains()' in that specification. living standard initial definition ...
Node.hasChildNodes() - Web APIs
true if the node has child nodes, and false otherwise. example let foo = document.getelementbyid('foo'); if (foo.haschildnodes()) { // do something with 'foo.childnodes' } polyfill here is one possible polyfill: ;(function(prototype) { prototype.haschildnodes = prototype.haschildnodes || function() { return !!this.firstchild; } })(node.prototype); there are various ways to determine whether the node has a child node: node.haschildnodes() node.firstchild != null (or just node.firstchild) node.childnodes && node.childnodes.length (or node.childnodes.length > 0) specifications specification status comment domthe definition of 'node: haschildnodes' in that specification. living standard ...
Node.nodeName - Web APIs
Web › API › Node › nodeName
t_field's value would read "div". however, in html, text_field's value would read "div", because nodename and tagname return in upper case on html elements in doms flagged as html documents. read more details on nodename case sensitivity in different browsers. note that the element.tagname property could have been used instead, since nodename has the same value as tagname for an element. bear in mind, however, that nodename will return "#text" for text nodes while tagname will return undefined. specifications specification status comment domthe definition of 'nodename' in that specification. living standard ...
Node.removeChild() - Web APIs
Web › API › Node › removeChild
node is the parent node of child. oldchild holds a reference to the removed child node, i.e., oldchild === child. the removed child node still exists in memory, but is no longer part of the dom. with the first syntax form shown, you may reuse the removed node later in your code, via the oldchild object reference. in the second syntax form, however, there is no oldchild reference kept, so assuming your code has not kept any other reference to the node elsewhere, it will immediately become unusable and irretrievable, and will usually be automatically deleted from memory after a short time. if child is actually not a child of the element node, the method throws an exception. this will also happen if child was in fact a child of element at the time of the call, but was removed by an event h...
NodeFilter.acceptNode() - Web APIs
eing the object to check against the filter. ...
NodeFilter - Web APIs
ode but not its children". ...
NodeIterator.filter - Web APIs
the nodeiterator.filter read-only method returns a nodefilter object, that is an object implement an acceptnode(node) method, used to screen nodes. when creating the nodeiterator, the filter object is passed in as the third parameter, and the object method acceptnode(node) is called on every single node to determine whether or not to accept it. this function should return the constant nodefilter.filter_accept for cases when the node should be accepted and nodefilter.filter_reject for cases when the node should be rejected. syntax nodefilter = nodeiterator.filter; example const nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); nodefilter = nodeiterator.filter; ...
NodeList.length - Web APIs
Web › API › NodeList › length
it's often used to test the length of a list, to see if it exists at all. it's also commonly used as the iterator in a for loop, as in this example. ...
NodeList - Web APIs
Web › API › NodeList
ole.log(child_nodes.length); // let's assume "2" parent.appendchild(document.createelement('div')); console.log(child_nodes.length); // outputs "3" static nodelists in other cases, the nodelist is static, where any changes in the dom does not affect the content of the collection. the ubiquitous document.queryselectorall() method returns a static nodelist. it's good to keep this distinction in mind when you choose how to iterate over the items in the nodelist, and whether you should cache the list's length. properties nodelist.length the number of nodes in the nodelist. methods nodelist.item() returns an item in the list by its index, or null if the index is out-of-bounds. an alternative to accessing nodelist[i] (which instead returns undefined when i is out-of-bounds). this i...
Notification.requestPermission() - Web APIs
page, as chrome and firefox no longer allow notification permissions to be requested from cross-origin <iframe>s, with other browsers to follow. to see a example in action, check out our to-do list example (also see the app running live.) note: in the above example we spawn notifications in response to a user gesture (clicking a button). this is not only best practice — you should not be spamming users with notifications they didn't agree to — but going forward browsers will explicitly disallow notifications not triggered in response to a user gesture. firefox is already doing this from version 72, for example. specifications specification status comment notifications api living standard living standard ...
Notification.timestamp - Web APIs
notification interface returns a domtimestamp, as specified in the timestamp option of the notification() constructor. the notification's timestamp can represent the time, in milliseconds since 00:00:00 utc on 1 january 1970, of the event for which the notification was created, or it can be an arbitrary timestamp that you want associated with the notification. for example, a timestamp for an upcoming meeting could be set in the future, whereas a timestamp for a missed message could be set in the past. syntax var timestamp = notification.timestamp; value a domtimestamp. examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor. var dts = math.floor(date.now()); var options = { body: 'd...
Notification - Web APIs
page, as chrome and firefox no longer allow notification permissions to be requested from cross-origin <iframe>s, with other browsers to follow. to see a example in action, check out our to-do list example (also see the app running live.) note: in the above example we spawn notifications in response to a user gesture (clicking a button). this is not only best practice — you should not be spamming users with notifications they didn't agree to — but going forward browsers will explicitly disallow notifications not triggered in response to a user gesture. firefox is already doing this from version 72, for example. specifications specification status comment notifications api living standard living standard ...
Notifications API - Web APIs
stem notifications, which is generally done when the app or site initialises, using the notification.requestpermission() method. this should be done in response to a user gesture, such as clicking a button, for example: btn.addeventlistener('click', function() { let promise = notification.requestpermission(); // wait for permission }) this is not only best practice — you should not be spamming users with notifications they didn't agree to — but going forward browsers will explicitly disallow notifications not triggered in response to a user gesture. firefox is already doing this from version 72, for example. this will spawn a request dialog, along the following lines: from here the user can choose to allow notifications from this origin, or block them. once a choice has been mad...
OES_texture_float - Web APIs
ext by default. extended methods this extension extends webglrenderingcontext.teximage2d() and webglrenderingcontext.texsubimage2d(): the type parameter now accepts gl.float. the pixels parameter now accepts an arraybufferview of type float32array. limitation: linear filtering linear filtering on floating-point textures is not allowed with this extension. if you set the magnification or minification filter in the webglrenderingcontext.texparameter() method to one of gl.linear, gl.linear_mipmap_nearest, gl.nearest_mipmap_linear, or gl.linear_mipmap_linear, and use floating-point textures, the texture will be marked as incomplete. to use linear filtering on floating-point textures, enable the oes_texture_float_linear extension in addition to this extension. floating-point color buff...
OES_texture_float_linear - Web APIs
extension() method. for more information, see also using extensions in the webgl tutorial. availability: this extension is available to both, webgl1 and webgl2 contexts. linear filtering the oes_texture_float extension alone does not allow linear filtering with floating-point textures. this extension enables this ability. with the help of this extension, you can now set the magnification or minification filter in the webglrenderingcontext.texparameter() method to one of gl.linear, gl.linear_mipmap_nearest, gl.nearest_mipmap_linear, or gl.linear_mipmap_linear, and use floating-point textures. examples gl.getextension('oes_texture_float'); gl.getextension('oes_texture_float_linear'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.texparameterf(gl.texture_...
OES_texture_half_float - Web APIs
loat. constants ext.half_float_oes half floating-point type (16-bit). extended methods this extension extends webglrenderingcontext.teximage2d() and webglrenderingcontext.texsubimage2d(): the type parameter now accepts ext.half_float_oes. limitation: linear filtering linear filtering on half floating-point textures is not allowed with this extension. if you set the magnification or minification filter in the webglrenderingcontext.texparameter() method to one of gl.linear, gl.linear_mipmap_nearest, gl.nearest_mipmap_linear, or gl.linear_mipmap_linear, and use half floating-point textures, the texture will be marked as incomplete. to use linear filtering on half floating-point textures, enable the oes_texture_half_float_linear extension in addition to this extension. half float...
OES_texture_half_float_linear - Web APIs
) method. for more information, see also using extensions in the webgl tutorial. availability: this extension is available to both, webgl1 and webgl2 contexts. linear filtering the oes_texture_half_float extension alone does not allow linear filtering with half floating-point textures. this extension enables this ability. with the help of this extension, you can now set the magnification or minification filter in the webglrenderingcontext.texparameter() method to one of gl.linear, gl.linear_mipmap_nearest, gl.nearest_mipmap_linear, or gl.linear_mipmap_linear, and use half floating-point textures. examples var halffloat = gl.getextension('oes_texture_half_float'); gl.getextension('oes_texture_half_float_linear'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture)...
OfflineAudioCompletionEvent - Web APIs
the complete event implements this interface. note: this interface is marked as deprecated; it is still supported for legacy reasons, but it will soon be superseded when the promise version of offlineaudiocontext.startrendering is supported in browsers, which will no longer need it. constructor offlineaudiocompletionevent.offlineaudiocompletionevent creates a new offlineaudiocompletionevent object instance. properties also inherits properties from its parent, event. ...
OfflineAudioContext.oncomplete - Web APIs
syntax var offlineaudioctx = new offlineaudiocontext(); offlineaudioctx.oncomplete = function() { ... } example when processing is complete, you might want to use the oncomplete handler the prompt the user that the audio can now be played, and enable the play button. ...
OscillatorNode.detune - Web APIs
ar oscillator = audioctx.createoscillator(); oscillator.detune.setvalueattime(100, audioctx.currenttime); // value in cents note: though the audioparam returned is read-only, the value it represents is not. value an a-rate audioparam. example the following example shows basic usage of an audiocontext to create an oscillator node. for applied examples/information, check out our violent theremin demo (see app.js for relevant code). // create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.setvalueattime(440, audioctx.currenttime); // value in hertz oscillator.detune.setvalueattime(100, audioctx.currenttime); // value in...
OscillatorNode.frequency - Web APIs
ntax var oscillator = audioctx.createoscillator(); oscillator.frequency.setvalueattime(440, audioctx.currenttime); // value in hertz note: though the audioparam returned is read-only, the value it represents is not. value an a-rate audioparam. example the following example shows basic usage of an audiocontext to create an oscillator node. for an applied example, check out our violent theremin demo (see app.js for relevant code). // create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.setvalueattime(440, audioctx.currenttime); // value in hertz oscillator.start(); specifications specification status ...
OscillatorNode.onended - Web APIs
the onended property of the oscillatornode interface is used to set the event handler for the ended event, which fires when the tone has stopped playing. syntax var oscillator = audioctx.createoscillator(); oscillator.onended = function() { ... }; example the following example shows basic usage of an audiocontext to create an oscillator node. for an applied example, check out our violent theremin demo (see app.js for relevant code). // create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.value = 440; // value in hertz oscillator.start(); // start the tone playing oscillator.stop(5); // the tone will stop again in 5 se...
OscillatorNode.start() - Web APIs
al double representing the time (in seconds) when the oscillator should start, in the same coordinate system as audiocontext's currenttime attribute. if a value is not included or is less than currenttime, the oscillator starts playing immediately. example the following example shows basic usage of an audiocontext to create an oscillator node. for an applied example, check out our violent theremin demo (see app.js for relevant code). // create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.setvalueattime(3000, audioctx.currenttime); // value in hertz oscillator.start(); specifications specification status ...
OscillatorNode.stop() - Web APIs
l an optional double representing the audio context time when the oscillator should stop. if a value is not included, it defaults to 0. if the time is equal to or before the current audio context time, the oscillator will stop playing immediately. example the following example shows basic usage of an audiocontext to create an oscillator node. for an applied example, check out our violent theremin demo (see app.js for relevant code). // create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.connect(audioctx.destination); oscillator.start(); oscillator.stop(audioctx.currenttime + 2); // stop 2 seconds after the current time specifications specific...
OscillatorNode.type - Web APIs
data representing the waveform. doing so automatically sets the type to custom. exceptions invalidstateerror the value custom was specified. to set a custom waveform, just call setperiodicwave(). doing so automatically sets the type for you. example the following example shows basic usage of an audiocontext to create an oscillator node. for an applied example, check out our violent theremin demo (see app.js for relevant code). // create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.setvalueattime(440, audioctx.currenttime); // value in hertz oscillator.start(); specifications specification status ...
OscillatorNode - Web APIs
his replaces the now-obsolete oscillatornode.setwavetable() method. oscillatornode.start() specifies the exact time to start playing the tone. oscillatornode.stop() specifies the time to stop playing the tone. examples the following example shows basic usage of an audiocontext to create an oscillator node and to start playing a tone on it. for an applied example, check out our violent theremin demo (see app.js for relevant code). // create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.setvalueattime(440, audioctx.currenttime); // value in hertz oscillator.connect(audioctx.destination); oscillator.start(); specifica...
PannerNode.distanceModel - Web APIs
the distancemodel property of the pannernode interface is an enumerated value determining which algorithm to use to reduce the volume of the audio source as it moves away from the listener. the possible values are: linear: a linear distance model calculating the gain induced by the distance according to: 1 - rollofffactor * (distance - refdistance) / (maxdistance - refdistance) inverse: an inverse distance model calculating the gain induced by the distance according to: refdistance / (refdistance + rollofffactor * (math.max(distance, refdistance) - refdistance)) exponential: an exponential distance model calculating the gain induced by the distance according to: pow((math.max(distance, refdistance) / refdistance, -rollofffactor). inverse is the default value of distancemodel.
PannerNode.panningModel - Web APIs
the possible values are: equalpower: represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value. hrtf: renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects. syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; value a enum — see panningmodeltype. ...
Path2D - Web APIs
Web › API › Path2D
and radius, connected to the previous point by a straight line. path2d.ellipse() adds an elliptical arc to the path which is centered at (x, y) position with the radii radiusx and radiusy starting at startangle and ending at endangle going in the given direction by anticlockwise (defaulting to clockwise). path2d.rect() creates a path for a rectangle at position (x, y) with a size that is determined by width and height. specifications specification status comment html living standardthe definition of 'path2d' in that specification. living standard ...
PaymentAddress.country - Web APIs
ry values: "us", "gb", "cn", or "jp". syntax var paymentcountry = paymentaddress.country; value a domstring which contains the iso3166-1 alpha-2 code identifying the country in which the address is located, or an empty string if no country is available, which frequently can be assumed to mean "same country as the site owner." usage notes if the payment handler validates the address and determines that the value of country is invalid, a call to paymentrequestupdateevent.updatewith() will be made with a details object containing a shippingaddresserrors field. that field contains an addresserrors-compliant object whose country property is a string indicating the validation error that occurred and, if possible, suggests how to fix it. specifications specification status com...
PaymentAddress.languageCode - Web APIs
the languagecode read-only property of the paymentaddress interface returns a string containing the bcp-47 language code for the address. this is used while localizing the displayy of the address, allowing the determination of the field separators and the order of fields when formatting the address. syntax var paymentlanguagecode = paymentaddress.languagecode; value a domstring providing the bcp-47 format language code indicating the language the address was written in, such as "en-us", "pt-br", or "ja-jp". ...
PaymentAddress - Web APIs
rson. paymentaddress.postalcode read only a domstring specifying a code used by a jurisdiction for mail routing, for example, the zip code in the united states or the pin code in india. paymentaddress.recipient read only a domstring giving the name of the recipient, purchaser, or contact person at the payment address. paymentaddress.region read only a domstring containing the top level administrative subdivision of the country, for example a state, province, oblast, or prefecture. paymentaddress.regioncode read only a domstring specifying the region of the address, represented as a "code element" of an iso3166-2 country subdivision name (e.g. "qld" for queensland, australia, "ca" for california, and so on). paymentaddress.sortingcode read only a domstring providing a postal sor...
PaymentRequest.PaymentRequest() - Web APIs
sn't appropriate for your use case. for example, in english speaking countries you would say "pizza delivery" not "pizza shipping". valid values are "shipping", "delivery", and "pickup". quotation marks must be included. the default value is "shipping". return value a new paymentrequest object, configured for use as configured by the input parameters. examples the following example shows minimal functionality and focuses instead on showing the complete context of instantiating a paymentrequest object. var supportedinstruments = [{ supportedmethods: 'basic-card', data: { supportednetworks: ['visa', 'mastercard', 'amex', 'jcb', 'diners', 'discover', 'mir', 'unionpay'] } }]; var details = { total: {label: 'donation', amount: {currency: 'usd', value: '65.
PaymentRequest.abort() - Web APIs
.abort(); returns void. parameters none examples the following example sets up a timeout to clear the payment request that might have been abandoned or neglected. var request = new paymentrequest(supportedinstruments, details, options); var paymenttimeout = window.settimeout(() => { window.cleartimeout(paymenttimeout); request.abort().then(() => { print('payment timed out after 20 minutes.'); }).catch(() => { print('unable to abort, because the user is currently in the process ' + 'of paying.'); }); }, 20 * 60 * 1000); /* 20 minutes */ specifications specification status comment payment request apithe definition of 'abort()' in that specification. candidate recommendation initial definition. browser compatibility the...
PaymentRequestUpdateEvent - Web APIs
paymentrequestupdateevent() secure context creates a new paymentrequestupdateevent object. properties provides only the properties inherited from its parent interface, event. methods in addition to methods inherited from the parent interface, event, paymentrequestupdateevent offers the following methods: paymentrequestupdateevent.updatewith() secure context if the event handler determines that information included in the payment request needs to be changed, or that new information needs to be added, it calls updatewith() with the information that needs to be replaced or added. specifications specification status comment payment request apithe definition of 'paymentrequestupdateevent' in that specification. candidate recommendation initial definit...
PaymentResponse.details - Web APIs
this data is returned by the payment app that satisfies the payment request, and must conform to the structure defined in the basiccardresponse dictionary. syntax var detailsobject = paymentresponse.details; example the following example extracts the details from the paymentresponse object to the promise returned from paymentrequest.show(). ...
PaymentResponse - Web APIs
the paymentresponse interface of the payment request api is returned after a user selects a payment method and approves a payment request. properties paymentresponse.details read only secure context returns a json-serializable object that provides a payment method specific message used by the merchant to process the transaction and determine successful fund transfer. the contents of the object depend on the payment method being used; for example, if the basic card payment method is used, this object must conform to the structure defined in the basiccardresponse dictionary. paymentresponse.methodname read only secure context returns the payment method identifier for the payment method that the user selected, for example, visa, mastercard, paypal, etc.. paymentresponse.payeremail ...
Using the Payment Request API - Web APIs
} note: see our customizing the payment button demo for the full code. checking before all prices are known if the checkout flow needs to know whether paymentrequest.canmakepayment() will return true even before all line items and their prices are known, you can instantiate paymentrequest with dummy data and pre-query .canmakepayment(). if you call .canmakepayment() multiple times, keep in mind that the first parameter to the paymentrequest constructor should contain the same method names and data. // the page has loaded. should the page use paymentrequest? // if paymentrequest fails, should the page fallback to manual // web form checkout? const supportedpaymentmethods = ... let shouldcallpaymentrequest = true; let fallbacktolegacyonpaymentrequestfailure = false; (new paymentrequest(...
Pbkdf2Params - Web APIs
everywhere, so unless you need to use sha-1, don't. use a different digest algorithm instead. salt a buffersource. this should be a random or pseudo-random value of at least 16 bytes. unlike the input key material passed into derivekey(), salt does not need to be kept secret. iterations a number representing the number of times the hash function will be executed in derivekey(). this determines how computationally expensive (that is, slow) the derivekey() operation will be. in this context, slow is good, since it makes it more expensive for an attacker to run a dictionary attack against the keys. the general guidance here is to use as many iterations as possible, subject to keeping an acceptable level of performance for your application. examples see the examples for subtlecrypto.d...
performance.clearMarks() - Web APIs
e.mark("dog"); logmarkcount() // "found this many entries: 6" // delete just the "squirrel" performancemark entries. performance.clearmarks('squirrel'); logmarkcount() // "found this many entries: 4" // delete all of the performancemark entries. performance.clearmarks(); logmarkcount() // "found this many entries: 0" specifications specification status comment user timing level 2the definition of 'clearmarks()' in that specification. working draft clarifies clearmarks(). user timingthe definition of 'clearmarks()' in that specification. recommendation basic definition. ...
performance.clearMeasures() - Web APIs
/ "found this many entries: 5" // delete just the "from navigation" performancemeasure entries. performance.clearmeasures("from navigation"); logmeasurecount() // "found this many entries: 3" // delete all of the performancemeasure entries. performance.clearmeasures(); logmeasurecount() // "found this many entries: 0" specifications specification status comment user timing level 2the definition of 'clearmeasures()' in that specification. working draft clarifies clearmeasures(). user timingthe definition of 'clearmeasures()' in that specification. recommendation basic definition. ...
performance.getEntriesByName() - Web APIs
.performance.getentriesbyname(name, type); arguments name the name of the entry to retrieve. type optional the type of entry to retrieve such as "mark". the valid entry types are listed in performanceentry.entrytype. return value entries a list of performanceentry objects that have the specified name and type. if the type argument is not specified, only the name will be used to determine the entries to return. the items will be in chronological order based on the entries' starttime. if no objects meet the specified criteria, an empty list is returned. example function use_performanceentry_methods() { log("performanceentry tests ..."); if (performance.mark === undefined) { log("... performance.mark not supported"); return; } // create some performance entries...
Performance.memory - Web APIs
totaljsheapsize the total allocated heap size, in bytes. usedjsheapsize the currently active segment of js heap, in bytes. ...
Performance.navigation - Web APIs
this property is deprecated in the navigation timing level 2 specification. the legacy performance.navigation read-only property returns a performancenavigation object representing the type of navigation that occurs in the given browsing context, such as the number of redirections needed to fetch the resource. this property is not available in workers. syntax navobject = performance.navigation; specifications specification status comment navigation timingthe definition of 'performance.navigation' in that specification. recommendation initial definition. ...
PerformanceEntry.startTime - Web APIs
timestamp with a value of "0". "resource" - returns the timestamp immediately before the browser starts fetching the resource. this property is read only . syntax entry.starttime; return value a domhighrestimestamp representing the first timestamp when the performance entry was created. note: if the performance entry has an entrytype of "resource" (i.e. the entry is a performanceresourcetiming object), this property returns the performanceentry.fetchstart timestamp. example the following example shows the use of the starttime property. function run_performanceentry() { log("performanceentry support ..."); if (performance.mark === undefined) { log("... performance.mark not supported"); return; } // create some performance entries via the mark() method performance...
PerformanceNavigation.redirectCount - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancenavigation.redirectcount read-only property returns an unsigned short representing the number of redirects done before reaching the page. syntax amount = performancenavigation.redirectcount; specifications specification status comment navigation timingthe definition of 'performancenavigation.redirectcount' in that specification. recommendation initial definition. ...
PerformanceObserver.observe() - Web APIs
when a matching performance entry is recorded, the performance observer's callback function—set when creating the performanceobserver—is invoked. ...
PerformanceObserverEntryList.getEntriesByType() - Web APIs
the list is available in the observer's callback function (as the first parameter in the callback). this method is exposed to window and worker interfaces. syntax entries = list.getentriesbytype(type); parameters type the type of entry to retrieve such as "frame". ...
Using Performance Timeline - Web APIs
ment are defined in the performance timeline standard which has two levels: performance timeline level 2; editors draft; work in progress. this version introduces performance observers (and the performanceobserver and performanceobserverentrylist interfaces). performance timeline; w3c recommendation 12 december 2013 see also performance timeline (overview) a primer for web performance timing apis ...
Performance Timeline - Web APIs
, most of these interfaces are broadly implemented by desktop browsers and have less support on mobile devices. performance observers : as shown in the performanceobserver interface's browser compatibility table, this interface has no shipping implementations. to test your browser's support for these interfaces, run the perf-api-support application. see also a primer for web performance timing apis ...
Permissions.query() - Web APIs
Web › API › Permissions › query
escriptor).then(function(permissionstatus) { ... }) parameters permissiondescriptor an object that sets options for the query operation consisting of a comma-separated list of name-value pairs. the available options are: name: the name of the api whose permissions you want to query. an up-to-date list of permission names can be found in the spec under the permissionname enum, but bear in mind that the actual permissions supported by browsers is currently much smaller than this. firefox for example currently supports geolocation, notifications, push, and persistent-storage (see our permissions.webidl file). uservisibleonly: (push only, not supported in firefox — see the browser support section below) indicates whether you want to show a notification for every message or be able to...
Permissions API - Web APIs
concepts and usage historically different apis handle their own permissions inconsistently — for example the notifications api allows for explicit checking of permission status and requesting permission, whereas the geolocation api doesn't (which causes problems if the user denied the initial permission request). ...
PhotoCapabilities - Web APIs
e="range"]'); var imagecapture; navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); return imagecapture.getphotocapabilities(); }) .then(photocapabilities => { const settings = imagecapture.track.getsettings(); input.min = photocapabilities.imagewidth.min; input.max = photocapabilities.imagewidth.max; input.step = photocapabilities.imagewidth.step; return imagecapture.getphotosettings(); }) .then(photosettings => { input.value = photosettings.imagewidth; }) .catch(error => console.log('argh!', error.name || error)); specifications specification status comment mediastream image c...
PointerEvent.pressure - Web APIs
the pressure read-only property of the pointerevent interface indicates the normalized pressure of the pointer input. syntax var pressure = pointerevent.pressure; return value pressure the normalized pressure of the pointer input in the range of 0 to 1, inclusive, where 0 and 1 represent the minimum and maximum pressure the hardware is capable of detecting, respectively. for hardware that does not support pressure, such as a mouse, the value is 0.5 when the pointer is active buttons state and 0 otherwise. example in this snippet, when a pointerdown event is fired, different functions are called depending on the value of the event's pressure property. someelement.addeventlistener('pointerdown', function(event) { if (event.pressure == 0) { // no pressure process_no_pressu...
Pinch zoom gestures - Web APIs
invoking a two-pointer pinch/zoom gesture. if two pointers are down, and the distance between the pointers is increasing (signifying a pinch out or zoom in), the element's background color is changed to pink, and if the distance between the pointers is decreasing (a pinch in or zoom out), the background color is changed to lightblue. in a more sophisticated application, pinch in or pinch out determination could be used to apply application-specific semantics. when this event is processed, the target's border is set to dashed to provide a clear visual indication the element has received a move event. function pointermove_handler(ev) { // this function implements a 2-pointer horizontal pinch/zoom gesture. // // if the distance between the two pointers has increased (zoom in), // the targe...
Using Pointer Events - Web APIs
this is done by looking at each touch's pointerevent.pointerid property. this property is a unique integer for each pointer event, and remains consistent for each event during the duration of each finger's contact with the surface. this lets us get the coordinates of the previous position of each touch and use the appropriate con...
ProgressEvent() - Web APIs
performed by the underlying process. the ratio of work done can be calculated with the property and progressevent.total. when downloading a resource using http, this only represent the part of the content itself, not headers and other overhead. it defaults to 0. total optional is an unsigned long long representing the total amount of work that the underlying process is in the progress of performing. when downloading a resource using http, this only represent the content itself, not headers and other overhead. it defaults to 0. specifications specification status comment xmlhttprequestthe definition of 'progressevent()' in that specification. living standard ...
ProgressEvent.initProgressEvent() - Web APIs
the amount of work already performed by the underlying process. the ratio of work done can be calculated with the property and progressevent.total. when downloading a resource using http, this only represent the part of the content itself, not headers and other overhead. total is an unsigned long long representing the total amount of work that the underlying process is in the progress of performing. when downloading a resource using http, this only represent the content itself, not headers and other overhead. specifications this feature does not exist in any specifications. ...
ProgressEvent.total - Web APIs
when downloading a resource using http, this only represent the content itself, not headers and other overhead. ...
PromiseRejectionEvent.promise - Web APIs
syntax promise = promiserejectionevent.promise value the javascript promise which was rejected, and whose rejection went unhandled. examples this example listens for unhandled promises and, if the reason is an object with a code field containing the text "module not ready", it sets up an idle callback that will retry the task that failed to execute correctly. ...
Proximity Events - Web APIs
t handler to the window.ondeviceproximity or window.onuserproximity properties. once captured, the event object gives access to different kinds of information: the deviceproximityevent event provides an exact match for the distance between the device and the object through its value property. it also provides the closest and farthest distance the device is able to detect something through its min and max properties. the userproximityevent event provides a rough approximation of the distance, expressed through a boolean. the userproximityevent.near property is true if the object is close or false if the object is far. example window.addeventlistener('userproximity', function(event) { if (event.near) { // let's power off the screen navigator.mozpower.screenenabled = false; }...
PublicKeyCredentialCreationOptions.authenticatorSelection - Web APIs
the default value is "preferred". the authenticator used for the creation of the public key credential must comply with the requirements. note: see publickeycredential.isuserverifyingplatformauthenticatoravailable() which resolves to true when a user-verifiying platform authenticator is available. examples var publickey = { authenticatorse...
PublicKeyCredentialCreationOptions.timeout - Web APIs
wser. note: an analogous option exists for the fetching operation (navigators.credentials.get()), see publickeycredentialrequestoptions.timeout. syntax timeout = publickeycredentialcreationoptions.timeout value a numerical hint, expressed in milliseconds, giving the time to wait for the creation operation to complete. examples var publickey = { timeout: 6000, // accepting to wait for a minute before giving up. challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.cre...
PublicKeyCredentialCreationOptions - Web APIs
e server challenge: new uint8array(26), // user user: { id: new uint8array(16), name: "john.p.smith@example.com", displayname: "john p. ...
PublicKeyCredentialRequestOptions.timeout - Web APIs
creation operation (navigators.credentials.create()), see publickeycredentialcreationoptions.timeout. syntax timeout = publickeycredentialrequestoptions.timeout value a numerical hint, expressed in milliseconds, giving the time to wait for the creation operation to complete. ...
PublicKeyCredentialRequestOptions.userVerification - Web APIs
the default value is "preferred". examples var options = { userverification: "preferred", challenge: new uint8array([/* bytes sent from the server */]), }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of t...
PublicKeyCredentialRequestOptions - Web APIs
ealing with legacy fido apis credentials, prompting a specific text on the authenticator, etc.). methods none. ...
PushManager.subscribe() - Web APIs
firefox is already doing this from version 72, for example. specifications specification status comment push apithe definition of 'subscribe()' in that specification. working draft initial definition. ...
Push API - Web APIs
Web › API › Push API
ve push messages, it has to have an active service worker. when the service worker is active, it can subscribe to push notifications, using pushmanager.subscribe(). the resulting pushsubscription includes all the information that the application needs to send a push message: an endpoint and the encryption key needed for sending data. the service worker will be started as necessary to handle incoming push messages, which are delivered to the serviceworkerglobalscope.onpush event handler. 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. the endpoint for the subscription is a unique capability url: knowledge of the endpoint is all that is ...
RTCConfiguration.certificates - Web APIs
connection's setconfiguration(), it is ignored. this attribute supports providing multiple certificates because even though a given dtls connection uses only one certificate, providing multiple certificates allows support for multiple encryption algorithms. the implementation of rtcpeerconnection will choose which certificate to use based on the algorithms it and the remote peer support, as determined during dtls handshake. if you don't provide certificates, new ones are generated automatically. one obvious benefit to providing your own is identity key continuity—if you use the same certificate for subsequent calls, the remote peer can tell you're the same caller. this also avoids the cost of generating new keys. <<<--- add link to information about identity --->>> examples specificati...
RTCConfiguration.iceTransportPolicy - Web APIs
nfiguration.icetransportpolicy; value a domstring which indicates what ice candidate policy the ice agent should use during the negotiation process, per the jsep standard. the permitted values are: all the ice agent is permitted to use any kind of candidate, including both local and relay candidates. the agent—or the browser itself—may still perform some form of ip filtering on the incoming candidates for reasons including privacy and security, as well as to simply limit the number of candidates. this is the default. relay the ice agent only considers media relay candidates when evaluating candidates. this includes, for example, those candidates relayed by a stun or turn server. this can be used to prevent the remote endpoint from receiving the user's ip addresses, which may ...
RTCConfiguration - Web APIs
lls to rtcpeerconnection.generatecertificate(). this attribute supports providing multiple certificates because even though a given dtls connection uses only one certificate, providing multiple certificates allows support for multiple encryption algorithms. the implementation of rtcpeerconnection will choose which certificate to use based on the algorithms it and the remote peer support, as determined during dtls handshake. if you don't provide certificates, new ones are generated automatically. one obvious benefit to providing your own is identity key continuity—if you use the same certificate for subsequent calls, the remote peer can tell you're the same caller. this also avoids the cost of generating new keys. <<<--- add link to information about identity --->>> example the configur...
RTCDTMFSender.insertDTMF() - Web APIs
r clears the tone buffer, aborting any currently queued tones. a "," character inserts a two second delay. duration optional the amount of time, in milliseconds, that each dtmf tone should last. this value must be between 40 ms and 6000 ms (6 seconds), inclusive. the default is 100 ms. intertonegap optional the length of time, in milliseconds, to wait between tones. the browser will enforce a minimum value of 30 ms (that is, if you specify a lower value, 30 ms will be used instead); the default is 70 ms. return value undefined exceptions invalidstateerror the dtmf tones couldn't be sent because the track has been stopped, or is in a read-only or inactive state. invalidcharactererror one or more of the characters in tones is not valid dtmf. example tbd specifications ...
RTCDTMFSender.toneBuffer - Web APIs
syntax var tonebuffer = rtcdtmfsender.tonebuffer; value a domstring listing the tones to be played. if the string is empty, there are no tones pending. ...
RTCDTMFSender: tonechange event - Web APIs
the tonechange event is sent to an rtcdtmfsender by the webrtc api to indicate when dtmf tones previously queued for sending (by calling rtcdtmfsender.insertdtmf()) begin and end. bubbles no cancelable no interface rtcdtmftonechangeevent event handler property ontonechange to determine what tone started playing, or if a tone stopped playing, check the value of the event's tone property. examples this example establishes a handler for the tonechange event which updates an element to display the currently playing tone in its content, or, if all tones have played, the string "<none>". this can be done using addeventlistener(): dtmfsender.addeventlistener("tonechange", ev => { let tone = ev.tone; if (tone === "") { tone = "&lt;n...
RTCDataChannel.bufferedAmount - Web APIs
the read-only rtcdatachannel property bufferedamount returns the number of bytes of data currently queued to be sent over the data channel. the queue may build up as a result of calls to the send() method. this only includes data buffered by the user agent itself; it doesn't include any framing overhead or buffering done by the operating system or network hardware. the user agent may implement the process of actually sending data in any way it chooses; this may be done periodically during the event loop or truly asynchronously. as messages are actually sent, this value is reduced accordingly. closing the data channel doesn't reset this count, even though the user agent purges the queued messages. however, even after closing the channel, attempts to send messages continue to add to the b...
RTCDataChannel: bufferedamountlow event - Web APIs
urce = /* source data object */ dc.bufferedamountlowthreshold = 65536; pc.addeventlistener("bufferedamountlow", ev => { if (source.position <= source.length) { dc.send(source.readfile(65536)); } }, false); after creating the rtcpeerconnection, this calls rtcpeerconnection.createdatachannel() to create the data channel. then a listener is created for bufferedamountlow to refill the incoming data buffer any time its contents fall below 65536 bytes. 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 betwe...
RTCDataChannel: message event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessage note: the message event uses as its event object type the messageevent interface defined by the html specification. 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. dc.addeventlistener("message", ev => { let newparagraph = document.createelement("p"); let textnode = document.createtextnode(event.data); newparagraph.appendchild(textnode); document.body.appendchild(newparagraph); }, false); lines 2-4 create the new pa...
RTCDataChannel.negotiated - Web APIs
rtcdatachannel's connection was negotiated by the web app itself; false if the negotiation was handled by the webrtc layer. the default is false. example the code snippet below checks the value of negotiated; if it's true, a function called shutdownremotechannel() is called with the channel's id; presumably this would be implemented to transmit a shutdown signal to the remote peer prior to terminating the connection. if (datachannel.negotiated) { shutdownremotechannel(datachannel.id); } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.negotiated' in that specification. candidate recommendation initial specification. ...
RTCDataChannelEvent.channel - Web APIs
l object representing the data channel linking the receiving rtcpeerconnection to its remote peer. example the first line of code in the datachannel event handler shown below takes the channel from the event object and saves it locally for use by the code handling data traffic. pc.ondatachannel = function(event) { inbounddatachannel = event.channel; inbounddatachannel.onmessage = handleincomingmessage; inbounddatachannel.onopen = handlechannelopen; inbounddatachannel.onclose = handlechannelclose; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannelevent.channel' in that specification. candidate recommendation initial specification. ...
RTCDataChannelEvent - Web APIs
ethods from: event examples in this example, the datachannel event handler is set up to save the data channel reference and set up handlers for the events which need to be monitored. the channel property provides the rtcdatachannel representing the connection to the other peer. pc.ondatachannel = function(event) { inbounddatachannel = event.channel; inbounddatachannel.onmessage = handleincomingmessage; inbounddatachannel.onopen = handlechannelopen; inbounddatachannel.onclose = handlechannelclose; } see a simple rtcdatachannel sample for another, more complete, example of how to use data channels. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannelevent' in that specification. ...
RTCIceCandidate.address - Web APIs
rmation about the remote device's location, network topology, and so forth. it can also be used for fingerprinting purposes. the candidate ip addresses are always exposed to the application through address, and unsavory applications can in turn potentially reveal the address to the user. this can occur without the remote peer's consent. applications being built with user privacy and security in mind can choose to limit the permitted candidates to relay candidates only. doing so prevents the remote user's address from being exposed, but reduces the pool of available candidates to choose from. 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", ...
RTCIceCandidate.component - Web APIs
7325 1 udp 2043278322 192.168.0.56 44323 typ host this is an ice candidate a-line, whose foundation is 4234997325. the next field on the a-line, "1", is the component id. a value of "1" indicates rtp, which is recorded in the component property as "rtp". if this value were instead "2", the a-line would be describing an rtcp candidate, and compoment would be "rtcp". example this code snippet examines a candidate's component type and dispatches the candidate to different handlers depending on the value. if (candidate.component == "rtp") { handlertpcandidate(candidate); } else if (candidate.component == "rtcp") { handlertcpcandidate(candidate); } else { handleunknowncandidate(candidate); } specifications specification status comment webrtc 1.0: real-time commu...
RTCIceCandidate.foundation - Web APIs
pported by the user agent — passing the candidate to addicecandidate() will fail, throwing an operationerror exception. usage notes consider this sdp attribute line (a-line) which describes an ice candidate: a=candidate:4234997325 1 udp 2043278322 192.168.0.56 44323 typ host the field "4234997325" is the foundation. example this code snippet uses the foundation of two candidates to determine if they're actually the same candidate. if (candidate1.foundation == candidate2.foundation) { /* the two candidates are the same, even if they're on different transports */ } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicecandidate.foundation' in that specification. candidate recommenda...
RTCIceCandidate.priority - Web APIs
this applies only if the candidate implements the priority property. usage notes consider this sdp attribute line (a-line) which describes an ice candidate: a=candidate:4234997325 1 udp 2043278322 192.168.0.56 44323 typ host the priority is the number after the protocol, so it's the fourth field in the candidate string. in this example, the priority is 2043278322. example this candidate examines the priority of the candidate and, if it's greater than the priority of a previously-seen candidate, remembers the candidate for later use. var bestcandidate = { candidate: "", sdpmid: null, sdpmlineindex: null, priority: 0 }; function handlecandidate(candidatestring) { var candidate = new rtcicecandidate(candidatestring); if (candidate.priority > bestcandidate.priority) { be...
RTCIceCandidate.protocol - Web APIs
he user agent — passing the candidate to addicecandidate() will fail, throwing an operationerror exception. usage notes here's an example candidate a-line from an ice transaction: a=candidate:4234997325 1 udp 2043278322 192.168.0.56 44323 typ host the third field, "udp", is the protocol type, indicating that the candidate would use the udp transport protocol. example this code snippet examines the value of protocol to decide if it should look at the value of tcptype to see if it's a simultaneous-open (s-o) candidate. if (candidate.protocol == "tcp") { if (candidate.tcptype == "so") { adjustforsimultaneousopen(candidate); } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicecandidat...
RTCIceCandidate.tcpType - Web APIs
te() constructor is used. you can't directly set its value; instead, its value is automatically extracted from the candidate a-line, if it's formatted properly. syntax var tcptype = rtcicecandidate.tcptype; value a domstring whose value is one of those defined by the rtcicetcpcandidatetype enumerated type. "active" the transport will try to open an outbound connection but won't receive inoming connection requests. "passive" the transport will receive incoming connection requests but won't try to open an outbound connection. "so" the transport will try to open a connection simultaneously with its peer. tcptype is null for udp candidates. example in this example, the candidate's protocol and tcptype are used to adjust the user interface for simultaneous-open tcp candidates. if ...
RTCIceCandidate. toJSON() - Web APIs
you can then get a stringified version of the object by calling stringify() on the returned object. see the example below. ...
RTCIceCandidatePairStats.availableOutgoingBitrate - Web APIs
the rtcicecandidatepairstats property availableoutgoingbitrate returns a value indicative of the available outbound capacity of the network connection represented by the candidate pair. the higher the value, the more bandwidth you can assume is available for outgoing data. you can get the incoming available bitrate from availableincomingbitrate. syntax availableoutgoingbitrate = rtcicecandidatepairstats.availableoutgoingbitrate; value a floating-point value which approximates the amount of available bandwidth for outgoing data on the network connection described by the rtcicecandidatepair. the value is reported in bits per second and is computed over a 1-second interval. the returned value is undefined in each of the following situations: the underlying implementation doesn't suppor...
RTCIceCandidatePairStats.selected - Web APIs
ox-specific rtcicecandidatepairstats property selected indicates whether or not the candidate pair described by the object is the one currently being used to communicate with the remote peer. syntax isselected = icpstats.selected; value a firefox-specific boolean value which is true if the candidate pair described by this object is the one currently in use. in any other browser, you can determine the selected candidate pair by looking for a stats object of type transport, which is an rtctransportstats object. that object's selectedcandidatepairid property indicates whether or not the specified transport is the one being used. example the function shown in this example identifies the currently-selected candidate pair from a statistics report by first iterating over each report, looking ...
RTCIceCandidateStats.networkType - Web APIs
ribed connection uses wifi. wimax the described connection uses a wimax network. vpn the connection uses a virtual private network (vpn). the vpn obscures the underlying network type, which is not discernible. unknown the user's browser is unable or unwilling to identify the underlying connection technology used by the described connection. this may be because the browser isn't able to determine the network type for some reason or it may be intentionally getting obscured for security reasons, such as to avoid device fingerprinting. note: keep in mind that the specified value only reflects the initial connection between the local peer and the next hop along the network toward reaching the remote peer. for example, if the networktype is wifi but the user is connected using a cellular h...
RTCIceCandidateStats.priority - Web APIs
the rtcicecandidatestats dictionary's priority property is a positive integer value indicating the priority (or desirability) of the described candidate. during ice negotiation while setting up a webrtc peer connection, the priority values reported to the remote peer by a user agent are used to determine which candidates are considered "more desirable". the higher the value, the more desirable the candidate is. syntax priority = rtcicecandidatestats.priority; value a positive integer indicating the priority of the rtcicecandidate described by the rtcicecandidatestats object. the value may be anywhere from 1 to 2,147,483,647. determining priority the ice specification describes how user agents and other software using webrtc should calculate the priority. the priority of a candidate is ...
RTCIceCandidateStats - Web APIs
idates, the url property is the url of the ice server from which the candidate was received. this url matches the one included in the rtcpeerconnectioniceevent object representing the icecandidate event that delivered the candidate to the local peer. example this example features a function, isusablenetworktype(), whose job it is to look at an rtcicecandidatestats object's networktype and determine whether or not the type of network is acceptable for use. this function is then called for rtcstats objects whose type is local-candidate, indicating that the object is in fact an rtcicecandidatestats with information about a local ice candidate. const isusablenetworktype = stats => { switch(stats.networktype) { case "ethernet": case "vpn": return true; case "bluetooth": ...
RTCIceServers.urls - Web APIs
Web › API › RTCIceServer › urls
.example.org", username: "webrtc", credential: "turnpassword" } ] }); a single ice server with multiple urls the next example creates a new rtcpeerconnection which will use a single turn server which has multiple urls. this is useful if the server is, for example, available both on "turn" and "turns" schemes, or if there's a fallback address available for the server. keep in mind that ice will try all the urls you list here, so the more you include, the longer connections will take to establish. mypeerconnection = new rtcpeerconnection({ iceservers: [ { urls: ["turns:turnserver.example.org", "turn:turnserver.example.org"], username: "webrtc", credential: "turnpassword" } ] }); multiple ice servers finally, this example creates a new rtcp...
RTCIceTransport.getRemoteCandidates() - Web APIs
received candidate to the ice session, the ice agent places it in the list returned by this function. syntax remotecandidates = rtcicetransport.getremotecandidates(); parameters none. return value an array containing one rtcicecandidate object for each candidate that has been received so far from the remote peer during the current ice candidate gathering session. it's important to keep in mind that there's no way to correlate these remote candidates with compatible local candidates. to find the best match found so far, call rtcicetransport.getselectedcandidatepair(). example this simple example gets the remote candidate list from the rtcicetransport for the first rtcrtpsender on the rtcpeerconnection, then outputs to the console all of the candidates in the list. var remotecandidat...
RTCIceTransport.ongatheringstatechange - Web APIs
dler for the rtcicetransport interface specifies an event handler that is to be called when the gatheringstatechange event occurs on the transport. this event is delivered whenever the transport's gatheringstate property changes. syntax rtcicetransport.ongatheringstatechange = statechangehandler; value a function to be called when the rtcicetransport object's gathering state changes. to determine the new state, examine the value of gatheringstate. the gathering state indicates whether or not the ice agent has begun gathering candidates, and if so, whether or not gathering has finished. its possible values are: "new" the rtcicetransport is newly created and has not yet started to gather ice candidates. "gathering" the transport is in the process of gathering candidates. "complete"...
RTCIceTransport.onselectedcandidatepairchange - Web APIs
ent 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. this event will occur at least once, and may occur more than once if the ice agent continues to identify candidate pairs that will work better, more closely match the requested parameters, and so forth. the event handler can determine the current state by calling the transport's getselectedcandidatepair() method, which returns a rtcicecandidatepair whose rtcicecandidatepair.local and rtcicecandidatepair.global properties specify rtcicecandidate objects describing the local and remote candidates that are currently being used. example in this example, an event handler for selectedcandidatepairchange is set up to update an on-...
RTCIceTransport.onstatechange - Web APIs
statechange event that is fired whenever the transport's state changes. syntax rtcicetransport.onstatechange = statechangehandler; value set this property to reference a function you provide that is called by the webrtc layer when the rtcicetransport object's state changes. the event handler receives as its sole input an event object describing the statechange event which occurred. to determine the new state, examine the value of state. example this snippet establishes a handler for the statechange event that looks to see if the transport has entered the "failed" state, which indicates that the connection has failed with no chance of being automatically restored. var icetransport = pc.getsenders()[0].transport.icetransport; icetransport.onstatechange = function(event) { if (icetr...
RTCIceTransport: statechange event - Web APIs
bubbles no cancelable no interface event event handler property rtcicetransport.onstatechange examples given an rtcpeerconnection, pc, the following code creates an event handler that calls a function named handlefailure() if the ice transport enters a failure state. ...
RTCIceTransport - Web APIs
g", or "complete". role read only returns a domstring whose value is one of the members of the rtcicerole enumerated type: "controlling" or "controlled"; this indicates whether the ice agent is the one that makes the final decision as to the candidate pair to use or not. state read only a domstring indicating what the current state of the ice agent is. 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. see the rtcicetransportstate enumerated type for a complete list of states. methods also includes methods from eventtarget, the parent interface. getlocalcandidates() returns an arr...
RTCInboundRtpStreamStats.averageRtcpInterval - Web APIs
p interval is the amount of time that should elapse between transmissions of rtcp packets. syntax var averagertcpinterval = rtcinboundrtpstreamstats.averagertcpinterval; value a floating-point value indicating the average interval, in seconds, between transmissions of rtcp packets. this interval is computed following the formula outlined in rfc 1889: a.7. because the interval's value is determined in part by the number of active senders, it will be different for each user of a service. 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. the sending end...
RTCInboundRtpStreamStats.fecPacketsReceived - Web APIs
rded instead of being used. 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. this may also happen if the fec packet arrives outside the window of time in which the client will attempt to use it. if you wish to know how many of the received packets were discarded, you can examine the value of fecpacketsdiscarded. specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcinboundrtpstreamstats.fecpacketsreceived' in that specification. candidate recommendation initial definition. ...
RTCInboundRtpStreamStats.framesDecoded - Web APIs
y of the rtcinboundrtpstreamstats dictionary indicates the total number of frames which have been decoded successfully for this media source. syntax var framesdecoded = rtcinboundrtpstreamstats.framesdecoded; value an integer value indicating the total number of video frames which have been decoded for this stream so far. this represents the number of frames that would have been displayed assuming no frames were skipped. specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcinboundrtpstreamstats.framesdecoded' in that specification. candidate recommendation initial definition. ...
RTCInboundRtpStreamStats.qpSum - Web APIs
e process of applying lossy compression to a range of values, resulting in a single quantum value. this value takes the place of the range of values, thereby reducing the number of different values that appear in the overall data set, making the data more compressible. the quantization process and the amount of compression can be controlled using one or more parameters. it's important to keep in mind that the value of qp can change periodically—even every frame—so it's difficult to know for certain how substantial the compression is. the best you can do is make an estimate. you can, for example, use the value of rtcreceivedrtpstreamstats.framesdecoded if receiving the media or rtcsentrtpstreamstats.framesencoded if sending it to get the number of frames handled so far, and compute an ave...
RTCInboundRtpStreamStats.sliCount - Web APIs
ce loss indication (sli) packets the rtcrtpreceiver for which this object provdes statistics sent to the remote rtcrtpsender. an sli packet is used by a decoder to let the encoder 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, requiring resends or dropping frames. syntax var slicount = rtcinboundrtpstreamstats.slicount; value an unsigned integer indicating the number of sli packets this receiver sent to the remote sender due to lost runs of macroblocks. a high value of slicount may be an indication of an unreliable network. this is a very technical part of how video ...
RTCInboundRtpStreamStats.trackId - Web APIs
syntax var trackstatsid = rtcinboundrtpstreamstats.trackid; value a domstring containing the id of the rtcreceiveraudiotrackattachmentstats or rtcreceivervideotrackattachmentstats object representing the track which is receiving the media from this rtp session. ...
RTCInboundRtpStreamStats - Web APIs
services code point (dscp). 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. this is only available for video streams. qpsum a 64-bit value containing the sum of the qp values for every frame decoded by this rtp receiver. you can determine the average qp per frame by dividing this value by framesdecoded. valid only for video streams. receiverid a string indicating which identifies the rtcaudioreceiverstats or rtcvideoreceiverstats object associated with the stream's receiver. this id is stable across multiple calls to getstats(). remoteid a string which identifies the rtcremoteoutboundrtpstreamstats object that provides statis...
RTCNetworkType - Web APIs
ribed connection uses wifi. wimax the described connection uses a wimax network. vpn the connection uses a virtual private network (vpn). the vpn obscures the underlying network type, which is not discernible. unknown the user's browser is unable or unwilling to identify the underlying connection technology used by the described connection. this may be because the browser isn't able to determine the network type for some reason or it may be intentionally getting obscured for security reasons, such as to avoid device fingerprinting. note: keep in mind that the specified value only reflects the initial connection between the local peer and the next hop along the network toward reaching the remote peer. for example, if the networktype is wifi but the user is connected using a cellular h...
RTCOfferAnswerOptions.voiceActivityDetection - Web APIs
sed and that if possible, the user agent should automatically disable or mute outgoing audio when the audio source is not sensing a human voice. syntax var options = { voiceactivitydetection: trueorfalse }; value a boolean value indicating whether or not the connection should use voice detection once running. the default value, true, indicates that the user agent should monitor the audio coming from the microphone or other audio source and automatically cease transmitting data or mute when the user isn't speaking into the microphone, a value of false indicates that the audio should continue to be transmitted regardless of whether or not speech is detected. ...
RTCOutboundRtpStreamStats.averageRtcpInterval - Web APIs
g the average time that should pass between transmissions of rtcp packets on this stream. syntax var averagertcpinterval = rtcoutboundrtpstreamstats.averagertcpinterval; value a floating-point value indicating the average interval, in seconds, between transmissions of rtcp packets. this interval is computed following the formula outlined in rfc 1889: a.7. because the interval's value is determined in part by the number of active senders, it will be different for each user of a service. 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. the sending end...
RTCOutboundRtpStreamStats.qpSum - Web APIs
e process of applying lossy compression to a range of values, resulting in a single quantum value. this value takes the place of the range of values, thereby reducing the number of different values that appear in the overall data set, making the data more compressible. the quantization process and the amount of compression can be controlled using one or more parameters. it's important to keep in mind that the value of qp can change periodically—even every frame—so it's difficult to know for certain how substantial the compression is. the best you can do is make an estimate. you can use the value of rtcsentrtpstreamstats.framesencoded to get the number of frames that have been encoded so far, and compute an average from there. see calculating average quantization below for a function that...
RTCOutboundRtpStreamStats.sliCount - Web APIs
li) packets the rtcrtpsender received from the remote rtcrtpreceiver for the rtp stream described by this object. 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. syntax var slicount = rtcoutboundrtpstreamstats.slicount; value an unsigned integer indicating the number of sli packets the sender received from the receiver due to lost runs of macroblocks. a high value of slicount may be an indication of an unreliable network. this is a ...
RTCPeerConnection.addIceCandidate() - Web APIs
any candidates which you'll deliver to the ice agent in this way, allowing it to build up a list of potential connection methods. this is covered in more detail in the articles webrtc connectivity and signaling and video calling. syntax apromise = pc.addicecandidate(candidate); addicecandidate(candidate, successcallback, failurecallback); parameters candidate optional an object conforming to the rtcicecandidateinit dictionary, or an rtcicecandidate object; the contents of the object should be constructed from a message received over the signaling channel, describing a newly received ice candidate that's ready to be delivered to the local ice agent. 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-...
RTCPeerConnection.addStream() - Web APIs
set to stable, the event negotiationneeded is sent on the rtcpeerconnection to indicate that ice negotiation must be repeated to consider the new stream. syntax rtcpeerconnection.addstream(mediastream); parameters mediastream a mediastream object indicating the stream to add to the webrtc peer connection. return value none. example this simple example adds the audio and video stream coming from the user's camera to the connection. navigator.mediadevices.getusermedia({video:true, audio:true}, function(stream) { var pc = new rtcpeerconnection(); pc.addstream(stream); }); migrating to addtrack() compatibility allowing, you should update your code to instead use the addtrack() method: navigator.getusermedia({video:true, audio:true}, function(stream) { var pc = new rtcpeercon...
RTCPeerConnection: addstream event - Web APIs
h for the track event, which is sent for each media track added to the rtcpeerconnection. bubbles no cancelable no interface mediastreamevent event handler property rtcpeerconnection.onaddstream you can, similarly, watch for streams to be removed from the connection by monitoring the removestream event. examples this example looks to determine if the user's browser supports the track event. if it does, a track event listener is set up; otherwise, an addstream event listener is set up. pc is an rtcpeerconnection. if (pc.addtrack !== undefined) { pc.ontrack = ev => { ev.streams.foreach(stream => doaddstream(stream)); } } else { pc.onaddstream = ev => { doaddstream(ev.stream); } } this calls a function doaddstream() on...
RTCPeerConnection.canTrickleIceCandidates - Web APIs
changes to "completed" before creating and sending the initial offer. that way, the offer contains all of the candidates. syntax var cantrickle = rtcpeerconnection.cantrickleicecandidates; value a boolean that is true if the remote peer can accept trickled ice candidates and false if it cannot. if no remote peer has been established, this value is null. note: this property's value is determined once the local peer has called rtcpeerconnection.setremotedescription(); the provided description is used by the ice agent to determine whether or not the remote peer supports trickled ice candidates. example var pc = new rtcpeerconnection(); // the following code might be used to handle an offer from a peer when // it isn't known whether it supports trickle ice. pc.setremotedescription(remo...
RTCPeerConnection.close() - Web APIs
this also releases any resources in use by the ice agent, including turn permissions. all rtcrtpsender objects are considered to be stopped once this returns (they may still be in the process of stopping, but for all intents and purposes, they're stopped). ...
RTCPeerConnection.getConfiguration() - Web APIs
ficate({ name: 'rsassa-pkcs1-v1_5', hash: 'sha-256', moduluslength: 2048, publicexponent: new uint8array([1, 0, 1]) }).then(function(cert) { configuration.certificates = [cert]; mypeerconnection.setconfiguration(configuration); }); } this example fetches the current configuration of the rtcpeerconnection, then looks to see if it has any certificates set by examining whether or not (a) the configuration has a value for certificates, and (b) whether its length is zero. if it's determined that there are no certificates in place, rtcpeerconnection.generatecertificate() is called to create a new certificate; we provide a fulfillment handler which adds a new array containing the one newly-created certificate to the current configuration and passes it to setcon...
RTCPeerConnection.getSenders() - Web APIs
syntax var senders = rtcpeerconnection.getsenders(); return value an array of rtcrtpsender objects, one for each track on the connection. the array is empty if there are no rtp senders on the connection. ...
RTCPeerConnection: iceconnectionstatechange event - Web APIs
t the connection had been temporarily lost. state transitions as negotiation ends when the negotiation process runs out of candidates to check, the ice connection transitions to one of two states. if no suitable candidates were found, the state transitions to failed. if at least one suitable candidate was successfully identified, the state transitions to completed. the ice layer makes this determination upon receiving the end-of-candidates signal, which is provided by caling addicecandidate() with a candidate whose candidate property is an empty string (""), or by setting the rtcpeerconnection property cantrickleicecandidates to false. examples an event handler for this event can be added using the rtcpeerconnection.oniceconnectionstatechange property or by using addeventlistener() on the...
RTCPeerConnection: icegatheringstatechange event - Web APIs
ering to indicate that the process of collecting candidate configurations for the connection has begun. when the value changes to complete, all of the transports that make up the rtcpeerconnection have finished gathering ice candidates. bubbles no cancelable no interface event event handler onicegatheringstatechange note: while you can determine that ice candidate gathering is complete by watching for icegatheringstatechange events and checking for the value of icegatheringstate to become complete, you can also simply have your handler for the icecandidate event look to see if its candidate property is null. this also indicates that collection of candidates is finished. examples this example creates a handler for icegatheringstatecha...
RTCPeerConnection: icecandidate event - Web APIs
on. sharing a new candidate the majority of icecandidate events are fired to indicate that a new candidate has been gathered. this candidate needs to be delivered to the remote peer over the signaling channel your code manages. 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. indicating the end of a generation of candidates when an ice negotiation session runs out of candidates to propose for a given rtcicetransport, it has comple...
RTCPeerConnection: icecandidateerror event - Web APIs
the event object is of type rtcpeerconnectioniceerrorevent, and contains information describing the error in some amount of detail. bubbles no cancelable no interface rtcpeerconnectioniceerrorevent event handler property rtcpeerconnection.onicecandidateerror description the error object's errorcode property is one of the numeric stun error codes. there is one additional, webrtc-specific, error which lies outside the valid stun error code range: 701. ...
RTCPeerConnection.oniceconnectionstatechange - Web APIs
ction's ice agent, as represented by the iceconnectionstate property, changes. syntax rtcpeerconnection.oniceconnectionstatechange = eventhandler; value this event handler can be set to function which is passed a single input parameter: an event object describing the iceconnectionstatechange event which occurred. your code can look at the value of rtcpeerconnection.iceconnectionstate to determine what the new state is. example the example below watches the state of the ice agent for a failure or unexpected closure and takes appropriate action, such as presenting an error message or attempting to restart the ice agent. pc.oniceconnectionstatechange = function(event) { if (pc.iceconnectionstate === "failed" || pc.iceconnectionstate === "disconnected" || pc.iceconnectionsta...
RTCPeerConnection.onnegotiationneeded - Web APIs
eeded event will fire until negotiation completes, and only then if negotiation is still needed. syntax rtcpeerconnection.onnegotiationneeded = eventhandler; value this should be set to a function you provide which is passed a single parameter: an event object containing the negotiationneeded event. there's no additional information provided in the event; anything you need, you can get by examining the properties of the rtcpeerconnection. example this example, derived from the example in signaling and video calling, establishes a handler for negotiationneeded events to handle creating an offer, configuring the local end of the connection, and sending the offer to the remote peer. pc.onnegotiationneeded = function() { pc.createoffer().then(function(offer) { return pc.setlocaldesc...
RTCPeerConnection.onsignalingstatechange - Web APIs
signalingstate changes, which may happen either because of a call to setlocaldescription() or to setremotedescription(). syntax rtcpeerconnection.onsignalingstatechange = errorhandler; value set this to a function which you provide that receives an event object as input; this contains the signalingstatechange event. this event object doesn't provide details about what changed, but you can examine the signalingstate property to determine what the new state is. 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 even...
RTCPeerConnection.peerIdentity - Web APIs
ntifying the remote peer. once this promise resolves successfully, the resulting identity is the target peer identity and cannot change for the duration of the connection. syntax var identity = rtcpeerconnection.peeridentity; value a javascript promise which resolves to an rtcidentityassertion that describes the remote peer's identity. if an error occcurs while attempting to validate an incoming identity assertion (that is, the information describing a peer's identity), the promise is rejected. if there isn't already a target peer identity, peeridentity is set to a newly created promise and the process begins again, until the process succeeds or no further attempts to authenticate occur. note: the promise returned by setremotedescription() cannot resolve until any target peer identity...
RTCPeerConnection.pendingLocalDescription - Web APIs
nt. for details on the difference, see pending and current descriptions in webrtc connectivity. syntax sessiondescription = rtcpeerconnection.pendinglocaldescription; return value if a local description change is in progress, this is an rtcsessiondescription describing the proposed configuration. otherwise, this returns null. example this example looks at the pendinglocaldescription to determine whether or not there's a description change being processed. var pc = new rtcpeerconnection(); … var sd = pc.pendinglocaldescription; if (sd) { // there's a description change underway! } else { // no description change pending } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnecti...
RTCPeerConnection.pendingRemoteDescription - Web APIs
for details on the difference, see pending and current descriptions in webrtc connectivity. syntax sessiondescription = rtcpeerconnection.pendingremotedescription; return value if a remote description change is in progress, this is an rtcsessiondescription describing the proposed configuration. otherwise, this returns null. example this example looks at the pendingremotedescription to determine whether or not there's a description change being processed. var pc = new rtcpeerconnection(); … var sd = pc.pendingremotedescription; if (sd) { // there's a description change underway! } else { // no description change pending } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnect...
RTCPeerConnection.restartIce() - Web APIs
eer has been set) and on the remote peer, once the offer is sent across your signaling mechanism and the remote peer has set its description as well. restartice() causes the negotiationneeded event to be fired on the rtcpeerconnection to inform the application that it should perform negotiation using its signaling channel. if negotiation fails to complete—either due to rollback or because incoming offers are in the process of being negotiated—the rtcpeerconnection will remember that you requested ice restart. the next time the connection's signalingstate changes to stable, the connection will fire the negotiationneeded event. this process continues until an ice restart has been successfully completed. syntax rtcpeerconnection.restartice(); parameters none. return value undefined. ...
RTCPeerConnection.sctp - Web APIs
ibing the sctp transport being used by the rtcpeerconnection for transmitting and receiving on its data channels, or null if sctp negotiation hasn't happened. example var pc = new rtcpeerconnection(); var channel = pc.createdatachannel("mydata"); channel.onopen = function(event) { channel.send('sending a message'); } channel.onmessage = function(event) { console.log(event.data); } // determine the largest message size that can be sent var sctp = pc.sctp; var maxmessagesize = sctp.maxmessagesize; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.sctp' in that specification. candidate recommendation initial specification. ...
RTCPeerConnection.setConfiguration() - Web APIs
ut the connection already has identity information specified. this happens if configuration.peeridentity or configuration.certificates is set and their values differ from the current configuration. invalidstateerror the rtcpeerconnection is closed. syntaxerror one or more of the urls provided in the configuration.iceservers list is invalid. example in this example, it has already been determined that ice restart is needed, and that negotiation needs to be done using a different ice server. var restartconfig = { iceservers: [{ urls: "turn:asia.myturnserver.net", username: "allie@oopcode.com", credential: "topsecretpassword" }] }; mypeerconnection.setconfiguration(restartconfig); mypeer...
RTCPeerConnection.setIdentityProvider() - Web APIs
ignalingstate is set to "closed", an invalidstateerror is raised. syntax pc.setidentityprovider(domainname [, protocol] [, username]); there is no return value for this method. parameters domainname is a domstring is the domain name where the idp is. protocol optional is a domstring representing the protocol used to communicate with the idp. it defaults to "default" and is used to determine the url where the idp is listening. username optional is a domstring representing the username associated with the idp. example var pc = new peerconnection(); pc.setidentityassertion("developer.mozilla.org"); specifications specification status comment identity for webrtcthe definition of 'rtcpeerconnection.setidentityprovider()' in that specification. can...
RTCPeerConnectionIceErrorEvent.address - Web APIs
omstring which specifies the local ip address of the network connection to the ice server with which negotiations were occurring when the error occurred. this address identifies the network interface on the local device which is being used to attempt to establish the connection to the remote peer. this can be useful on multi-homed systems—devices with more than one network connection—to determine which network interface is being used. for example, on a mobile phone, there are typically at least two network interfaces available: the cellular connection and a wifi connection. if the local ip address isn't exposed as part of a local candidate, the value of address is null. examples this example creates a handler for icecandidateerror events which creates human readable messages describin...
RTCRemoteOutboundRtpStreamStats.remoteTimestamp - Web APIs
ghrestimestamp value indicating the timestamp on the remote peer at which it sent these statistics. this is different from the value timestamp, which gives the time at which the statistics were generated or received by the local peer. if this property is present, it comes from the rtcp sender report (sr) block, which reflects the clock on the remote peer at the time the message was sent. keep in mind that this means the clock may not be synchronized with the local clock, and that both the current time and the pace at which the clock runs may differ to some extent. specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcremoteoutboundrtpstreamstats.remotetimestamp' in that specification. candidate recommendation ...
RTCRtpReceiver.getCapabilities() static function - Web APIs
tcrtpreceiver.getcapabilities("audio"); the returned set of capabilities is the most optimistic possible list. it is entirely possible that certain combinations of options may fail to work when you actually try to use them. calling rtcrtpreceiver.getcapabilities() doesn't prime the browser in any way to handle media. nothing is loaded, fetched, or otherwise prepared. it's simply a means of determining what might be usable before starting to try to access media. because the set of capabilities available tend to be stable for a length of time (people don't install and uninstall codecs and the like very often), the media capabilities can in whole or in part provide a cross-origin method for identifying a user. for that reason, in privacy-sensitive contexts, the browser may choose to obscure t...
RTCRtpReceiver.getContributingSources() - Web APIs
utingsource instances, each corresponding to one csrc (contributing source) identifier received by the current rtcrtpreceiver in the last ten seconds. syntax var rtcrtpcontributingsources = rtcrtpreceiver.getcontributingsources() parameters none. return value an array of rtcrtpcontributingsource instances. each instance describes one of the contributing sources that provided data to the incoming stream in the past ten seconds. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'getcontributingsources()' in that specification. candidate recommendation initial definition. ...
RTCRtpReceiver.getStats() - Web APIs
the rtcrtpreceiver method getstats() asynchronously requests an rtcstatsreport object which provides statistics about incoming traffic on the owning rtcpeerconnection, returning a promise whose fulfillment handler will be called once the results are available. syntax var promise = rtcrtpreceiver.getstats(); return value a javascript promise which is fulfilled once the statistics are available. the promise's fulfillment handler receives as a parameter a rtcstatsreport object containing the collected statistics. the returned statistics include those from all streams which are coming in through the rtcrtpreceiver, as well as any of their dependencies. example this simple example obtains the statistics for an rtcrtpreceiver and updates an element's innertext to display the number of pack...
RTCRtpReceiver.getSynchronizationSources() - Web APIs
ce instances, each corresponding to one ssrc (synchronization source) identifier received by the current rtcrtpreceiver in the last ten seconds. syntax var rtcrtpcontributingsources = rtcrtpreceiver.getcontributingsources() parameters none. return value an array of rtcrtpsynchronizationsource instances. each instance describes one of the synchronization sources that provided data to the incoming stream in the past ten seconds. as you'll see in the documentarion for rtcrtpsynchronizationsource, it inherits the properties of rtcrtpcontributingsource, including timestamp, source, and audiolevel. the synchronization source objects add a voiceactivityflag property, which indicates if the last rtp packet received contained voice activity. specifications specification status ...
RTCRtpReceiver - Web APIs
tances for each unique csrc (contributing source) identifier received by the current rtcrtpreceiver in the last ten seconds. rtcrtpreceiver.getparameters() returns an rtcrtpparameters object which contains information about how the rtc data is to be decoded. rtcrtpreceiver.getstats() returns a promise whose fulfillment handler receives a rtcstatsreport which contains statistics about the incoming streams and their dependencies. rtcrtpreceiver.getsynchronizationsources() returns an array including one rtcrtpsynchronizationsource instance for each unique ssrc (synchronization source) identifier received by the current rtcrtpreceiver in the last ten seconds. static methods rtcrtpreceiver.getcapabilities() returns the most optimistic view of the capabilities of the system for receiv...
RTCRtpSendParameters.encodings - Web APIs
the rtcrtpsendparameters dictionary's encodings property is an rtcrtpencodingparameters object providing configuration settings for the encoder being used for the rtcrtpsender's track. syntax sendparameters.encodings = encodingparameterlist; encodingparameterlist = sendparameters.encodings; value an array of objects conforming to the rtcrtpencodingparameters dictionary, each of which contains properties which provide settings and parameters that describe and configure a single codec that could be used to encode the track. each object's properties are: active if true, the described encoding is currently actively being used. that is, for rtp senders, the encoding is currently being used to send data, while for receivers, the encoding is being used to decode received data. the default...
RTCRtpSender.getCapabilities() static function - Web APIs
= rtcrtpsender.getcapabilities("audio"); the returned set of capabilities is the most optimistic possible list. it is entirely possible that certain combinations of options may fail to work when you actually try to use them. calling rtcrtpsender.getcapabilities() doesn't prime the browser in any way to handle media. nothing is loaded, fetched, or otherwise prepared. it's simply a means of determining what might be usable before starting to try to access media. because the set of capabilities available tend to be stable for a length of time (people don't install and uninstall codecs and the like very often), the media capabilities can in whole or in part provide a cross-origin method for identifying a user. for that reason, in privacy-sensitive contexts, the browser may choose to obscure t...
RTCRtpSender.setParameters() - Web APIs
changes the configuration of sender's track, which is the mediastreamtrack for which the rtcrtpsender is responsible. in other words, setparameters() updates the configuration of the rtp transmission as well as the encoding configuration for a specific media track on the webrtc connection. syntax var promise = rtcrtpsender.setparameters(parameters) parameters parameters an object conforming with the rtcrtpsendparameters dictionary, specifying options for the rtcrtpsender; these include potential codecs that could be use for encoding the sender's track. the available options are: degradationpreference specifies the preferred way the webrtc layer should handle optimizing bandwidth against quality in constrained-bandwidth situations; the value comes from the rtcdegradationprefe...
RTCRtpSender - Web APIs
rtcrtpsender. rtcrtpsender.setparameters() applies changes to parameters which configure how the track is encoded and transmitted to the remote peer. rtcrtpsender.setstreams() sets the mediastream(s) associated with the track being transmitted by this sender. rtcrtpsender.replacetrack() attempts to replace the track currently being sent by the rtcrtpsender with another track, without performing renegotiation. this method can be used, for example, to toggle between the front- and rear-facing cameras on a device. static methods rtcrtpsender.getcapabilities() returns an rtcrtpcapabilities object describing the system's capabilities for sending a specified kind of media data. specifications specification status comment webrtc 1.0: real-time communication be...
RTCRtpStreamStats.kind - Web APIs
the kind property of the rtcrtpstreamstats dictionary is a string indicating whether the described rtp stream contains audio or video media. its value is always either "audio" or "video". this property was previously called mediatype. the name was changed in the specification in february, 2018. see browser compatibility below to determine how this affects the browsers you're targeting. syntax mediakind = rtcrtpstreamstats.kind; value a domstring whose value is "audio" if the track whose statistics are given by the rtcrtpstreamstats object contains audio, or "video" if the track contains video media. this string will always be the same as the one provided by the associated mediastreamtrack object's kind property. it will also match the statistics object's rtccodecstats.codec property's ...
RTCRtpStreamStats.qpSum - Web APIs
e process of applying lossy compression to a range of values, resulting in a single quantum value. this value takes the place of the range of values, thereby reducing the number of different values that appear in the overall data set, making the data more compressible. the quantization process and the amount of compression can be controlled using one or more parameters. it's important to keep in mind that the value of qp can change periodically—even every frame—so it's difficult to know for certain how substantial the compression is. the best you can do is make an estimate. you can, for example, use the value of rtcreceivedrtpstreamstats.framesdecoded if receiving the media or rtcsentrtpstreamstats.framesencoded if sending it to get the number of frames handled so far, and compute an ave...
RTCRtpSynchronizationSource - Web APIs
since rtcrtpsynchronizationsource implements rtcrtpcontributingsource, its properties are also available. the information provided is based on the last ten seconds of media received. while the published specification describes this as an interface, it has since been changed to a dictionary in follow-up drafts. ...
RTCRtpTransceiver.direction - Web APIs
ne of the sender's encodings is active1. does not offer to receive rtp data and will not do so. "recvonly" does not offer to send rtp data, and will not do so. offers to receive rtp data, and will do so if the other peer offers. "inactive" does not offer to send rtp data, and will not do so. does not offer to receive rtp data and will not do so. [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. exceptions when setting the value of direction, the following exceptions can occur: invalidstateerror either the receiver'...
RTCRtpTransceiver.receiver - Web APIs
the read-only receiver property of webrtc's rtcrtptransceiver interface indicates the rtcrtpreceiver responsible for receiving and decoding incoming media data for the transceiver's stream. syntax var rtpreceiver = rtcrtptransceiver.receiver; value an rtcrtpreceiver object which is responsible for receiving and decoding incoming media data whose media id is the same as the current value of mid. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtptransceiver.receiver' in that specification. candidate recommendation ...
RTCRtpTransceiver.setCodecPreferences() - Web APIs
to support every codec in the list. if any unsupported codecs are listed, the browser will throw an invalidaccesserror exception when you call this method. a good approach to setting codec preferences is to first get the list of codecs that are actually supported, then modify that list to match what you want. pass the altered list into setcodecpreferences() to specify your preferences. to determine which codecs are supported by the transceiver, call the sender's getcapabilities() and the receiver's getcapabilities() methods and get the codecs list from the results of each. the following code snippet demonstrates how to get both the list of codecs supported by the transceiver's rtcrtpsender and rtcrtpreceiver. var availsendcodecs = transceiver.sender.getcapabilities("video").codecs; var a...
RTCRtpTransceiverDirection - Web APIs
ne of the sender's encodings is active1. does not offer to receive rtp data and will not do so. "recvonly" does not offer to send rtp data, and will not do so. offers to receive rtp data, and will do so if the other peer offers. "inactive" does not offer to send rtp data, and will not do so. does not offer to receive rtp data and will not do so. [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. specifications specification status comment webrtc 1.0: real-time communication between browsersthe de...
RTCSctpTransport - Web APIs
ort layer security (dtls) transport over which sctp packets for all of an rtcpeerconnection's data channels are sent and received. you don't create rtcsctptransport objects yourself; instead, you get access to the rtcsctptransport for a given rtcpeerconnection through its sctp property. possibly the most useful property on this interface is its maxmessagesize property, which you can use to determine the upper limit on the size of messages you can send over a data channel on the peer connection. properties also inherits properties from: eventtarget rtcsctptransport.maxchannelsread only an integer value indicating the maximum number of rtcdatachannels that can be open simultaneously. rtcsctptransport.maxmessagesizeread only an integer value indicating the maximum size, in bytes, of ...
RTCStats.type - Web APIs
Web › API › RTCStats › type
syntax var type = rtcstats.type; value a domstring which specifies which type of statistic is represented by the object. the string comes from the rtcstatstype enum and corrsponds to one of the rtcstats-based statistic object types. ...
RTCStatsIceCandidatePairState - Web APIs
nection. see ice check lists in rtcicecandidatepairstats.state for further information about how ice check lsits work. values failed a check for this pair has been performed but failed. a failure can occur either because no response was received or because the response indicated that an unrecoverable error occurred. frozen no check has been performed yet for this candidate pair, and performing the check is blocked until another check is successful. once that check has succeeded, this pair will unfreeze and move into the waiting state. in-progress a check has been initiated for this pair, but the check's transaction is still in progress. succeeded a check for this pair has been completed successfully. waiting this pair has not yet been checked, but the check can be performed as s...
RTCTrackEvent - Web APIs
s the same one specified by the event's track, and the track has been added to any associated remote mediastream objects. 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. note: it may be helpful to keep in mind that you receive the track event when a new inbound track has been added to your connection, and you call addtrack() to add a track to the far end of the connection, thereby triggering a track event on the remote peer. example this simple example creates an event listener for the track event which sets the srcobject of the <video> element with the id videobox to the first stream in the list p...
Range.collapse() - Web APIs
Web › API › Range › collapse
syntax range.collapse(tostart); parameters tostart optional a boolean value: true collapses the range to its start, false to its end. if omitted, it defaults to false . ...
Range.getBoundingClientRect() - Web APIs
see element.getboundingclientrect() for details on the returned value. ...
ReadableStream - Web APIs
() pipes the current readablestream to a given writablestream and returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. readablestream.tee() the tee method tees this readable stream, returning a two-element array containing the two resulting branches as new readablestream instances. each of those streams receives the same incoming data. readablestream[@@asynciterator]() alias of getiterator method. examples in the following example, an artificial response is created to stream html fragments fetched from another resource to the browser. it demonstrates the usage of a readablestream in combination with a uint8array. fetch("https://www.example.org/").then((response) => { const reader = response.body.getreader(); c...
ReadableStreamBYOBReader - Web APIs
treams api represents a byob ("bring your own buffer") reader that can be used to read stream data supplied by the developer (e.g. a custom readablestream() constructor). constructor readablestreambyobreader() creates and returns a readablestreambyobreader object instance. properties readablestreambyobreader.closed read only allows you to write code that responds to an end to the streaming process. returns a promise that fulfills if the stream becomes closed or the reader's lock is released, or rejects if the stream errors. methods readablestreambyobreader.cancel() cancels the stream, signaling a loss of interest in the stream by a consumer. the supplied reason argument will be given to the underlying source, which may or may not use it. readablestreambyobreader.read() ret...
ReadableStreamDefaultReader - Web APIs
treamdefaultreader interface of the streams api represents a default reader that can be used to read stream data supplied from a network (e.g. a fetch request). constructor readablestreamdefaultreader() creates and returns a readablestreamdefaultreader object instance. properties readablestreamdefaultreader.closed read only allows you to write code that responds to an end to the streaming process. returns a promise that fulfills if the stream becomes closed or the reader's lock is released, or rejects if the stream errors. methods readablestreamdefaultreader.cancel() cancels the stream, signaling a loss of interest in the stream by a consumer. the supplied reason argument will be given to the underlying source, which may or may not use it. readablestreamdefaultreader.read(...
Reporting API - Web APIs
can be retrieved independently of the running of the websites they relate to, which is useful — a crash for example could bring down a web site and stop anything running, but a report could still be obtained to give the developer some clues as to why it happened. reporting observers reports can also be obtained via reportingobserver objects created via javascript inside the website you are aiming to get reports on. this method is not as failsafe as the report-to method described above — any page crash could stop you retrieving the reports — but it is easier to set up, and more flexible. 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 o...
Request.destination - Web APIs
the destination read-only property of the request interface returns a string describing the type of content being requested. the string must be one of those found in the requestdestination enumerated type or the empty string, which is the default value. the destination is used by the user agent to, for example, help determine which set of rules to follow for cors purposes, or how to navigate any complicated code paths that affect how specific types of request get handled. these destinations vary substantially in how they operate. some are simply data receptacles, where the received data is stored for processing later. others are script-based, in which case the received data is delivered to a script by calling it and passing the data along. script-based destinations include <script> element...
Request.mode - Web APIs
Web › API › Request › mode
syntax var mymode = request.mode; value a requestmode value. the associated mode, available values of which are: same-origin — if a request is made to another origin with this mode set, the result is simply an error. you could use this to ensure that a request is always being made to your origin. ...
ResizeObserver - Web APIs
the border box encompasses the content, padding, and border. see the box model for further explanation. resizeobserver avoids infinite callback loops and cyclic dependencies that are often created when resizing via a callback function. ...
ResizeObserverEntry - Web APIs
orted than the above two properties, but it is left over from an earlier implementation of the resize observer api, is still included in the spec for web compat reasons, and may be deprecated in future versions. resizeobserverentry.target read only a reference to the element or svgelement being observed. note: the content box is the box in which content can be placed, meaning the border box minus the padding and border width. the border box encompasses the content, padding, and border. see the box model for further explanation. methods none. examples the following snippet is taken from the resize-observer-text.html (see source) example. this uses a simple feature detection test to see if the browser supports the newer contentboxsize property — if so, it uses that to get the sizin...
SVGAngle - Web APIs
Web › API › SVGAngle
interface is used to represent a value that can be an <angle> or <number> value. an svgangle reflected through the animval attribute is always read only. an svgangle object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown. an svgangle object can be associated with a particular element. the associated element is used to determine which element's content attribute to update if the object reflects an attribute. unless otherwise described, an svgangle object is not associated with any element. every svgangle object operates in one of two modes: reflect the base value of a reflected animatable attribute (being exposed through the baseval member of an svganimatedangle), be detached, which is the case for svgangle object...
SVGGeometryElement.isPointInFill() - Web APIs
the point argument is interpreted as a point in the local coordiante system of the element. syntax boolean someelement.ispointinfill(dompointinit point); parameters point a dompointinit interpreted as a point in the local coordiante system of the element. return value a boolean indicating whether the given point is within the fill or not. ...
SVGGeometryElement.isPointInStroke() - Web APIs
the point argument is interpreted as a point in the local coordiante system of the element. syntax boolean someelement.ispointinstroke(dompointinit point); parameters point a dompointinit interpreted as a point in the local coordinate system of the element. return value a boolean indicating whether the given point is within the stroke or not. ...
getBBox() - Web APIs
the coordinates returned are with respect to the current svg space (after the application of all geometry attributes on all the elements contained in the target element). note: getbbox() must return the actual bounding box at the time the method was called—even in case the element has not yet been rendered. it also does not account for any transformation applied to the element or its parents. ...
SVGMatrix - Web APIs
Web › API › SVGMatrix
-uniform scale transformation on the current matrix and returns the resulting matrix as svgmatrix. svgmatrix.rotate() post-multiplies a rotation transformation on the current matrix and returns the resulting matrix as svgmatrix. svgmatrix.rotatefromvector() post-multiplies a rotation transformation on the current matrix and returns the resulting matrix as svgmatrix. the rotation angle is determined by taking (+/-) atan(y/x). the direction of the vector (x, y) determines whether the positive or negative angle value is used. svgmatrix.flipx() post-multiplies the transformation [-1 0 0 1 0 0] and returns the resulting matrix as svgmatrix. svgmatrix.flipy() post-multiplies the transformation [1 0 0 -1 0 0] and returns the resulting matrix as svgmatrix. svgmatrix.skewx() post-multiplies ...
Screen.availHeight - Web APIs
css pixels tall the screen's available space is. this can be no larger than the value of window.screen.height, and will be less if the device or user agent reserves any vertical space for itself. for instance, on a mac whose dock is located at the bottom of screen (which is the default), the value of availheight is approximately the value of height (the total height of the screen in css pixels) minus the heights of the dock and menu bar, as seen in the diagram below. 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. in the main window, when it's time to open the panels, code like the f...
Screen.height - Web APIs
Web › API › Screen › height
een in pixels. syntax var height = window.screen.height example if (window.screen.availheight !== window.screen.height) { // something is occupying some screen real estate! } notes note that not all of the height given by this property may be available to the window itself. widgets such as taskbars or other special application windows that integrate with the os (e.g., the spinner player minimized to act like an additional toolbar on windows) may reduce the amount of space available to browser windows and other applications. internet explorer will take into account the zoom setting when reporting the screen height. it will only return the real height of the screen if the zoom is set to 100%. specification specification status comment css object model (c...
Screen - Web APIs
Web › API › Screen
the screen interface represents a screen, usually the one on which the current window is being rendered, and is obtained using window.screen. note that browsers determine which screen to report as current by detecting which screen has the center of the browser window. properties screen.availtop specifies the y-coordinate of the first pixel that is not allocated to permanent or semipermanent user interface features. screen.availleft returns the first available pixel available from the left side of the screen. screen.availheight specifies the height of the screen, in pixels, minus permanent or semipermanent user interface features displayed by the operating system, such as the taskbar on windows. screen.availwidth returns the amount of horizontal space in pixels available to th...
ScriptProcessorNode - Web APIs
nd was replaced by audioworklet (see audioworkletnode). the scriptprocessornode interface is an audionode audio-processing module that is linked to two buffers, one containing the input audio data, one containing the processed output audio data. an event, implementing the audioprocessingevent interface, is sent to the object each time the input buffer contains new data, and the event handler terminates when it has filled the output buffer with data. the size of the input and output buffer are defined at the creation time, when the audiocontext.createscriptprocessor() method is called (both are defined by audiocontext.createscriptprocessor()'s buffersize parameter). the buffer size must be a power of 2 between 256 and 16384, that is 256, 512, 1024, 2048, 4096, 8192 or 16384. small numbers...
SecurityPolicyViolationEvent.SecurityPolicyViolationEvent() - Web APIs
onevent object instance. syntax let spvevt = new securitypolicyviolationevent(type, eventinitdict); properties type a domstring representing the type of security policy violation that occurred. eventinitdict optional a dictionary object containing information about the properties of the securitypolicyviolationevent to be constructed. this can include the following properties, but bear in mind that if you do include an eventinitdict, certain properties must be included (marked below with required): blockeduri: the blockeduri of the securitypolicyviolationevent. if not included, the default value is "". columnnumber: the columnnumber of the securitypolicyviolationevent. if not included, the default value is 0. disposition: the disposition of the securitypolicyviolationevent (re...
Selection.isCollapsed - Web APIs
the selection.iscollapsed read-only property returns a boolean which indicates whether or not there is currently any text selected. no text is selected when the selection's start and end points are at the same position in the content. keep in mind that a collapsed selection may still have one (or more, in gecko) ranges, so selection.rangecount may not be zero. in that scenario, calling a selection object's getrangeat() method may return a range object which is collapsed. syntax bool = sel.iscollapsed specifications specification status comment selection apithe definition of 'selection.iscollapsed' in that specification. working draft current ...
Selection.modify() - Web APIs
Web › API › Selection › modify
ying a selection. click somewhere inside the example (optionally selecting some text), and then click the button to expand the selection. html <p>click somewhere in this example. then click the button below to expand the selection. watch what happens!</p> <p>et harum quidem rerum facilis est et expedita distinctio. ...
Selection.setBaseAndExtent() - Web APIs
, and any content located between them. syntax sel.setbaseandextent(anchornode,anchoroffset,focusnode,focusoffset) parameters anchornode the node at the start of the selection. anchoroffset the number of child nodes from the start of the anchor node that should be excluded from the selection. so for example, if the value is 0 the whole node is included. if the value is 1, the whole node minus the first child node is included. and so on. focusnode the node at the end of the selection. focusoffset the number of child nodes from the start of the focus node that should be included in the selection. so for example, if the value is 0 the whole node is excluded. if the value is 1, the first child node is included. and so on. note: if the focus position appears before the anchor posi...
Selection - Web APIs
Web › API › Selection
a user may make a selection from left to right (in document order) or right to left (reverse of document order). the anchor is where the user began the selection and the focus is where the user ends the selection. if you make a selection with a desktop mouse, the anchor is placed where you pressed the mouse button, and the focus is placed where you released the mouse button. ...
Server-sent events - Web APIs
concepts and usage to learn how to use server-sent events, see our article using server-sent events. ...
ServiceWorker - Web APIs
the following values: installing, installed, activating, activated, or redundant. event handlers serviceworker.onstatechange read only an eventlistener property called whenever an event of type statechange is fired; it is basically fired anytime the serviceworker.state changes. methods the serviceworker interface inherits methods from its parent, worker, with the exception of worker.terminate — this should not be accessible from service workers. examples this code snippet is from the service worker registration-events sample (live demo). the code listens for any change in the serviceworker.state and returns its value. if ('serviceworker' in navigator) { navigator.serviceworker.register('service-worker.js', { scope: './' }).then(function (registration) { ...
ServiceWorkerContainer.onmessage - Web APIs
note: messages received from service worker contexts (e.g. as the event object of onmessage) are represented by messageevent objects in modern browsers, for consistency with other web messaging features. (they used to be represented by serviceworkermessageevent objects, which have now been deprecated.) syntax serviceworkercontainer.onmessage = function(messageevent) { ... ...
ServiceWorkerGlobalScope: message event - Web APIs
controlled pages can use the serviceworker.postmessage() method to send messages to service workers. the service worker can optionally send a response back via the client.postmessage(), corresponding to the controlled page. bubbles no cancelable no interface extendablemessageevent event handler property onmessage examples in the below example a page gets a handle to the serviceworker object via serviceworkerregistration.active, and then calls its postmessage() function. ...
ServiceWorkerGlobalScope.onmessage - Web APIs
note: service workers define the extendable event to allow extending the lifetime of the event. for the message event, service workers use the extendablemessageevent interface which extends the extendableevent interface. note: messages received from service worker contexts (e.g. as the event object of onmessage) are represented by messageevent objects in modern browsers, for consistency with other web messaging features. ...
ServiceWorkerRegistration.showNotification() - Web APIs
ns and audible alerts when reusing a tag value. if options’s renotify is true and options’s tag is the empty string a typeerror will be thrown. the default is false. requireinteraction: indicates that on devices with sufficiently large screens, a notification should remain active until the user clicks or dismisses it. if this value is absent or false, the desktop version of chrome will auto-minimize notifications after approximately twenty seconds. the default value is false. silent: when set indicates that no sounds or vibrations should be made. if options’s silent is true and options’s vibrate is present a typeerror exception will be thrown. the default value is false. tag: an id for a given notification that allows you to find, replace, or remove the notification using a scri...
Using Service Workers - Web APIs
n if the promise is rejected. this registers a service worker, which runs in a worker context, and therefore has no dom access. you then run code in the service worker outside of your normal pages to control their loading. a single service worker can control many pages. each time a page within your scope is loaded, the service worker is installed against that page and operates on it. bear in mind therefore that you need to be careful with global variables in the service worker script: each page doesn’t get its own unique worker. note: your service worker functions like a proxy server, allowing you to modify requests and responses, replace them with items from its own cache, and more. note: one great thing about service workers is that if you use feature detection like we’ve show...
Service Worker API - Web APIs
nstallation, it is activated. if there is an existing service worker available, the new version is installed in the background, but not yet activated — at this point it is called the worker in waiting. it is only activated when there are no longer any pages loaded that are still using the old service worker. as soon as there are no more pages to be loaded, the new service worker activates (becoming the active worker). activation can happen sooner using serviceworkerglobalscope.skipwaiting() and existing pages can be claimed by the active worker using clients.claim(). you can listen for the installevent; a standard action is to prepare your service worker for usage when this fires, for example by creating a cache using the built in storage api, and placing assets inside it that you'll want...
SharedWorkerGlobalScope.close() - Web APIs
ffectively closing this particular scope. syntax self.close(); example if you want to close your worker instance from inside the worker itself, you can call the following: close(); close() and self.close() are effectively equivalent — both represent close() being called from inside the worker's inner scope. note: there is also a way to stop the worker from the main thread: the worker.terminate method. specifications specification status comment html living standardthe definition of 'close()' in that specification. living standard ...
SharedWorkerGlobalScope: connect event - Web APIs
orkerglobalscope.onconnect examples this example shows a shared worker file — when a connection to the worker occurs from a main thread via a messageport, the onconnect event handler fires. the event object is a messageevent. 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 ...
SharedWorkerGlobalScope.onconnect - Web APIs
onconnect = function() { ... }; examples this example shows a shared worker file — when a connection to the worker occurs from a main thread via a messageport, the onconnect event handler fires. the event object is a messageevent. 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. 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 worke...
SharedWorkerGlobalScope - Web APIs
rglobalscope.close() discards any tasks queued in the sharedworkerglobalscope's event loop, effectively closing this particular scope. inherited from workerglobalscope workerglobalscope.close() discards any tasks queued in the workerglobalscope's event loop, effectively closing this particular scope. workerglobalscope.dump() allows you to write a message to stdout — i.e. in your terminal. this is the same as firefox's window.dump, but for workers. workerglobalscope.importscripts() imports one or more scripts into the worker's scope. you can specify as many as you'd like, separated by commas. 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. windowbase...
SourceBuffer.abort() - Web APIs
ewhat confusing — consider for example step 1 of reset parser state. the mse api is fully asynchronous, but this step seems to suggest a synchronous (blocking) operation, which doesn't make sense. saying that, current implementations can be useful in certain situations, when you want to stop the current append (or whatever) operation occuring on a sourcebuffer, and then immediately start performing operations on it again. for example, consider this code: sourcebuffer.addeventlistener('updateend', function (_) { ... }); sourcebuffer.appendbuffer(buf); let's say that after the call to appendbuffer but before the updateend event fires (i.e. a buffer is being appended but the operation has not yet completed) a user "scrubs" the video seeking to a new point in time. in this case you would...
SourceBuffer.mode - Web APIs
Web › API › SourceBuffer › mode
the mode property of the sourcebuffer interface controls whether media segments can be appended to the sourcebuffer in any order, or in a strict sequence. the two available values are: segments: the media segment timestamps determine the order in which the segments are played. the segments can be appended to the sourcebuffer in any order. sequence: the order in which the segments are appended to the sourcebuffer determines the order in which they are played. segment timestamps are generated automatically for the segments that observe this order. the mode value is initially set when the sourcebuffer is created using mediasource.addsourcebuffer(). if timestamps already exist for the media segments, then the value will be set to segments; if they don't, then the value will be s...
SpeechRecognition.abort() - Web APIs
syntax myspeechrecognition.abort(); returns void. parameters none. ...
SpeechRecognition.onstart - Web APIs
the onstart property of the speechrecognition interface represents an event handler that will run when the speech recognition service has begun listening to incoming audio with intent to recognize grammars associated with the current speechrecognition (when the start event fires.) syntax myspeechrecognition.onstart = function() { ... }; examples recognition.onstart = function() { console.log('speech recognition service has started'); } specifications specification status comment web speech apithe definition of 'onstart' in that specification. draft ...
SpeechRecognition.start() - Web APIs
syntax myspeechrecognition.start(); parameters none. return value void. ...
SpeechRecognition: start event - Web APIs
the start event of the web speech api speechrecognition object is fired when the speech recognition service has begun listening to incoming audio with intent to recognize grammars associated with the current speechrecognition. bubbles no cancelable no interface event event handler property onstart examples you can use the start event in an addeventlistener method: var recognition = new webkitspeechrecognition() || new speechrecognition(); recognition.addeventlistener('start', function() { console.log('speech recognition service has started'); }); or use the onstart event handler property: recognition.onstart = function() { console.log('speech recognition service has started'); } specifications specificatio...
SpeechRecognition.stop() - Web APIs
syntax myspeechrecognition.stop(); returns void. parameters none. ...
SpeechRecognitionError.error - Web APIs
the possible error types are: no-speech no speech was detected. ...
SpeechRecognitionErrorEvent.error - Web APIs
the possible error types are: no-speech no speech was detected. aborted speech input was aborted in some manner, perhaps by some user-agent-specific behavior like a button the user can press to cancel speech input. audio-capture audio capture failed. network network communication required for completing the recognition failed. ...
SpeechRecognitionEvent.interpretation - Web APIs
if no semantic interpretation has been returned by the speec recognition system, null will be returned. ...
SpeechSynthesis.onvoiceschanged - Web APIs
syntax speechsynthesisinstance.onvoiceschanged = function() { ... }; examples this could be used to populate a list of voices that the user can choose between when the event fires (see our speak easy synthesis demo.) note that firefox doesn't support it at present, and will just return a list...
SpeechSynthesisUtterance.pitch - Web APIs
gets and sets the pitch at which the utterance will be spoken at. if unset, a default value of 1 will be used. syntax // default 1 speechsynthesisutteranceinstance.pitch = 1.5; value a float representing the pitch value. it can range between 0 (lowest) and 2 (highest), with 1 being the default pitch for the current platform or voice. some speech synthesis engines or voices may constrain the minimum and maximum rates further. if ssml is used, this value will be overridden by prosody tags in the markup. examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ... inputform.onsubmit = function(event) { event.preven...
SpeechSynthesisUtterance.rate - Web APIs
e.rate = 1.5; value a float representing the rate value. it can range between 0.1 (lowest) and 10 (highest), with 1 being the default pitch for the current platform or voice, which should correspond to a normal speaking rate. other values act as a percentage relative to this, so for example 2 is twice as fast, 0.5 is half as fast, etc. some speech synthesis engines or voices may constrain the minimum and maximum rates further. if ssml is used, this value will be overridden by prosody tags in the markup. examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ... inputform.onsubmit = function(event) { event.preven...
StereoPannerNode - Web APIs
the pan property takes a unitless value between -1 (full left pan) and 1 (full right pan). this interface was introduced as a much simpler way to apply a simple panning effect than having to use a full pannernode. ...
StorageEstimate.quota - Web APIs
the storageestimate dictionary's quota property is a conservative approximation of how much storage is allotted to the origin or web app that called storagemanager.estimate(); there may be more space available, but there will not be less. 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. syntax quota = storageestimate.quota; value a numeric value specifying an approximation of the total amount of storage space available for use by the application. example in this example, we obtain the usage estimates and present the percentage of storage capacity currently used to the user. html content <label> you’re currently using about <output id="percent"> <...
StyleSheet.disabled - Web APIs
a style sheet may be disabled by manually setting this property to true or if it's an inactive alternative style sheet. note that disabled == false does not guarantee the style sheet is applied (it could be removed from the document, for instance). syntax bool = stylesheet.disabled example // if the stylesheet is disabled... if (stylesheet.disabled) { // ... apply styles in-line. } specification specification status comment css object model (cssom)the definition of 'stylesheet.disabled' in that specification. ...
SubmitEvent.submitter - Web APIs
t> element whose type or a <button> whose type is submit, it could be some other element which has initiated a submission process. if the submission was not triggered by a button of some kind, the value of submitter is null. examples in this example, a shopping cart may have an assortment of different submit buttons depending on factors such as the user's settings, the shop's settings, and any minimum or maximum shopping card totals established by the payment processors. each of the submit elements' id is used to identify which payment processor the button corresponds to. let form = document.queryselector("form"); form.addeventlistener("submit", (event) => { let submitter = event.submitter; let handler = submitter.id; if (handler) { processorder(form, handler); } else { s...
SubmitEvent - Web APIs
t object which identifies the button or other element which was invoked to trigger the form being submitted. methods while submitevent offers no methods of its own, it inherits any specified by its parent interface, event. examples in this example, a shopping cart may have an assortment of different submit buttons depending on factors such as the user's settings, the shop's settings, and any minimum or maximum shopping card totals established by the payment processors. each of the submit elements' id is used to identify which payment processor the button corresponds to. let form = document.queryselector("form"); form.addeventlistener("submit", (event) => { let submitter = event.submitter; let handler = submitter.id; if (handler) { processorder(form, handler); } else { s...
SubtleCrypto.encrypt() - Web APIs
ciphertext has not been modified by an attacker. authentication helps protect against chosen-ciphertext attacks, in which an attacker can ask the system to decrypt arbitrary messages, and use the result to deduce information about the secret key. while it's possible to add authentication to ctr and cbc modes, they do not provide it by default and when implementing it manually one can easily make minor, but serious mistakes. gcm does provide built-in authentication, and for this reason it's often recommended over the other two aes modes. rsa-oaep the rsa-oaep public-key encryption system is specified in rfc 3447. aes-ctr this represents aes in counter mode, as specified in nist sp800-38a. aes-cbc this represents aes in cipher block chaining mode, as specified in nist sp800-38a. aes-gcm...
SubtleCrypto - Web APIs
the subtlecrypto interface of the web crypto api provides a number of low-level cryptographic functions. access to the features of subtlecrypto is obtained through the subtle property of the crypto object you get from window.crypto. warning: this api provides a number of low-level cryptographic primitives. it's very easy to misuse them, and the pitfalls involved can be very subtle. even assuming you use the basic cryptographic functions correctly, secure key management and overall security system design are extremely hard to get right, and are generally the domain of specialist security experts. errors in security system design and implementation can make the security of the system completely ineffective. if you're not sure you know what you are doing, you probably shouldn't be using ...
TextEncoder - Web APIs
ally more performant than the older encode() method. polyfill the below polyfill is compliant with the standard and therefore only supports utf-8. it is designed to work in ie5 "out of the box". however, in ie5-ie9, it will return a regular array instead of a typedarray. in those cases a polyfill might be impractical for large strings. finally, note that you should run the below code through a minifier (especially closure compiler) to turn sequences like 0x1e << 3 into 0xf0. these sequences are not already precomputed because they serve to aesthetically illustrate how the polyfill works. if (typeof textencoder === "undefined") { textencoder=function textencoder(){}; textencoder.prototype.encode = function encode(str) { "use strict"; var len = str.length, respos = -...
TextTrack.mode - Web APIs
Web › API › TextTrack › mode
safari additionally requires the default boolean attribute to be set to true when implementing your own video player controls in order for the subtitles cues to be shown. syntax var mode = texttrack.mode; texttrack.mode = "disabled" | "hidden" | "showing"; value a domstring which indicates the track's current mode. ...
msManipulationViewsEnabled - Web APIs
is feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the msmanipulationviewsenabled read-only property returns true if manipulation features are support available, such as touch panning and zooming using css rules. this proprietary property is specific to internet explorer and microsoft edge. 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 ...
Touch.force - Web APIs
Web › API › Touch › force
ouches list and logs the force value of each touch point but the code could invoke different processing depending on the value. someelement.addeventlistener('touchstart', function(e) { // iterate through the list of touch points and log each touch // point's force. for (var i=0; i < e.targettouches.length; i++) { // add code to "switch" based on the force value. for example // minimum pressure vs. maximum pressure could result in // different handling of the user's input. console.log("targettouches[" + i + "].force = " + e.targettouches[i].force); } }, false); specifications specification status comment touch events – level 2 draft initial definition. ...
TouchEvent.touches - Web APIs
their target element was at touchstart time. example this example illustrates the touchevent object's touchevent.touches property. the touchevent.touches property is a touchlist object and containing a list of touch objects for every point of contact currently touching the surface. in following code snippet, the touchstart event handler checks the length of the touchevent.touches list to determine the number of touch points that were activated and then invokes different handlers depending on the number of touch points. someelement.addeventlistener('touchstart', function(e) { // invoke the appropriate handler depending on the // number of touch points. switch (e.touches.length) { case 1: handle_one_touch(e); break; case 2: handle_two_touches(e); break; case 3: hand...
TrackEvent - Web APIs
specifications specification status comment html living standardthe definition of 'trackevent' in that specification. living standard initial definition. html5the definition of 'track...
TreeWalker.filter - Web APIs
Web › API › TreeWalker › filter
the treewalker.filter read-only property returns a nodefilter that is the filtering object associated with the treewalker. when creating the treewalker, the filter object is passed in as the third parameter, and its method nodefilter.acceptnode() is called on every single node to determine whether or not to accept it. syntax nodefilter = treewalker.filter; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); nodefilter = treewalker.filter; // document.body in this case specifications specification status comment domthe definition of 'treewalker.filter' in that specification. living standard no change from document object m...
TreeWalker - Web APIs
treewalker.expandentityreferences read only is a boolean indicating, when discarding an entityreference its whole sub-tree must be discarded at the same time. treewalker.currentnode is the node on which the treewalker is currently pointing at. methods this interface doesn't inherit any method. note: in the context of a treewalker, a node is visible if it exists in the logical view determined by the whattoshow and filter parameter arguments. (whether or not the node is visible on the screen is irrelevant.) treewalker.parentnode() moves the current node to the first visible ancestor node in the document order, and returns the found node. it also moves the current node to this one. if no such node exists, or if it is before that the root node defined at the object construction, r...
ULongRange - Web APIs
the ulongrange dictionary is used to define a range of permitted integer values for a property, with either or both a maximum and minimum value specified. the constrainulongrange dictionary is based on this, augmenting it to support exact and ideal values as well. properties max a numeric value in the range of signed 32-bit integers, specifying the largest permissible value of the property it describes. min a numeric value in the range of signed 32-bit integers, specifying the smallest permissible value of the property it describes. the specified min and/or and max values are required. if no match can be found that is within the given range, an error will occur. specifications specification status comment media capture and streamsthe definition of 'ulongran...
USBDevice.clearHalt() - Web APIs
see the for details. syntax var promise = usbdevice.clearhalt(direction, endpointnumber) parameters direction indicates whether the devices input or output should be cleared. valid values are 'in' or 'out'. ...
USBDevice.configuration - Web APIs
the configuration read only property of the usbdevice interface returns a usbconfiguration object for the currently selected interface for a paired usb device. syntax var usbconfiguration = usbdevice.configuration value a usbconfiguration object. example the following example uses this property to test for the existence of a usbconfiguration property to select a configuration before claiming an interface. async function connectdevice(usbdevice) { await usbdevice.open(); if (usbdevice.configuration === null) await usbdevice.selectconfiguration(1); await usbdevice.claiminterface(0); } specifications specification status comment webusbthe definition of 'configuration' in that specification. draft initial definition. ...
USBDevice.usbVersionMajor - Web APIs
the usbversionmajor read only property of the usbdevice interface is one of three properties that declare the usb protocol version supported by the device. the other two properties are usbdevice.usbversionminor and usbdevice.usbversionsubminor. syntax var serialnumber = usbdevice.usbversionmajor value the last of three properties that declare the usb protocol version supported by the device. specifications specification status comment webusbthe definition of 'usbversionmajor' in that specification. draft initial definition. ...
USBInterface - Web APIs
evice.selectalternateinterface() with any other value found in alternates. usbinterface.alternatesread only returns an array containing instances of the usbalternateinterface interface describing each of the alternative configurations possible for this interface. usbinterface.claimedread only returns whether or not this interface has been claimed by the current page by calling usbdevice.claiminterface(). specifications specification status comment webusbthe definition of 'usbinterface' in that specification. draft initial definition. ...
VTTCue() - Web APIs
Web › API › VTTCue › VTTCue
creates and returns a new vttcue object. syntax vttcue = new vttcue(starttime, endtime, text); parameters starttime this is a double representing the initial text track cue start time. this is the time, given in seconds and fractions of a second, denoting the beginning of the range of the media data to which this cue applies. for example, if a cue is to be visible from 50 seconds to a one minute, five and a half seconds in the media's playback, starttime will be 50.0. endtime this is a double representing the ending time for this text track cue. this is the time at which the cue should stop being presented to the user, given in seconds and fractions thereof. given the example cue mentioned under starttime, the value of endtime would be 65.5. text a domstring providing the text tha...
VTTCue - Web APIs
Web › API › VTTCue
e.snaptolines. vttcue.linealign returns an enum representing the alignment of the vttcue.line. vttcue.position returns the indentation of the cue within the line. this can be the string auto or a number representing the percentage of the vttcue.region, or the video size if vttcue.region is null. vttcue.positionalign returns an enum representing the alignment of the cue. this is used to determine what the vttcue.position is anchored to. the default is auto. vttcue.size returns a double representing the size of the cue, as a percentage of the video size. vttcue.textalign returns an enum representing the alignment of all the lines of text within the cue box. vttcue.text returns a domstring with the contents of the cue. methods getcueashtml() returns the cue text as a documentfr...
ValidityState.patternMismatch - Web APIs
contain characters that aren't digits, patternmismatch will be true. when true, the element matches the :invalid css pseudo-classes. input:invalid { border: red solid 3px; } note, in this case, we get a patternmismatch not a validitystate.toolong or validitystate.tooshort if the values are too long or too short because it is the pattern that is dictating the length of the value. had we used minlength and maxlength attributes instead, we may have seen validitystate.toolong or validitystate.tooshort being true. note: the email input type requires, at minimum, a match of x@y and the url type requires, at minimum, a match to x:, with no pattern attribute present. when invalid, the validitystate.typemismatch will be true, if there is no pattern attribute (or if the pattern attribute is not...
ValidityState.rangeOverflow - Web APIs
ing been edited by the user, does not conform to the constraints set by the element's max attribute. if the field is numeric in nature, including the date, month, week, time, datetime-local, number and range types and a max value is set, if the value don't doesn't conform to the constraints set by the max value, the rangeoverflow property will be true. given the following: <input type="number" min="20" max="40" step="2"/> if value > 40, rangeoverflow will be true. when true, the element matches the :invalid and :out-of-range css pseudo-classes. specifications specification status comment html living standardthe definition of 'validitystate.rangeoverflow' in that specification. living standard html 5.1the definition of 'validitystate.rangeoverflow'...
ValidityState.rangeUnderflow - Web APIs
the read-only rangeunderflow property of a validitystate object indicates if the value of an <input>, after having been edited by the user, does not conform to the constraints set by the element's min attribute. if the field is numeric in nature, including the date, month, week, time, datetime-local, number and range types and a min value is set, if the value don't doesn't conform to the constraints set by the min value, the rangeunderflow property will be true. given the following: <input type="number" min="20" max="40" step="2"/> if value < 20, rangeunderflow will be true. when true, the element matches the :invalid and :out-of-range css pseudo-classes. specifications specification status comment html living standardthe definition of 'validitystate.rang...
ValidityState.stepMismatch - Web APIs
perty of a validitystate object indicates if the value of an <input>, after having been edited by the user, does not conform to the constraints set by the element's step attribute. if the field is numeric in nature, including the date, month, week, time, datetime-local, number and range types and the step value is not any, if the value don't doesn't conform to the constraints set by the step and min values, then stepmismatch will be true. if the remainder of the form control's value less the min value, divided by the step value (which defaults to 1 if ommitted) is not zero, there is a mismatch. given the following: <input type="number" min="20" max="40" step="2"/> if (value - min) / 2 != 0, stepmismatch will be true. if true, the element matches the :invalid and :out-of-range css pseudo...
VideoConfiguration - Web APIs
properties the videoconfiguration dictionary is made up of five video properties, including: contenttype: a valid video mime type. see our web video codec guide for types which may be supported. width: the width of the video. height: the height of the video. ...
VideoPlaybackQuality.creationTime - Web APIs
e number of milliseconds since the browsing context was created this quality sample was recorded. syntax value = videoplaybackquality.creationtime; value a domhighrestimestamp object which indicates the number of milliseconds that elapased between the time the browsing context was created and the time at which this sample of the video quality was obtained. for details on how the time is determined, see performance.now(). example this example calls getvideoplaybackquality() to obtain a videoplaybackquality object, then determines what percentage of frames have been lost by either corruption or being dropped. if that exceeds 10% (0.1), a function called lostframesthresholdexceeded() is called to, perhaps, update a quality indicator to show an increase in frame loss. var videoelem = docu...
VideoPlaybackQuality.droppedVideoFrames - Web APIs
ber of video frames which have been dropped rather than being displayed since the last time the media was loaded into the htmlvideoelement. syntax value = videoplaybackquality.droppedvideoframes; value an unsigned 64-bit value indicating the number of frames that have been dropped since the last time the media in the <video> element was loaded or reloaded. this information can be used to determine whether or not to downgrade the video stream to avoid dropping frames. frames are typically dropped either before or after decoding them, when it's determined that it will not be possible to draw them to the screen at the correct time. example this example calls getvideoplaybackquality() to obtain a videoplaybackquality object, then determines what percentage of frames have been dropped. th...
VideoPlaybackQuality.totalVideoFrames - Web APIs
deoframes; value the total number of frames that the <video> element has displayed or dropped since the media was loaded into it. essentially, this is the number of frames the element would have presented had no problems occurred. this value is reset when the media is reloaded or replaced. example this example calls getvideoplaybackquality() to obtain a videoplaybackquality object, then determines what percentage of frames have been lost by either corruption or being dropped. if that exceeds 10% (0.1), a function called lostframesthresholdexceeded() is called to, perhaps, update a quality indicator to show an increase in frame loss. var videoelem = document.getelementbyid("my_vid"); var quality = videoelem.getvideoplaybackquality(); if ((quality.corruptedvideoframes + quality.droppedvi...
VideoPlaybackQuality - Web APIs
properties the videoplaybackquality interface doesn't inherit properties from any other interfaces. creationtime read only a domhighrestimestamp containing the time in miliseconds between the start of the navigation and the creation of the object. droppedvideoframes read only an unsigned long giving the number of video frames dropped since the creation of the associated htmlvideoelement. ...
VideoTrack.kind - Web APIs
Web › API › VideoTrack › kind
see video track kind strings for a list of the kinds available for video tracks. syntax var trackkind = videotrack.kind; value a domstring specifying the type of content the media represents. the string is one of those found in video track kind strings below. ...
VisualViewport - Web APIs
. scroll fired when the visual viewport is scrolled. also available via the visualviewport.onscroll property. examples hiding an overlaid box on zoom this example, taken from the visual viewport readme, shows how to write a simple bit of code that will hide an overlaid box (which might contain an advert, say) when the user zooms in. this is a nice way to improve the user experience when zooming in on pages. a live sample is also available. var bottombar = document.getelementbyid('bottombar'); var viewport = window.visualviewport; function resizehandler() { if (viewport.scale > 1.3) bottombar.style.display = "none"; else bottombar.style.display = "block"; } window.visualviewport.addeventlistener('resize', resizehandler); simulating position: device-fixed this examp...
WEBGL_compressed_texture_s3tc - Web APIs
recommendation initial definition. ...
WEBGL_compressed_texture_s3tc_srgb - Web APIs
image in an srgba image format. examples var ext = gl.getextension('webgl_compressed_texture_s3tc_srgb'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.compressedteximage2d(gl.texture_2d, 0, ext.compressed_srgb_s3tc_dxt1_ext, 512, 512, 0, texturedata); gl.texparameteri(gl.texture_2d, gl.texture_mag_filter, gl.linear); gl.texparameteri(gl.texture_2d, gl.texture_min_filter, gl.linear); specifications specification status comment webgl_compressed_texture_s3tc_srgbthe definition of 'webgl_compressed_texture_s3tc_srgb' in that specification. recommendation initial definition. ...
WakeLock - Web APIs
Web › API › WakeLock
the system wake lock is exposed through the global navigator.wakelock property. methods request requests a wakelocksentinel object, which returns a promise that resolves with a wakelocksentinel object. examples the following asynchronous function requests a wakelocksentinel object. the wakelock.request method is wrapped in a try...catch statement to account for if the browser refuses the request for any reason. ...
WakeLockSentinel.type - Web APIs
the read-only type property of the wakelocksentinel interface returns a string representation of the currently acquired wakelocksentinel type. syntax var type = wakelocksentinel.type; value a string representation of the currently acquired wake lock type. type read only return values are: 'screen': a screen wake lock. prevents devices from dimming or locking the screen. examples this example shows an asynchronous function that acquires a wakelocksentinel, then logs the type to the console. const requestwakelock = async () => { wakelock = await navigator.wakelock.request('screen'); console.log(wakelock.type); // logs 'screen' }; requestwakelock(); specifications specification status comment screen wake lock apithe definition...
WakeLockSentinel - Web APIs
turns on a power save mode. releasing all wakelocksentinel instances of a given wake lock type will cause the underlying platform wake lock to be released. properties this interface provides the following properties. type read only returns a string representation of the currently acquired wakelocksentinel type. return values are: 'screen': a screen wake lock. prevents devices from dimming or locking the screen. event handlers onrelease fired when the release() method is called or the wake lock is released by the user agent. methods release() releases the wakelocksentinel, returning a promise that is resolved once the sentinel has been successfully released. examples in this example we create an asynchronous function which requests a wakelocksentinel. once acqui...
WaveShaperNode.WaveShaperNode() - Web APIs
a new waveshapernode object which is an audionode that represents a non-linear distorter. syntax var waveshapernode = new waveshapernode(context, options) parameters inherits parameters from the audionodeoptions dictionary. context a reference to an audiocontext. options optional options are as follows: curve: the shaping curve used for the waveshaping effect. the input signal is nominally within the range [-1;1]. oversample: specifies what type of oversampling (if any) should be used when applying the shaping curve. valid values are 'none', '2x', or '4x'. the default is 'none'. return value a new waveshapernode object instance. specifications specification status comment web audio apithe definition of 'waveshapernode()' in that specification.
WebGL2RenderingContext.drawRangeElements() - Web APIs
ues are: gl.points: draws a single dot. gl.line_strip: draws a straight line to the next vertex. gl.line_loop: draws a straight line to the next vertex, and connects the last vertex back to the first. gl.lines: draws a line between a pair of vertices. gl.triangle_strip gl.triangle_fan gl.triangles: draws a triangle for a group of three vertices. start a gluint specifying the minimum array index contained in offset. end a gluint specifying the maximum array index contained in offset. count a glsizei specifying the number of elements to be rendered. type a glenum specifying the type of the values in the element array buffer. possible values are: gl.unsigned_byte gl.unsigned_short gl.unsigned_int offset a glintptr specifying an offset in the element arra...
WebGL2RenderingContext.getActiveUniformBlockParameter() - Web APIs
parameters program a webglprogram containing the active uniform block. uniformblockindex a gluint specifying the index of the active uniform block within the program. pname a glenum specifying which information to query. possible values: gl.uniform_block_binding: returns a gluint indicating the uniform buffer binding point. gl.uniform_block_data_size: returns a gluint indicating the minimum total buffer object size. gl.uniform_block_active_uniforms: returns a gluint indicating the number of active uniforms in the uniform block. gl.uniform_block_active_uniform_indices: returns a uint32array indicating the list of active uniforms in the uniform block. gl.uniform_block_referenced_by_vertex_shader: returns a glboolean indicating whether the uniform block is referenced by the v...
WebGL2RenderingContext.getSamplerParameter() - Web APIs
information to return. possible values: gl.texture_compare_func: returns a glenum indicating the texture comparison function. gl.texture_compare_mode: returns a glenum indicating the texture comparison mode. gl.texture_mag_filter: returns a glenum indicating the texture magnification filter. gl.texture_max_lod: returns a glfloat indicating the maximum level-of-detail value. gl.texture_min_filter: returns a glenum indicating the texture minification filter gl.texture_min_lod: returns a glfloat indicating the minimum level-of-detail value. gl.texture_wrap_r: returns a glenum indicating the texture wrapping function for the texture coordinate r. gl.texture_wrap_s: returns a glenum indicating the texture wrapping function for the texture coordinate s. gl.texture_wrap_t: return...
WebGL2RenderingContext.getUniformBlockIndex() - Web APIs
method of the webgl 2 api retrieves the index of a uniform block within a webglprogram. syntax gluint gl.getuniformblockindex(program, uniformblockname); parameters program a webglprogram containing the uniform block. uniformname a domstring specifying the name of the uniform block to whose index to retrieve. return value a gluint indicating the uniform block index. examples // assuming a shader with the following declaration: // uniform ubodata { // mat4 foo; // } instancename; // use the block name, not the instance name: var blockindex = gl.getuniformblockindex(program, 'ubodata'); specifications specification status comment webgl 2.0the definition of 'getuniformblockindex' in that specification. editor's draft initial definition for webgl...
WebGL2RenderingContext.samplerParameter[if]() - Web APIs
t. pname a glenum specifying which parameter to set. possible values: gl.texture_compare_func: a glenum specifying the texture comparison function. gl.texture_compare_mode: a glenum specifying the texture comparison mode. gl.texture_mag_filter: a glenum specifying the texture magnification filter. gl.texture_max_lod: a glfloat specifying the maximum level-of-detail value. gl.texture_min_filter: a glenum specifying the texture minification filter gl.texture_min_lod: a glfloat specifying the minimum level-of-detail value. gl.texture_wrap_r: a glenum specifying the texture wrapping function for the texture coordinate r. gl.texture_wrap_s: a glenum specifying the texture wrapping function for the texture coordinate s. gl.texture_wrap_t: a glenum specifying the texture wrappi...
WebGL2RenderingContext.texImage3D() - Web APIs
and level n is the nth mipmap reduction level. internalformat a glint specifying the color components in the texture. possible values: gl.alpha: discards the red, green and blue components and reads the alpha component. gl.rgb: discards the alpha components and reads the red, green and blue components. gl.rgba: red, green, blue and alpha components are read from the color buffer. gl.luminance: each color component is a luminance component, alpha is 1.0. gl.luminance_alpha: each component is a luminance/alpha component. gl.r8 gl.r16f gl.r32f gl.r8ui gl.rg8 gl.rg16f gl.rg32f gl.rgui gl.rgb8 gl.srgb8 gl.rgb565 gl.r11f_g11f_b10f gl.rgb9_e5 gl.rgb16f gl.rgb32f gl.rgb8ui gl.rgba8 gl.srgb_aplha8 gl.rgb5_a1 gl.rgba4444 gl.rgba16f gl.rgba32f ...
WebGL2RenderingContext.texSubImage3D() - Web APIs
ture. depth a glsizei specifying the depth of the texture. format a glenum specifying the format of the texel data. possible values: gl.alpha: discards the red, green and blue components and reads the alpha component. gl.rgb: discards the alpha components and reads the red, green and blue components. gl.rgba: red, green, blue and alpha components are read from the color buffer. gl.luminance: each color component is a luminance component, alpha is 1.0. gl.luminance_alpha: each component is a luminance/alpha component. gl.r8 gl.r16f gl.r32f gl.r8ui gl.rg8 gl.rg16f gl.rg32f gl.rgui gl.rgb8 gl.srgb8 gl.rgb565 gl.r11f_g11f_b10f gl.rgb9_e5 gl.rgb16f gl.rgb32f gl.rgb8ui gl.rgba8 gl.srgb_aplha8 gl.rgb5_a1 gl.rgba4444 gl.rgba16f gl.rgba32f ...
WebGL2RenderingContext - Web APIs
bgl2renderingcontext.resumetransformfeedback() resumes a transform feedback operation. uniform buffer objects webgl2renderingcontext.bindbufferbase() binds a given webglbuffer to a given binding point (target) at a given index. webgl2renderingcontext.bindbufferrange() binds a range of a given webglbuffer to a given binding point (target) at a given index. webgl2renderingcontext.getuniformindices() retrieves the indices of a number of uniforms within a webglprogram. webgl2renderingcontext.getactiveuniforms() retrieves information about active uniforms within a webglprogram. webgl2renderingcontext.getuniformblockindex() retrieves the index of a uniform block within a webglprogram. webgl2renderingcontext.getactiveuniformblockparameter() retrieves information about an active ...
WebGLProgram - Web APIs
) function. after attaching the shader programs using attachshader(), you link them into a usable program. this is shown in the code below. var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); if ( !gl.getprogramparameter( program, gl.link_status) ) { var info = gl.getprograminfolog(program); throw 'could not compile webgl program. \n\n' + info; } see webglshader for information on creating the vertexshader and fragmentshader in the above example. 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.attachShader() - Web APIs
a webglprogram. shader a fragment or vertex webglshader. examples the following code attaches pre-existing shaders to a webglprogram. var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); if ( !gl.getprogramparameter( program, gl.link_status) ) { var info = gl.getprograminfolog(program); throw 'could not compile webgl program. \n\n' + info; } specifications specification status comment webgl 1.0the definition of 'attachshader' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glattachshader' in that specification. standard opengl man page. ...
WebGLRenderingContext.compressedTexImage[23]D() - Web APIs
recommendation initial definition for webgl. opengl es 2.0the definition of 'glcompressedteximage2d' in that specification. standard man page of the (similar) opengl es 2.0 api. opengl es 3.0the definition...
WebGLRenderingContext.copyTexImage2D() - Web APIs
nd level n is the nth mipmap reduction level. internalformat a glenum specifying the color components in the texture. possible values: gl.alpha: discards the red, green and blue components and reads the alpha component. gl.rgb: discards the alpha components and reads the red, green and blue components. gl.rgba: red, green, blue and alpha components are read from the color buffer. gl.luminance: each color component is a luminance component, alpha is 1.0. gl.luminance_alpha: each component is a luminance/alpha component. x a glint specifying the x coordinate of the lower left corner where to start copying. y a glint specifying the y coordinate of the lower left corner where to start copying. width a glsizei specifying the width of the texture. height a glsizei specifyi...
WebGLRenderingContext.createProgram() - Web APIs
rtex shader and a fragment shader (both written in glsl). these are then linked into a usable program.. examples creating a webgl program var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); if ( !gl.getprogramparameter( program, gl.link_status) ) { var info = gl.getprograminfolog(program); throw 'could not compile webgl program. \n\n' + info; } see webglshader for information on creating the vertexshader and fragmentshader in the above example. specifications specification status comment webgl 1.0the definition of 'createprogram' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glcr...
WebGLRenderingContext.disable() - Web APIs
enderingcontext.depthfunc(). gl.dither deactivates dithering of color components before they get written to the color buffer. gl.polygon_offset_fill deactivates adding an offset to depth values of polygon's fragments. see webglrenderingcontext.polygonoffset(). gl.sample_alpha_to_coverage deactivates the computation of a temporary coverage value determined by the alpha value. gl.sample_coverage deactivates anding the fragment's coverage with the temporary coverage value. see webglrenderingcontext.samplecoverage(). gl.scissor_test deactivates the scissor test that discards fragments that are outside of the scissor rectangle. see webglrenderingcontext.scissor(). gl.stencil_test deactivates stencil tes...
WebGLRenderingContext.enable() - Web APIs
webglrenderingcontext.depthfunc(). gl.dither activates dithering of color components before they get written to the color buffer. gl.polygon_offset_fill activates adding an offset to depth values of polygon's fragments. see webglrenderingcontext.polygonoffset(). gl.sample_alpha_to_coverage activates the computation of a temporary coverage value determined by the alpha value. gl.sample_coverage activates anding the fragment's coverage with the temporary coverage value. see webglrenderingcontext.samplecoverage(). gl.scissor_test activates the scissor test that discards fragments that are outside of the scissor rectangle. see webglrenderingcontext.scissor(). gl.stencil_test activates stencil testing a...
WebGLRenderingContext.getExtension() - Web APIs
abled, you are able to use the methods, properties or constants that this extension object provides. var canvas = document.getelementbyid('canvas'); gl = canvas.getcontext('webgl'); gl.getextension('webgl_lose_context').losecontext(); webgl extensions extensions for the webgl api are registered in the webgl extension registry. ...
WebGLRenderingContext.getParameter() - Web APIs
gl.pack_skip_pixels glint see pixelstorei. gl.pack_skip_rows glint see pixelstorei. gl.pixel_pack_buffer_binding webglbuffer or null see bindbuffer. gl.pixel_unpack_buffer_binding webglbuffer or null see bindbuffer. gl.rasterizer_discard ...
WebGLRenderingContext.getShaderPrecisionFormat() - Web APIs
cision types aren't recognized. gl.invalid_operation if the shader compiler isn't supported. examples the following code gets the precision format of a gl.vertex_shader with a gl.medium_float precision type. var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.getshaderprecisionformat(gl.vertex_shader, gl.medium_float); // webglshaderprecisionformat { rangemin: 127, rangemax: 127, precision: 23 } specifications specification status comment webgl 1.0the definition of 'getshaderprecisionformat' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glgetshaderprecisionformat' in that specification. standard man page of the (similar) opengl api. ...
WebGLRenderingContext.isEnabled() - Web APIs
updates to the depth buffer. see webglrenderingcontext.depthfunc(). gl.dither dithering of color components before they get written to the color buffer. gl.polygon_offset_fill adding an offset to depth values of polygon's fragments. see webglrenderingcontext.polygonoffset(). gl.sample_alpha_to_coverage computation of a temporary coverage value determined by the alpha value. gl.sample_coverage anding the fragment's coverage with the temporary coverage value. see webglrenderingcontext.samplecoverage(). gl.scissor_test scissor test that discards fragments that are outside of the scissor rectangle. see webglrenderingcontext.scissor(). gl.stencil_test stencil testing and updates to the stencil buffer. ...
WebGLRenderingContext.lineWidth() - Web APIs
the webglrenderingcontext.linewidth() method of the webgl api sets the line width of rasterized lines. the webgl spec, based on the opengl es 2.0/3.0 specs points out that the minimum and maximum width for a line is implementation defined. the maximum minimum width is allowed to be 1.0. the minimum maximum width is also allowed to be 1.0. because of these implementation defined limits it is not recommended to use line widths other than 1.0 since there is no guarantee any user's browser will display any other width. as of january 2017 most implementations of webgl only support a minimum of 1 and a maximum of 1 as the technology they are based on has these same limits. syntax void gl.linewidth(width); parameters width a glfloat specifying the width of rasterized lines. default valu...
WebGLRenderingContext.linkProgram() - Web APIs
d vertex shaders. syntax void gl.linkprogram(program); parameters program the webglprogram to link. return value none. examples var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); if ( !gl.getprogramparameter( program, gl.link_status) ) { var info = gl.getprograminfolog(program); throw new error('could not compile webgl program. \n\n' + info); } specifications specification status comment webgl 1.0the definition of 'linkprogram' in that specification. recommendation initial definition. opengl es 2.0the definition of 'gllinkprogram' in that specification. standard man page of the opengl api. ...
WebGLRenderingContext.makeXRCompatible() - Web APIs
) { 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. these both use the handlestartbuttonclick() function as their event handler. the function determines that the button clicked was the one requesting immersive-vr mode by checking to see if the button has the use-webxr class on it. if the button clicked by the user has that class (and we've confirmed that webxr is available by ensuring that the navigator.xr property exists), we use requestsession() to request a new webxr session and set the usingxr flag to true. if the other button was clicked,...
WebGLRenderingContext.texSubImage2D() - Web APIs
t a glsizei specifying the height of the texture in texels. format a glenum specifying the format of the texel data. possible values: gl.alpha: discards the red, green and blue components and reads the alpha component. gl.rgb: discards the alpha components and reads the red, green and blue components. gl.rgba: red, green, blue and alpha components are read from the color buffer. gl.luminance: each color component is a luminance component, alpha is 1.0. gl.luminance_alpha: each component is a luminance/alpha component. 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_in...
WebGLRenderingContext.validateProgram() - Web APIs
validateprogram(program); parameters program a webglprogram to validate. return value none. examples var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); gl.validateprogram(program); if ( !gl.getprogramparameter( program, gl.link_status) ) { var info = gl.getprograminfolog(program); throw 'could not compile webgl program. \n\n' + info; } gl.useprogram(program); specifications specification status comment webgl 1.0the definition of 'validateprogram' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glvalidateprogram' in that specification. standard man page of the opengl ...
WebGLRenderingContext.vertexAttribPointer() - Web APIs
es are of a uniform shade. for those meshes, it is not necessary to place the same color for each vertex into the array buffer, so you use gl.vertexattrib4fv() to set a constant color. querying current settings you can call gl.getvertexattrib() and gl.getvertexattriboffset() to get the current parameters for an attribute, e.g. the data type or whether the attribute should be normalized. keep in mind that these webgl functions have a slow performance and it is better to store the state inside your javascript application. however, these functions are great for debugging a webgl context without touching the application code. examples this example shows how to send your vertex attributes to the shader program. we use an imaginary data structure where the attributes of each vertex are stored i...
Basic scissoring - Web APIs
canvas.width = canvas.clientwidth; canvas.height = canvas.clientheight; var gl = canvas.getcontext("webgl") || canvas.getcontext("experimental-webgl"); if (!gl) { paragraph.innerhtml = "failed to get webgl context. " + "your browser or device may not support webgl."; return; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); // enab...
Canvas size and WebGL - Web APIs
» this webgl example explores the effect of setting (or not setting) the canvas size to its element size in css pixels, as it appears in the browser window. effect of canvas size on rendering with webgl with scissor() and clear() we can demonstrate how the webgl drawing buffer is affected by the size of the canvas. the size of the first canvas is set to the styled element size, determined by css. this is done by assigning the width and height properties of the canvas to the values of the clientwidth and clientheight properties, respectively. in contrast, no such assignment is done for the second canvas. the internal width and height properties of the canvas remain at default values, which are different than the actual size of the canvas element in the browser window. the effec...
Hello GLSL - Web APIs
" + "error log: " + linkerrlog; return; } initializeattributes(); gl.useprogram(program); gl.drawarrays(gl.points, 0, 1); cleanup(); } var buffer; function initializeattributes() { gl.enablevertexattribarray(0); buffer = gl.createbuffer(); gl.bin...
Raining rectangles - Web APIs
ore; rainingrect = new rectangle(); } } function rectangle () { // keeping a reference to the new rectangle object, rather // than using the confusing this keyword. var rect = this; // we get three random numbers and use them for new rectangle // size and position. for each we use a different number, // because we want horizontal size, vertical size and // position to be determined independently. var randnums = getrandomvector(); rect.size = [ 5 + 120 * randnums[0], 5 + 120 * randnums[1] ]; rect.position = [ randnums[2]*(gl.drawingbufferwidth - rect.size[0]), gl.drawingbufferheight ]; rect.velocity = 1.0 + 6.0*math.random(); rect.color = getrandomvector(); gl.clearcolor(rect.color[0], rect.color[1], rect.color[2], 1.0); function getrandom...
Textures from code - Web APIs
" + "error log: " + linkerrlog; return; } initializeattributes(); gl.useprogram(program); gl.drawarrays(gl.points, 0, 1); cleanup(); } var buffer; function initializeattributes() { gl.enablevertexattribarray(0); buffer = gl.createbuffer(); gl.bindbu...
Creating 3D objects using WebGL - Web APIs
/ left face -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, ]; since we've added a z-component to our vertices, we need to update the numcomponents of our vertexposition attribute to 3. // tell webgl how to pull out the positions from the position // buffer into the vertexposition attribute { const numcomponents = 3; ... gl.vertexattribpointer( programinfo.attriblocations.vertexposition, numcomponents, type, normalize, stride, offset); gl.enablevertexattribarray( programinfo.attriblocations.vertexposition); } define the vertices' colors we also need to build an array of colors for each of the 24 vertices. this code starts by defining a color for each face, then uses a loop to assemble an array of all the c...
WebRTC coding guide - Web APIs
how do you create a web application that uses two-way video or data streams without having to do all the hard work of compressing frames, building streams, and so forth by yourself? this coding guide will explain in depth how webrtc works, and will dive into actual code that uses webrtc to do useful things. there are no subpages at this time. ...
Introduction to WebRTC protocols - Web APIs
you a unique address if like most situations your device doesn’t have a public ip address, and relay data through a server if your router doesn’t allow you to directly connect with peers. ice uses stun and/or turn servers to accomplish this, as described below. stun session traversal utilities for nat (stun) (acronym within an acronym) is a protocol to discover your public address and determine any restrictions in your router that would prevent a direct connection with a peer. the client will send a request to a stun server on the internet who will reply with the client’s public address and whether or not the client is accessible behind the router’s nat. nat network address translation (nat) is used to give your device a public ip address. a router will have a public ip addres...
Writing a WebSocket server in C# - Web APIs
am() gets the stream which is the communication channel. both sides of the channel have reading and writing capability. properties: int available this property indicates how many bytes of data have been sent. the value is zero until networkstream.dataavailable is true. networkstream methods: write(byte[] buffer, int offset, int size) writes bytes from buffer, offset and size determine length of message. read(byte[] buffer, int offset, int size) reads bytes to buffer. offset and size determine the length of the message. let us extend our example. tcpclient client = server.accepttcpclient(); console.writeline("a client connected."); networkstream stream = client.getstream(); //enter to an infinite cycle to be able to handle every change in stream while (true) { whi...
Writing a WebSocket server in Java - Web APIs
et these bytes: 129 134 167 225 225 210 198 131 130 182 194 135 - 129: fin (is this the whole message?) rsv1 rsv2 rsv3 opcode 1 0 0 0 0x1=0001 fin: you can send your message in frames, but now keep things simple. opcode 0x1 means this is a text. full list of opcodes - 134: if the second byte minus 128 is between 0 and 125, this is the length of the message. if it is 126, the following 2 bytes (16-bit unsigned integer), if 127, the following 8 bytes (64-bit unsigned integer, the most significant bit must be 0) are the length. i can take 128 because the first bit is always 1. - 167, 225, 225 and 210 are the bytes of the key to decode. it changes every time. - the remaining encoded byt...
WebXR permissions and security - Web APIs
or if the document doesn't have permission to enter immersive mode. inline presentation when you request an xrsession with the mode set to inline, and any features are required or requested, the browser will only allow the session to be created if the call to requestsession() was made by code which is executing expressly due to user intent. specifically: if the requestsession() call isn't coming from within the handler executed in response to a user event, and is not being issued while launching a web application, the request is denied and false is delivered to the promise's fulfillment handler. if the document making the request isn't the one which is responsible for the script, the request is denied. if the document making the request isn't trustworthy, the request is denied and fal...
Keyframe Formats - Web APIs
s described below. the following special attributes may also be specified: offset the offset of the keyframe specified as a number between 0.0 and 1.0 inclusive or null. this is equivalent to specifying start and end states in percentages in css stylesheets using @keyframes. if this value is null or missing, the keyframe will be evenly spaced between adjacent keyframes. easing the timing function used from this keyframe until the next keyframe in the series. composite the keyframeeffect.composite operation used to combine the values specified in this keyframe with the underlying value. this will be auto if the composite operation specified on the effect is being used. specifications specification status comment web animationsthe definition of ...
Basic concepts behind Web Audio API - Web APIs
llow modular routing. basic audio operations are performed with audio nodes, which are linked together to form an audio routing graph. several sources — with different types of channel layout — are supported even within a single context. this modular design provides the flexibility to create complex audio functions with dynamic effects. audio nodes are linked via their inputs and outputs, forming a chain that starts with one or more sources, goes through one or more nodes, then ends up at a destination. although, you don't have to provide a destination if you, say, just want to visualize some audio data. a simple, typical workflow for web audio would look something like this: create the audio context. inside the context, create sources — such as <audio>, oscillator, or stream. cre...
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. warning: the web crypto api provides a number of low-level cryptographic primitives. it's very easy to misuse them, and the pitfalls involved can be very subtle. even assuming you use the basic cryptographic functions correctly, secure key management and overall security system design are extremely hard to get right, and are generally the domain of specialist security experts. errors in security system design and implementation can make the security of the system completely ineffective. if you're not sure you know what you are doing, you probably shouldn't be using this api. interfaces some browsers implemented an interface called crypto without having i...
Functions and classes available to Web Workers - Web APIs
provides information about the system's connection in terms of general connection type (e.g., 'wifi', 'cellular', etc.). 53.0 (53) only on mobile (yes) only on mobile no support no support notifications allows web pages to control the display of system notifications to the end user 41 (41) ? ? ? performance the performance interface represents timing-related performance information for the given page. 34.0 (34.0) no support 33.0 no support performanceentry, performancemeasure, performancemark, performanceobserver, performanceresourcetiming enables retrieval and analysis of detailed data regarding various aspects of an application's network performance. (yes) (yes) (yes) (yes) promise javascript...
window.cancelAnimationFrame() - Web APIs
window.webkitrequestanimationframe || window.msrequestanimationframe; var cancelanimationframe = window.cancelanimationframe || window.mozcancelanimationframe; var start = window.mozanimationstarttime; // only supported in ff. other browsers can use something like date.now(). ...
Window.dialogArguments - Web APIs
the dialogarguments property returns the parameters that were passed into the window.showmodaldialog() method. this lets you determine what parameters were specified when the modal dialog was created. syntax value = window.dialogarguments; ...
window.dump() - Web APIs
Web › API › Window › dump
need to create it (right-click the content area -> new -> boolean). on windows, you will need a console to actually see anything. if you don't have one already, closing the application and re-opening it with the command line parameter -console should create the console or use -attach-console to use the existing console. on other operating systems, it's enough to launch the application from a terminal. to redirect the console output to a file, run firefox without the -console option and use the syntax to redirect stderr and stdout to a file, i.e.: firefox > console.txt 2>&1 if you would like the console messages to appear in the console you used to launch the application, you can use the gecko console redirector. precompiled binaries are available in the zipped archive https://github.co...
Window.fullScreen - Web APIs
Web › API › Window › fullScreen
this is to prevent scripts designed to set this property in internet explorer from breaking. return value isinfullscreen a boolean. ...
Window.getComputedStyle() - Web APIs
entages for width or height, as those will be replaced by their pixel equivalent only for used values. returned values are sometimes deliberately inaccurate. to avoid the “css history leak” security issue, browsers may lie about the computed styles for a visited link, returning values as if the user never visited the linked url. see plugging the css history leak and privacy-related changes coming to css :visited for examples of how this is implemented. during css transitions, getcomputedstyle returns the original property value in firefox, but the final property value in webkit. in firefox, properties with the value auto return the used value, not the value auto. so if you apply top:auto and bottom:0 on an element with height:30px and a containing block of height:100px, firefox's compu...
Window.getDefaultComputedStyle() - Web APIs
specifications proposed to the css working group. ...
Window.innerWidth - Web APIs
Web › API › Window › innerWidth
om the innerheight property. syntax let intviewportwidth = window.innerwidth; value an integer value indicating the width of the window's layout viewport in pixels. this property is read-only, and has no default value. to change the window's width, use one of the window methods for resizing windows, such as resizeby() or resizeto(). usage notes if you need to obtain the width of the window minus the scrollbar and borders, use the root <html> element's clientwidth property instead. the innerwidth property is available on any window or object that behaves like a window, such as a frame or tab. example // this will return the width of the viewport var intframewidth = window.innerwidth; // this will return the width of the frame viewport within a frameset var intframewidth = self.inner...
Window.matchMedia() - Web APIs
Web › API › Window › matchMedia
syntax mqlist = window.matchmedia(mediaquerystring) parameters mediaquerystring a string specifying the media query to parse into a mediaquerylist. return value a new mediaquerylist object for the media query. use this object's properties and events to detect matches and to monitor for changes to those matches over time. ...
Window: online event - Web APIs
network problems or firewalls might still prevent the website from being reached. ...
Window.performance - Web APIs
the window interface's performance property returns a performance object, which can be used to gather performance information about the current document. it serves as the point of exposure for the performance timeline api, the high resolution time api, the navigation timing api, the user timing api, and the resource timing api. syntax performancedata = window.performance; value a performance object offering access to the performance and timing-related information offered by the apis it exposes. specifications specification status comment high resolution timethe definition of 'window.performance' in that specification. recommendation defines now() method. ...
Window: resize event - Web APIs
.e. returned by document.defaultview). only handlers registered on the window object will receive resize events. there is a proposal to allow all elements to be notified of resize changes. see resize observer to read the draft document, and github issues to read the on-going discussions. examples window size logger the following example reports the window size each time it is resized. bear in mind that since the example is running in an <iframe>, you'll need to actually get the <iframe> to resize before you see an effect. <p>resize the browser window to fire the <code>resize</code> event.</p> <p>window height: <span id="height"></span></p> <p>window width: <span id="width"></span></p> const heightoutput = document.queryselector('#height'); const widthoutput = document.queryselector('#wi...
Window.sizeToContent() - Web APIs
the window.sizetocontent() method sizes the window according to its content. in order for it to work, the dom content should be loaded when this function is called—for example, once the domcontentloaded event has been thrown. the minimal size of the window can be clamped. syntax window.sizetocontent() example window.sizetocontent(); specification this feature is not part of any specification. ...
WindowEventHandlers.onpopstate - Web APIs
o history entries for the same document. if the activated history entry was created by a call to history.pushstate(), or was affected by a call to history.replacestate(), the popstate event's state property contains a copy of the history entry's state object. note: calling history.pushstate() or history.replacestate() won't trigger a popstate event. the popstate event is only triggered by performing a browser action, such as clicking on the back button (or calling history.back() in javascript), when navigating between two history entries for the same document. syntax window.onpopstate = funcref; funcref is a handler function. examples for example, a page at http://example.com/example.html running the following code will generate alerts as indicated: window.onpopstate = function(e...
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
e using microtasks in javascript with queuemicrotask() for more details. microtasks are especially useful for libraries and frameworks that need to perform final cleanup or other just-before-rendering tasks. queuemicrotask() is exposed on the windoworworkerglobalscope mixin. syntax scope.queuemicrotask(function); parameters function a function to be executed when the browser engine determines it is safe to call your code. enqueued microtasks are executed after all pending tasks have completed but before yielding control to the browser's event loop. return value undefined. examples self.queuemicrotask(() => { // function contents here }) taken from the queuemicrotask spec: myelement.prototype.loaddata = function (url) { if (this._cache[url]) { queuemicrotask(() => { ...
Worker - Web APIs
Web › API › Worker
the message is stored in the event's data property. worker.onmessageerror is an eventhandler representing the code to be called when the messageerror event is raised. methods inherits methods from its parent, eventtarget, and implements methods from abstractworker. worker.postmessage() sends a message — consisting of any javascript object — to the worker's inner scope. worker.terminate() immediately terminates the worker. this does not let worker finish its operations; it is halted at once. serviceworker instances do not support this method. events message fires when the worker's parent receives a message from that worker. also available via the onmessage property. messageerror fires when a worker object receives a message that can't be deserialized. also availabl...
WorkerGlobalScope.close() - Web APIs
...
WorkerGlobalScope - Web APIs
erface and windoworworkerglobalscope and windoweventhandlers mixins. standard methods workerglobalscope.importscripts() imports one or more scripts into the worker's scope. you can specify as many as you'd like, separated by commas. for example: importscripts('foo.js', 'bar.js'); non-standard methods workerglobalscope.dump() allows you to write a message to stdout — i.e. in your terminal. this is the same as firefox's window.dump, but for workers. methods implemented from elsewhere windoworworkerglobalscope.atob() decodes a string of data which has been encoded using base-64 encoding. windoworworkerglobalscope.btoa() creates a base-64 encoded ascii string from a string of binary data. windoworworkerglobalscope.clearinterval() cancels the repeated execution set using w...
WritableStream - Web APIs
this object comes with built-in backpressure and queuing. constructor writablestream() creates a new writablestream object. properties writablestream.locked read only a boolean indicating whether the writablestream is locked to a writer. methods writablestream.abort() aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. writablestream.close() closes the stream. ...
WritableStreamDefaultWriter - Web APIs
t returned by writablestream.getwriter() and once created locks the writer to the writablestream ensuring that no other streams can write to the underlying sink. constructor writablestreamdefaultwriter() creates a new writablestreamdefaultwriter object instance. properties writablestreamdefaultwriter.closedread only allows you to write code that responds to an end to the streaming process. returns a promise that fulfills if the stream becomes closed or the writer's lock is released, or rejects if the stream errors. writablestreamdefaultwriter.desiredsizeread only returns the desired size required to fill the stream's internal queue. writablestreamdefaultwriter.readyread only returns a promise that resolves when the desired size of the stream's internal queue tra...
XDomainRequest.onerror - Web APIs
syntax xdr.onerror = funcref; parameters funcref a function to call when an error occurs. ...
Sending and Receiving Binary Data - Web APIs
you don't have to set the content-length header yourself, as the information is fetched from the stream automatically: // make a stream from a file. ...
init() - Web APIs
use as the global for our request. often, this is the outer window, but it may also be a sandbox or backstage pass. this may be null, but if it is, the request cannot create a document. prior to firefox 23, this was always a window. baseuri the base uri to use when resolving relative uris when handling the request. this may be null. loadgroup optional an optional load group used when performing the request. if this is specified, it is used even if the global has a window with a load group already established. ...
XMLHttpRequest.channel - Web APIs
this is null if the channel hasn't been created yet. ...
XMLHttpRequest.response - Web APIs
cument the response is an html document or xml xmldocument, as appropriate based on the mime type of the received data. see html in xmlhttprequest to learn more about using xhr to fetch html content. json the response is a javascript object created by parsing the contents of received data as json. text the response is a text in a domstring object. ms-stream the response is part of a streaming download; this response type is only allowed for download requests, and is only supported by internet explorer. example this example presents a function, load(), which loads and processes a page from the server. it works by creating an xmlhttprequest object and creating a listener for readystatechange events such that that when readystate changes to done (4), the response is obtained and p...
XMLHttpRequest.responseType - Web APIs
cument the response is an html document or xml xmldocument, as appropriate based on the mime type of the received data. see html in xmlhttprequest to learn more about using xhr to fetch html content. json the response is a javascript object created by parsing the contents of received data as json. text the response is a text in a domstring object. ms-stream the response is part of a streaming download; this response type is only allowed for download requests, and is only supported by internet explorer. exceptions invalidaccesserror an attempt was made to change the value of responsetype on anxmlhttprequest which is in synchronous mode but not in a worker. for additional details, see synchronous xhr restrictions below. usage notes synchronous xhr restrictions you cannot chan...
XMLHttpRequest.timeout - Web APIs
the default value is 0, which means there is no timeout. timeout shouldn't be used for synchronous xmlhttprequests requests used in a document environment or it will throw an invalidaccesserror exception. when a timeout happens, a timeout event is fired. note: you may not use a timeout for synchronous requests with an owning window. ...
XMLHttpRequest: timeout event - Web APIs
the timeout event is fired when progression is terminated due to preset time expiring. 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. living standard ...
XPathException - Web APIs
properties xpathexception.code read only returns a short that contains one of the error code constants. constants constant value description invalid_expression_err 51 if the expression has a syntax error or otherwise is not a legal expression according to the rules of the specific xpathevaluator or contains specialized extension functions or variables not supported by this implementation. type_err 52 if the expression cannot be converted to return the specified type. ...
XPathResult - Web APIs
properties xpathresult.booleanvalueread only a boolean representing the value of the result if resulttype is boolean_type. xpathresult.invaliditeratorstateread only signifies that the iterator has become invalid. ...
XRBoundedReferenceSpace.boundsGeometry - Web APIs
t be located at ground level (that is, its y coordinate must be 0). this boundary is typically configured by the user, using the software that controls their xr hardware. this may be done by walking the border of the space they wish to use, or by drawing the shape of their room using their xr input device. theoretically, a more advanced system might use sensors or other detection methods to determine the bounds of a dedicated xr room (notice how we carefully don't call it a holodeck?). syntax bounds = xrreferencespace.boundsgeometry; value the boundsgeometry property is an array of dompointreadonly objects, each of which defines one vertex in a polygon inside which the viewer is required to remain. each point must be at floor level, with its y coordinate's value set to 0. additionally, t...
XRBoundedReferenceSpace - Web APIs
lowed to move. this is typically used when the xr system is capable of tracking the user's physical movement within a limited distance of their starting position. the specified bounds may, in fact, describe the shape and size of the room the user is located in, in order to let the webxr site or application prevent the user from colliding with the walls or other obstacles in the real world. at a minimum, the boundaries indicate the area in which the xr device is capable of tracking the user's movement. see the article using bounded reference spaces for details on how bounded spaces work and why they're useful. properties in addition to the properties of xrreferencespace, xrboundedreferencespace includes the following: boundsgeometry read only an array of dompointreadonly objects, each...
XRInputSource.targetRayMode - Web APIs
y're 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 target ray extends from the hand (or the object in the hand) in the targeted direction. 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. usage notes the input source's targetrayspace indicates the position and orientation of the target ray, and can be used to determine where to render the ray. example this fragment of code shows part of a function to be calle...
XRInputSource.targetRaySpace - Web APIs
's head. this shared space represents the same location as the space returned by the xrsession method requestreferencespace(), but is maintained as a different object to allow for future enhancements to the api. the target ray space reported by tracked pointer inputs (targetraymode of tracked-pointer) is actually based upon the true spatial position and orientation of the input device. to determine the position and orientation of the target ray while rendering a frame, pass it into the xrframe method getpose() method, then use the returned xrpose object's transform to gather the spatial information you need. example this fragment of code shows part of a function to be called once every frame. it looks for inputs which have a non-null targetrayspace. inputs which have a value for this pro...
XRInputSource - Web APIs
gamepad read only a gamepad object describing the state of the buttons and axes on the xr input source, if it is a gamepad or comparable device. if the device isn't a gamepad-like device, this property's value is null. note: while xrinputsource uses the gamepad interface from the gamepad api, this input device is strictly associated with the webxr hardware and is not a general-purpose gaming device. gripspaceread only an xrspace whose origin tracks the pose which is used to render objects which should appear as if they're held in the hand indicated by handedness. the orientation of this space indicates the angle at which the hand is gripping the object. read on in the main article on gripspace for more details on how to use this space. handednessread only a domstring that in...
XRInputSourceEvent() - Web APIs
ent to an xrsession when an ongoing primary squeeze action ends or when an input source with an ongoing primary squeeze action is disconnected. squeezestart sent to an xrsession when an input source begins its primary squeeze action, indicating that the user has begun to grab, squeeze, or grip the controller. examples the code below sets up handlers for primary action events in order to determine when the user clicks on (shoots at/pokes at/whatever) objects in the scene. xrsession.addeventlistener("select", event => { let targetraypose = event.frame.getpose(event.inputsource.targetrayspace, myrefspace); if (targetraypose) { let hit = myhittest(targetraypose.transform); if (hit) { /* handle the hit */ } } }); specifications specification status ...
XRInputSourceEvent - Web APIs
ent to an xrsession when an ongoing primary squeeze action ends or when an input source with an ongoing primary squeeze action is disconnected. squeezestart sent to an xrsession when an input source begins its primary squeeze action, indicating that the user has begun to grab, squeeze, or grip the controller. examples the code below sets up handlers for primary action events in order to determine when the user clicks on (shoots at/pokes at/whatever) objects in the scene. xrsession.addeventlistener("select", event => { let targetraypose = event.frame.getpose(event.inputsource.targetrayspace, myrefspace); if (targetraypose) { let hit = myhittest(targetraypose.transform); if (hit) { /* handle the hit */ } } }); specifications specification status ...
XRInputSourcesChangeEvent() - Web APIs
available webxr input devices. you won't typically call this constructor yourself, as these events are created and sent to you by the webxr system. syntax newinputsourceschangeevent = new xrinputsourceschangeevent(type, eventinitdict); parameters type a domstring indicating the type of event which has occurred. this string must always be inputsourceschange. eventinitdict an object conforming to the xrinputsourceschangeeventinit dictionary, prodividing the initial values for the event. return value a newly-created xrinputsourceschangeevent object configured based upon the input parameters provided. event types inputsourceschange delivered to the xrsession when the set of input devices available to it changes. example the following snippet of code creates a new xrinputsourc...
XRPermissionDescriptor - Web APIs
feature which is requested but not required for the app to function. the available features are the same as those used by xrsessioninit; see default features in xrsessioninit for further information. requiredfeatures an array of strings giving the names of the webxr features for which permission must be obtained in order to use your app or site. examples the example below demonstrates performing the permission request for an application that requires the local-floor reference space in an immersive-vr environment. if the permissions api is found to be available (by checking to see if navigator.permissions is defined), its query() method is called, specifying the permission descriptor we've established, xrpermissiondesc. when the returned promise resolves, we check the returned status. ...
XRPose.transform - Web APIs
Web › API › XRPose › transform
obtained by calling xrframe.getpose(). syntax let posetransform = xrpose.transform; value an xrrigidtransform which provides the position and orientation of the xrpose relative to the xrframe to which this xrpose is aligned. this is the same pose that's returned by the frame's getpose() method. example this handler for the xrsession event select handles events for tracked pointers. it determines the targeted object by passing the event frame's pose into a function called findtargetusingray(), then dispatches the event differently depending on the user's handedness; this is done by comparing the value of the xrinputsource property handedness to a value in the variable user.handedness. if the source is a controller in the user's primary hand, a function is called on the targeted object c...
XRRigidTransform.position - Web APIs
3d point, specified in meters, describing the translation component of the transform. syntax let pos = xrrigidtransform.position; value a read-only dompointreadonly indicating the 3d position component of the transform matrix. the units are meters. note: the w component of the point is always 1.0. ...
XRSession.cancelAnimationFrame() - Web APIs
ode which starts up a webxr session if immersive vr mode is supported. once started, the session schedules its first frame to be rendered by calling requestanimationframe(). the pausexr() function shown at the bottom can be called to suspend the webvr session, in essence, by canceling any pending animation frame callback. since each frame callback schedules the next one, removing the callback terminates updating of the webxr scene. const xr = navigator.xr; let requesthandle = null; let xrsession = null; if (xr) { xr.issessionsupported('immersive-vr') .then((issupported) => { if (issupported) { startxr(); } }); } function framecallback(time, xrframe) { xrsession.requestanimationframe(framecallback); // update and render the frame } async function startxr() { xr...
XRSession: end event - Web APIs
an end event is fired at an xrsession object when the webxr session has ended, either because the web application has chosen to stop the session, or because the user agent terminated the session. 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 st...
XRSession.inputSources - Web APIs
ally to the xr device currently in use. the returned object is live; as devices are connected to and removed from the user's system, the list's contents update to reflect the changes. usage notes you can add a handler for the xrsession event inputsourceschange to be advised when the contents of the session's connected devices list changes. you can then either get the value of inputsources to examine the list, or you can refer to a reference to the list that you've previously saved. specifications specification status comment webxr device apithe definition of 'xrsession.inputsources' in that specification. working draft initial definition. ...
XRSession.onsqueezeend - Web APIs
eze events works, see primary squeeze actions in inputs and input sources. syntax xrsession.onsqueezeend = squeezeendhandlerfunction; value a function to be invoked whenever the xrsession receives a squeezestart event, indicating the ending of a primary squeeze action. examples this snippet of code adds a simple handler for the squeezeend event, which responds only to events on the user's dominant hand. in response to the end of the squeeze operation, this code looks to see if there is an object currently being held by the user by checking to see if the variable user.heldobject contains a reference to an object representing the held item. if heldobject has an object reference, that object is passed to a function called cancelobjectdrag(), which would be written to return the object to ...
XRSession.onsqueezestart - Web APIs
object or controller. to learn more about how to use and handle webxr controller inputs, see inputs and input sources. syntax xrsession.onsqueezestart = squeezestarthandlerfunction; value a function to be invoked whenever the xrsession receives a squeezestart event. 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.inputs...
XRSession.renderState - Web APIs
while this property is read only, you can call the xrsession method updaterenderstate() to make changes. ...
XRSession: select event - Web APIs
the webxr event select is sent to an xrsession when one of the session's input sources has completed a primary action. 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. bubbles yes cancelable no interface xrinputsourceevent event handler property onselect for details on how the selectstart, select, and selectend events work, and how you should react to them, see primary actions in inputs and input sources. examples the following example uses addeventlistener() to set up a handler for the select event. the handler fetches the pose representing the...
XRSession: squeeze event - Web APIs
the webxr event squeeze is sent to an xrsession when one of the session's input sources has completed a primary squeeze action. 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. bubbles yes cancelable no interface xrinputsourceevent event handler property onsqueeze for details on how the squeezestart, squeeze, and squeezeend events work, and how you should react to them, see primary squeeze actions in inputs and input sources. examples the following example uses addeventlistener() to set up a handler for the squeeze event. the handler fetches the...
XRSession: squeezestart event - Web APIs
d successfully, the code then uses the value of event property type to route control to an appropriate function to handle the event which arrived: for squeezestart events, a mybegintracking() function is called with the target ray pose's matrix. 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. mybegintracking() returns an object representing the object the user has begun to drag. upon receiving a squeeze event, the mydropobject() function is called with the target object and the current target ray pose transform as inputs. this places the object into its new position in the world and triggers any effects that may arise from doing so (like scheduling an anim...
XRSession.updateRenderState() - Web APIs
the specified object may have any combination of the following fields. ...
XRSession.visibilityState - Web APIs
sion may currently be visible to the user, it is not the user's primary focus at the moment; it's also possible the session is not currently visible at all. in order to optimize resource utilization, the user agent may be handling the session's requestanimationframe() callbacks at a throttled rate. input controllers are not being processed for the session. 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 obscure...
XRSession: visibilitychange event - Web APIs
bubbles yes cancelable no interface xrsessionevent event handler property onvisibilitychange when the xrsession receives this event, the visibility state has already been changed. ...
XRSessionEvent - Web APIs
rovides the folllowing: session read only the xrsession to which the event refers. methods while xrsessionevent defines no methods, it inherits methods from its parent interface, event. session event types the following events are represented using the xrsessionevent interface, and are permitted values for its type property. end fired at the session when it has ended, after being terminated by the application or the user agent. visibilitychange fired at the session whenever its visibility state changes. examples this example creates a listiener that watches for the visibility state of the session to change. it reacts by calling a function mysessionvisible() with a boolean indicating whether or not the session is visible; this function might, for instance, spin up or reconfi...
XRSessionInit - Web APIs
immersive-ar) sessions support both the viewer and local reference spaces. because immersive sessions are required to support the local reference space, any request to open an immersive xrsession is required to obtain explicit or implicit user consent. inline sessions all inline webxr sessions support the viewer reference space. security requirements each reference space or feature type has minimum safety requirements. by session type, those are: reference space type user consent rquirement feature policy requirement bounded-floor always required xr-spatial-tracking local always required for inline sessions xr-spatial-tracking local-floor always required xr-spatial-tracking unbounded always required xr-spati...
XRSessionMode - Web APIs
ther than occupying the full visual space. inline sessions can be presented in either mono or stereo mode, and may or may not have viewer tracking available. inline sessions don't require special hardware and should be avalable on any user agent offering webxr api support. usage notes the xrsessionmode type indicates the values that can be specified when calling xr.issessionsupported() to determine whether or not the specified session type is supported and available to be used, and by requestsession() to attempt to open a new webxr session. the immersive-ar mode supports all the same features and reference spaces that immersive-vr does, since both are immersive sessions. browsers may support either or both of these modes, but if webxr is available, the inline mode is always supported. sp...
XRSystem - Web APIs
Web › API › XRSystem
xrsession.end() .then(() => xrsession = null); } } this code starts by checking to see if webxr is available by looking for the navigator.xr property. if it's found, we know webxr is present, so we proceed by establishing a handler for the button which the user can click to toggle immersive vr mode on and off. however, we don't yet know if the desired immersive mode is available. to determine this, we call issessionsupported(), passing it the desired session option before enabling the button, immersivebutton, which the user can then use to switch to immersive mode only if immersive vr mode is available. if immersive vr isn't available, the button is disabled to prevent its use. the onbuttonclicked() function checks to see if there's already a session running. if there isn't, we use ...
XRTargetRayMode - Web APIs
y're 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 target ray extends from the hand (or the object in the hand) in the targeted direction. 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. examples this fragment of code shows part of a function to be called once every frame. it looks for inputs which have a non-null targetrayspace. inputs which have a value for this property represent inputs that project a targe...
XRViewerPose - Web APIs
he views array, rendering them one after another. by calling viewport() on the webgl context, specifying the xrview as input, you can get the viewport to use when rendering in order to draw the frame for that eye into the correct part of the drawing surface. also, when rendering the scene for spectators or other players in a multiplayer game, the transform of the xrviewerpose can be used to determine both placement and facing direction of the other players in the game, so that they can be drawn in the correct place with the correct facing. the viewer's pose for the animation frame represented by xrframe can be obtained by calling the frame's getviewerpose() method, specifying the reference space in which the origin's position should be computed. the returned xrviewerpose tells you where the...
XRWebGLLayer() - Web APIs
scene. 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. context a webglrenderingcontext or webgl2renderingcontext identifying the webgl drawing context to use for rendering the scene for the specified webxr session. layerinit optional an object conforming to the xrwebgllayerinit dictionary, providing configuration options for the new xrwebgllayer. the options available are: alpha optional the frame buffer's color buffer will be established with an alpha channel if the alpha boolean property is true. otherwise, the color buffer will not have an alpha channel. the default value is true. antialias optional a boolean value which is true if anti...
XRWebGLLayer.framebuffer - Web APIs
from the framebuffer results in a webgl invalid_framebuffer_operation error (0x0506). calling checkframebufferstatus() on the webgl context from outside the animation frame callback causes the webgl framebuffer_unsupported error (0x8cdd) to be reported. opaque framebuffers initialized with the depth property set to false will not have a depth buffer and will rely on the coordinates alone to determine distance. opaque framebuffers initialized without specifying a stencil will not have a stencil buffer. opaque framebuffers will not have an alpha channel available unless the alpha property is true when creating the layer. the xr compositor assumes that opaque framebuffers use colors with premultiplied allpha, regardless of whether or not the webgl context's premultipliedalpha context attribu...
XRWebGLLayer.getNativeFramebufferScaleFactor() static method - Web APIs
e while at the same time providing typical applications an acceptable balance of image quality and performance. for example, consider a device which uses a 2560x1440 pixel frame buffer (which is used to render two views, for the left and right eyes, side by side each at a resolution of 1280x1440 pixels). consider a frame buffer which at full size looks like this: if, on this device, it's determined that due to gpu limitations the browser needs to reduce image quality in order to improve performance to an acceptable level, it might choose to halve the resolution. in this case, the value returned by xrwebgllayer.getnativeframebufferscalefactor() will be 2.0. this method of dividing the frame buffer between views is shown in the following diagram. now the width and height of the frame buf...
XRWebGLLayer.ignoreDepthValues - Web APIs
the value of ignoredepthvalues can only be set when the xrwebgllayer is instantiated, by setting the corresponding value in the xrwebgllayerinit object specified as the constructor's layerinit parameter. ...
XRWebGLLayer - Web APIs
ources. 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. properties antialias read only a boolean value indicating whether or not the webgl context's framebuffer supports anti-aliasing. the specific type of anti-aliasing is determined by the user agent. framebuffer read only returns a webglframebuffer suitable for passing into the bindframebuffer() method. framebufferwidth read only returns the width of the xrwebgllayer's framebuffer. framebufferheight read only returns the height of the layer's framebuffer. ignoredepthvalues read only a boolean which indicates whether or not the webxr compositor should make use ...
XRWebGLLayerInit.depth - Web APIs
he only source for depth information is the vertex coordinates, and reduces the accuracy and quality of rendering, but may potentially affect the performance of rendering as well. the default value is true. usage notes this property differs from ignoredepthvalues in that a layer created with ignoredepthvalues set to true may still have a depth buffer, but will not make use of it. you can determine whether or not the depth buffer is being used by a given webgl rendering layer during your xr session by checking the value returned by xrwebgllayer.ignoredepthvalues. if this is true, then the depth buffer is either not present or is being ignored. if (gllayer.ignoredepthvalues) { /* not using the depth buffer */ } example in this example, a new xrwebgllayer is created for a webxr session,...
XRWebGLLayerInit.stencil - Web APIs
tencil buffer. the stencil buffer is an optional buffer which, just like the depth buffer, contains one entry for every pixel in the frame buffer. also just like the depth buffer, the value of an enter in the stencil buffer directly affects how (or if) the corresponding pixel is drawn during rendering. you can store values into each entry in the stencil bufer, then specify an operation that determines which stencil buffer values correspond to pixels which should be drawn to the screen during each frame. syntax let layerinit = { stencil: false }; let gllayer = new xrwebgllayer(xrsession, gl, layerinit); let gllayer = new xrwebgllayer(xrsession, gl, { stencil: false }); value a boolean which can be set to false to specify that the new webgl layer should not include a stencil buffer. th...
Introduction - Web APIs
or multiple content, as well as simplify maintenance and allow a quick (only modify one file) way to change the look of content. css (cascade style sheets) was one of the first ways proposed by the w3c. css is a simple way to apply style rules to a web document. these style rules define how the document (the content) should be laid out. however, it has several limitations, such as lack of programming structures and ability to create complex layout models. css also has limited support for changing the position of an element. xsl (extensible stylesheet language) transformations are composed of two parts: xsl elements, which allow the transformation of an xml tree into another markup tree and xpath, a selection language for trees. xslt takes an xml document (the content) and creates a brand ne...
Resources - Web APIs
resources transforming xml: netscape and xslt what kind of language is xslt? 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. ...
XSL Transformations in Mozilla FAQ - Web APIs
, both text/xsl and application/xslt+xml are supported mime types for xslt media stylesheets. note that firefox will override your xslt stylesheet if your xml is detected as an rss or atom feed. a known workaround is to add a sufficiently long xml comment to the beginning of your xml file in order to "push" the <feed> or <rss> tag out of the first 512 bytes, which is analyzed by firefox to determine if it's a feed or not. see the discussion on bug #338621 for more information. it works in ie, but not in mozilla? there are even more differences. most come from what we suspect ie to do after the transformation. it (afaict) serializes and parses the output to generate what it actually renders. mozilla in contrast renders exactly the result of your transformation. can i do disable-output-esc...
msRegionOverflow - Web APIs
this proprietary property is specific to internet explorer. ...
Using the aria-hidden attribute - Accessibility
aria-hidden="true" will remove the entire element from the accessibility api. role="presentation" and role="none" will remove the semantic meaning of an element while still exposing it to assistive technology. values false (default) the element is exposed to the accessibility api. true the element is not exposed to the accessibility api. undefined (default) the user agent determines if the element is exposed to or hidden from the accessibility api. examples in the example below, the paragraph is not exposed to the accessibility api (e.g. would not be read aloud by a screen reader). <p aria-hidden="true"> some things are better left unsaid. </p> children elements can be omitted from accessibility apis: <p> this is not hidden <span aria-hidden="true">but this is</...
Using the aria-orientation attribute - Accessibility
assistive technology note: opinions may differ on how assistive technology should handle this technique. the information provided above is one of those opinions and therefore not normative. examples example 1: the snippet below shows a simple slider that is oriented vertically. ...
Using the aria-valuetext attribute - Accessibility
e is one of those opinions and therefore not normative. examples example 1: the snippet below shows a simple slider for selecting a day of the week. the value of the slider is numeric, and the aria-valuetext attribute is used to provide the name of the day. the application would programmatically update aria-valuetext depending on aria-valuenow. ...
Using the group role - Accessibility
a script or assistive technologies); a group should not be considered a major perceivable section on a page. when the role is added to an element, the browser will send out an accessible group event to assistive technology products which can then notify the user about it. a group should be used to form a logical collection of items with related functionality, such as children in a tree widget forming a collection of siblings in a hierarchy, or a collection of items having the same container in a directory. however, when a group is used in the context of list, authors must limit its children to listitem elements. group elements may be nested. proper handling of a group by assistive technologies is determined by the context in which it is provided. if an author believes a section is signific...
Using ARIA: Roles, states, and properties - Accessibility
dialog states and properties widget attributes aria-autocomplete aria-checked aria-current aria-disabled aria-errormessage aria-expanded aria-haspopup aria-hidden aria-invalid aria-label aria-level aria-modal aria-multiline aria-multiselectable aria-orientation aria-placeholder aria-pressed aria-readonly aria-required aria-selected aria-sort aria-valuemax aria-valuemin aria-valuenow aria-valuetext live region attributes aria-live aria-relevant aria-atomic aria-busy drag & drop attributes aria-dropeffect aria-dragged relationship attributes aria-activedescendant aria-colcount aria-colindex aria-colspan aria-controls aria-describedby aria-details aria-errormessage aria-flowto aria-labelledby aria-owns aria-posinset aria-rowc...
ARIA: application role - Accessibility
s not have a related html widget and thus is completely free form. the author of the application must take full responsibility for not letting users get stuck in a focus limbo or trap focus inside something the user cannot exit of. all aspects of interaction, including returning to the regular web content on other parts of the page, must be handled. use wisely, and cautiously! 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. think hard on if you ...
ARIA: article role - Accessibility
ticle items there are within that feed. keyboard interactions this role does not support any specific keyboard interaction. required javascript features event handlers this role does not require any event handlers to be present. changing attribute values when constructing a feed, set the aria-posinset and aria-setsize attributes on each article role to the appropriate values, bearing in mind that aria-posinset is 1-based. always use native element if available. instead of a div with the article role, the <article> element should be used. examples the restaurant recommendations feed display along with its separate documentation from the wai-aria 1.1 authoring practices feed design pattern specifications specification status accessible rich internet app...
ARIA: feed role - Accessibility
required by any attributes. for example, setting aria-busy to true during the update operation if needed, and then to false upon completion. examples example implementation of feed pattern specifications specification status accessible rich internet applications (wai-aria) 1.1the definition of 'feed' in that specification. recommendation screen reader support coming soon ...
ARIA: grid role - Accessibility
oes not move. ← moves focus one cell to the left. if focus is on the left-most cell in the row, focus does not move. ↓ moves focus one cell down. if focus is on the bottom cell in the column, focus does not move. ↑ moves focus one cell up. if focus is on the top cell in the column, focus does not move. page down moves focus down an author-determined number of rows, typically scrolling so the bottom row in the currently visible set of rows becomes one of the first visible rows. if focus is in the last row of the grid, focus does not move. page up moves focus up an author-determined number of rows, typically scrolling so the top row in the currently visible set of rows becomes one of the last visible rows. if focus is in the firs...
ARIA: table role - Accessibility
quired if the columns are not present in the dom all the time. it provides an explicit indication of the number of columns in the full table. set the value to the total number of columns in the full table. if unknown, set aria-colcount="-1". aria-rowcount attribute this attribute is only required if the rows are not present in the dom all the time, such as scrollable tables that reuse rows to minimize the number of dom nodes. it provides an explicit indication of the number of rows in the full table. set the value to the total number of rows in the full table. if unknown, set aria-colcount="-1". keyboard interactions none required javascript features none. for sortable columns, see the columnheader aria role. the first rule of aria use is if you can use a native feature with the...
ARIA: button role - Accessibility
lement 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. see the official wai-aria example code. description the button role identifies an element as a button to screen readers. a button is a widget used to perform actions such as submitting a form, opening a dialog, cancelling an action, or performing a command such as inserting a new record or displaying information. a common convention to inform users a button will launch a dialog is to append "…" (ellipsis) to the button's label, e.g., "save as…". 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. a toggle button is a two-state button th...
ARIA: heading role - Accessibility
t you cannot make major changes to. added benefits none. specifications specification status accessible rich internet applications (wai-aria) 1.1the definition of 'heading' in that specification. recommendation precedence order the heading role overrides the native semantic meaning of the element it is being used for. the aria-level attribute, in addition, determines what level of heading is being exposed. screen reader support tbd ...
Accessibility: What users can do to browse more safely - Accessibility
eed of the display and computer" hardware and operating systems on many computers offer control that is not afforded to developers. the user can do much to protect himself by learning his operating system, its personalization and accessibility settings. those in the public sector who must accomodate those with special sensitivities, should consider setting aside at least one work station and becoming familiar with its personalization and accessibility settings. understanding personalization and accessibility settings can actually be a money-saving endeavor. one work station can be set up to acommodate both a low-vision individual (needs high-contrast) and to accomodate an individual with photosensitive susceptibilities, by simply, adjusting personalization and accessiblity settings. use mod...
An overview of accessible web applications and widgets - Accessibility
into three different types of attributes: roles, states, and properties. roles describe widgets that aren't otherwise available in html 4, such as sliders, menu bars, tabs, and dialogs. properties describe characteristics of these widgets, such as if they are draggable, have a required element, or have a popup associated with them. states describe the current interaction state of an element, informing the assistive technology if it is busy, disabled, selected, or hidden. aria attributes are interpreted automatically by the browser and translated to the operating system's native accessibility apis. so an element with role="slider" will be controlled in the same way as a native slider is controlled on the operating system. this provides a much more consistent user experience than was possible...
Robust - Accessibility
ly by browsers and other user agents such as screenreaders. to pass this criterion, make sure that your html is as valid as possible. use the w3c validator to validate your markup. see debugging html for a practical guide. 4.1.2 name, role, value (a) the name and role of user interface components (e.g. form inputs, buttons, links, etc.) should be programmatically determinable. when using semantic elements correctly for their intended purpose, this criterion should be passed automatically. when scripting custom components, you will need to use wai-aria roles and other features to make sure your controls will be interpreted and are able to be used as intended, e.g. not only by sighted mouse users, but also by screenreader users, keyboard-only users, etc. ...
Accessibility
the steps that need to be taken to conform to the recommendations outlined in the w3c web content accessibility guidelines 2.0 (wcag 2.0 or just wcag, for the purposes of this writing). keyboard-navigable javascript widgets until now, web developers who want to make their styled <div> and <span> based widgets accessible have lacked the proper techniques. keyboard accessibility is part of the minimum accessibility requirements which a developer should be aware of. aria a collection of articles to learn how to use aria to make your html documents more accessible. assistive technology (at) development a collection of articles intended for at developers mobile accessibility checklist this document provides a concise checklist of accessibility requirements for mobile app developers. co...
-moz-user-input - CSS: Cascading Style Sheets
/* keyword values */ -moz-user-input: none; -moz-user-input: enabled; -moz-user-input: disabled; /* global values */ -moz-user-input: inherit; -moz-user-input: initial; -moz-user-input: unset; for elements that normally take user input, such as a <textarea>, the initial value of -moz-user-input is enabled. note: -moz-user-input was one of the proposals leading to the proposed css 3 user-input property, which has not yet reached candidate recommendation (call for implementations). a similar property, user-focus, was proposed in early drafts of a predecessor of the css3 ui specification, but was rejected by the working group. ...
-webkit-mask-attachment - CSS: Cascading Style Sheets
/* keyword values */ -webkit-mask-attachment: scroll; -webkit-mask-attachment: fixed; -webkit-mask-attachment: local; /* multiple values */ -webkit-mask-attachment: scroll, local; -webkit-mask-attachment: fixed, local, scroll; /* global values */ -webkit-mask-attachment: inherit; -webkit-mask-attachment: initial; -webkit-mask-attachment: unset; syntax values scroll if scroll is specified, the mask image scrolls within the viewport along with the block that contains the mask image. ...
:-moz-first-node - CSS: Cascading Style Sheets
the :-moz-first-node css pseudo-class is a mozilla extension that represents any element that is the first child node of some other element. it differs from :first-child because it does not match a first-child element with (non-whitespace) text before it. note: any whitespace at the start of an element is ignored for the determination of :-moz-first-node. syntax :-moz-first-node examples css span:-moz-first-node { background-color: lime; } html <p> <span>this matches!</span> <span>this doesn't match.</span> </p> <p> blahblah. <span>this doesn't match because it's preceded by text.</span> </p> result specifications not part of any standard. ...
:-moz-last-node - CSS: Cascading Style Sheets
the :-moz-last-node css pseudo-class is a mozilla extension that represents any element that is the last child node of some other element. it differs from :last-child because it does not match a last-child element with (non-whitespace) text after it. note: any whitespace at the end of an element is ignored for the determination of :-moz-last-node. syntax :-moz-last-node examples css span:-moz-last-node { background-color: lime; } html <p> <span>this does not match.</span> <span>this matches!</span> </p> <p> <span>this doesn't match because it's followed by text.</span> blahblah. </p> result specifications not part of any standard. ...
:-moz-locale-dir(ltr) - CSS: Cascading Style Sheets
note: this selector is mainly used by extensions and themes to adapt the user interface based on the user's locale. ...
:-moz-locale-dir(rtl) - CSS: Cascading Style Sheets
note: this selector is mainly used by extensions and themes to adapt the user interface based on the user's locale. ...
:-moz-only-whitespace - CSS: Cascading Style Sheets
pace css pseudo-class matches elements that only contains text nodes that only contain whitespace. (this includes elements with empty text nodes and elements with no child nodes.) syntax syntax not found in db! examples html <div> </div> css :root { overflow: hidden; max-width: 100vw; max-height: 100vh; } div { background-color: #ccc; box-sizing: border-box; height: 100vh; min-height: 16px; min-height: 1rem; } div { border: 4px solid red; } :-moz-only-whitespace { border-color: lime; } result specifications briefly defined as :blank in selectors level 4, but then the functionality was merged into :empty and :blank redefined to mean empty <input>. ...
::-moz-progress-bar - CSS: Cascading Style Sheets
-bar css pseudo-element is a mozilla extension that represents the progress bar inside a <progress> element. (the bar represents the amount of progress that has been made.) if you want to select the unfinished part of <progress> in mozilla, please select the <progress> directly. syntax ::-moz-progress-bar examples html <progress value="30" max="100">30%</progress> <progress max="100">indeterminate</progress> css ::-moz-progress-bar { background-color: red; } /* force indeterminate bars to have zero width */ :indeterminate::-moz-progress-bar { width: 0; } result specifications not part of any standard. ...
::-moz-range-progress - CSS: Cascading Style Sheets
wer portion of the track (i.e., groove) in which the indicator slides in an <input> of type="range". this portion corresponds to values lower than the value currently selected by the thumb (i.e., virtual knob). 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
oz-range-thumb css pseudo-element is a mozilla extension that represents the thumb (i.e., virtual knob) of an <input> of type="range". the user can move the thumb along the input's track to alter its numerical value. 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
the ::-moz-range-track css pseudo-element is a mozilla extension that represents the track (i.e., groove) in which the indicator slides in an <input> of type="range". 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. ...
::-webkit-meter-bar - CSS: Cascading Style Sheets
the ::-webkit-meter-bar css pseudo-class is a webkit extension that represents the meter bar in a <meter> element. syntax ::-webkit-meter-bar specifications not part of any standard. ...
::-webkit-meter-even-less-good-value - CSS: Cascading Style Sheets
the ::-webkit-meter-even-less-good-value gives a red color to a <meter> element when the value and the optimum attributes fall outside the low-high range, but in opposite zones. ...
::-webkit-meter-inner-element - CSS: Cascading Style Sheets
ebkit css pseudo-element for selecting and applying styles to to the outer containing element of a <meter> element. additional markup to render the meter element as read-only. syntax ::-webkit-meter-inner-element specifications not part of any standard. ...
::-webkit-meter-optimum-value - CSS: Cascading Style Sheets
the ::-webkit-meter-optimum-value css pseudo-element styles the <meter> element when its value is inside the low-high range. green is the default color. syntax ::-webkit-meter-optimum-value specifications not part of any standard. examples this example will only work in browsers based on webkit or blink. ...
::-webkit-meter-suboptimum-value - CSS: Cascading Style Sheets
the ::-webkit-meter-suboptimum-value pseudo-element gives a yellow color to the <meter> element when the value attribute falls outside of the low-high range. syntax ::-webkit-meter-suboptimum-value examples this example will only work in browsers based on webkit or blink. html <meter min="0" max="10" value="6">score out of 10</meter> css meter::-webkit-meter-suboptimum-value { background: -webkit-gradient linear, left top, left bottom; height: 100%; box-sizing: border-box; } result specifications not part of any standard. ...
::after (:after) - CSS: Cascading Style Sheets
Web › CSS › ::after
ion of words and punctuation">text</span> with a few <span tabindex="0" data-descr="small popups that appear when hovering">tooltips</span>. </p> css span[data-descr] { position: relative; text-decoration: underline; color: #00f; cursor: help; } span[data-descr]:hover::after, span[data-descr]:focus::after { content: attr(data-descr); position: absolute; left: 0; top: 24px; min-width: 200px; border: 1px #aaaaaa solid; border-radius: 10px; background-color: #ffffcc; padding: 12px; color: #000000; font-size: 14px; z-index: 1; } result specifications specification status comment css pseudo-elements level 4the definition of '::after' in that specification. working draft no significant changes to the previous specification...
::before (:before) - CSS: Cascading Style Sheets
Web › CSS › ::before
consisting of a backslash followed by the hexadecimal unicode value. ...
::first-letter (:first-letter) - CSS: Cascading Style Sheets
html <h2>my heading</h2> <p>lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. at vero eos et accusam et justo duo dolores et ea rebum. stet clita kasd gubergren, no sea takimata sanctus est.</p> <p>duis autem vel eum iriure dolor in hendrerit in vulputate velit es...
::grammar-error - CSS: Cascading Style Sheets
working draft initial definition. ...
::selection - CSS: Cascading Style Sheets
g cognitive concerns or who are less technologically literate, unexpected changes to selection styles may hurt their understanding of the functionality. if overridden, it is important to ensure that the contrast ratio between the text and background colors of the selection is high enough that people experiencing low vision conditions can read it. color contrast ratio is found by comparing the luminosity of the selected text and the selected text background colors. to meet current web content accessibility guidelines (wcag), text content must have a contrast ratio of 4.5:1, or 3:1 for larger text such as headings. (wcag defines large text as between 18.66px and 24px and bold, or 24px or larger.) webaim: color contrast checker mdn understanding wcag, guideline 1.4 explanations understand...
:blank - CSS: Cascading Style Sheets
Web › CSS › :blank
risk, as the csswg keeps changing it. see csswg issue #1967. the :blank css pseudo-class selects empty user input elements (eg. <input> or <textarea>). syntax :blank examples simple :blank example in eventual supporting browsers, the :blank pseudo-class will enable developers to highlight in some way input controls that are not required, but still have no content filled in, perhaps as a reminder to users. html <textarea></textarea> css textarea:blank { border: 3px solid red; } result specifications specification status comment selectors level 4the definition of ':blank' in that specification. working draft initial definition. ...
:dir() - CSS: Cascading Style Sheets
Web › CSS › :dir
dir() pseudo-class is not equivalent to the [dir=…] attribute selectors. the latter match the html dir attribute, and ignore elements that lack it — even if they inherit a direction from their parent. (similarly, [dir=rtl] and [dir=ltr] won't match the auto value.) in contrast, :dir() will match the value calculated by the user agent, even if inherited. note: in html, the direction is determined by the dir attribute. other document types may have different methods. syntax the :dir() pseudo-class requires one parameter, representing the text directionality you want to target. parameters ltr target left-to-right elements. rtl target right-to-left elements. formal syntax :dir( ltr | rtl ) examples html <div dir="rtl"> <span>test1</span> <div dir="ltr">test2 <div di...
:focus-visible - CSS: Cascading Style Sheets
the :focus-visible pseudo-class applies while an element matches the :focus pseudo-class and the ua (user agent) determines via heuristics that the focus should be made evident on the element. (many browsers show a “focus ring” by default in this case.) this selector is useful to provide a different focus indicator based on the user’s input modality (mouse vs. keyboard). note that firefox supports similar functionality through an older, prefixed pseudo-class — :-moz-focusring. syntax :focus-visible examples basic example in this example, the :focus-visible selector uses the ua's behavior to determine when to match. compare what happens when you click on the different controls with a mouse, versus when you tab through them using a keyboard. note the difference in behavior from ...
:invalid - CSS: Cascading Style Sheets
Web › CSS › :invalid
r: 5px solid #ffdddd; } input:valid { background-color: #ddffdd; } form:valid { border: 5px solid #ddffdd; } input:required { border-color: #800000; border-width: 3px; } input:required:invalid { border-color: #c00000; } result accessibility concerns the color red is commonly used to indicate invalid input. people who have certain types of color blindness will be unable to determine the input's state unless it is accompanied by an additional indicator that does not rely on color to convey meaning. typically, descriptive text and/or an icon are used. mdn understanding wcag, guideline 1.4 explanations understanding success criterion 1.4.1 | w3c understanding wcag 2.0 notes radio buttons if any one of the radio buttons in a group is required, the :invalid pseudo-class ...
:left - CSS: Cascading Style Sheets
Web › CSS › :left
for example, if the first page has a major writing direction of left-to-right then it will be a :right page; if it has a major writing direction of right-to-left then it will be a :left page. ...
:not() - CSS: Cascading Style Sheets
Web › CSS › :not
since pseudo-elements are not simple selectors, they are not valid arguments to :not(); thus, selectors like :not(p::before) will not work. useless selectors can be written using this pseudo-class. for example, :not(*) matches any element which is not an element, which is obviously nonsense,...
:read-only - CSS: Cascading Style Sheets
the :read-only css pseudo-class represents an element (such as input or textarea) that is not editable by the user. input:read-only, textarea:read-only { background-color: #ccc; } p:read-only { background-color: #ccc; } syntax :read-only examples confirming form information in read-only/read-write controls one use of readonly form controls is to allow the user to check and verify information that they may have entered in an earlier form (for example, shipping details), while still being able to submit the information along with the rest of the form. we do just this in the example below. the :read-only pseudo-class is used to remove all the styling that makes the inputs look like clickable fields, making them look more like read-only paragraphs.the :read-write pseudo-class on the...
:read-write - CSS: Cascading Style Sheets
the :read-write css pseudo-class represents an element (such as input or textarea) that is editable by the user. input:read-write, textarea:read-write { background-color: #bbf; } p:read-write { background-color: #bbf; } syntax :read-write examples confirming form information in read-only/read-write controls one use of readonly form controls is to allow the user to check and verify information that they may have entered in an earlier form (for example, shipping details), while still being able to submit the information along with the rest of the form. we do just this in the example below. the :read-only pseudo-class is used to remove all the styling that makes the inputs look like clickable fields, making them look more like read-only paragraphs.the :read-write pseudo-class on th...
:right - CSS: Cascading Style Sheets
Web › CSS › :right
for example, if the first page has a major writing direction of left-to-right then it will be a :right page; if it has a major writing direction of right-to-left then it will be a :left page. ...
:valid - CSS: Cascading Style Sheets
Web › CSS › :valid
required text inputs are invalid when empty, but valid when they have something filled in. the email input on the other hand is valid when empty, as it is not required, but invalid when it contains something that is not a proper email address. accessibility concerns the color green is commonly used to indicate valid input. people who have certain types of color blindness will be unable to determine the input's state unless it is accompanied by an additional indicator that does not rely on color to convey meaning. typically, descriptive text and/or an icon are used. mdn understanding wcag, guideline 1.4 explanations understanding success criterion 1.4.1 | w3c understanding wcag 2.0 specifications specification status comment html living standardthe definit...
:where() - CSS: Cascading Style Sheets
Web › CSS › :where
r? footer a { color: blue; } this won't work for the red links, because the selectors inside :is() count towards the specificity of the overall selector, and class selectors have a higher specificity than element selectors. however, selectors inside :where() have specificity 0, so the orange footer link will be overidden by our simple selector. you can see the result below (although bear in mind that currently :is() and :where() are currently only enabled by default in firefox nightly, version 77+. in other versions of firefox it is behind a pref — layout.css.is-where-selectors.enabled). note: you can also find this example on github; see is-where. syntax :where( <complex-selector-list> )where <complex-selector-list> = <complex-selector>#where <complex-selector> = <compound-selec...
@charset - CSS: Cascading Style Sheets
Web › CSS › @charset
this method is obsoleted in html5 and must not be used. assume that the document is utf-8 syntax @charset "utf-8"; @charset "iso-8859-15"; where: charset is a <string> denoting the character encoding to be used. it must be the name of a web-safe character encoding defined in the iana-registry, and must be double-quoted, following exactly one space character (u+0020), and immediately terminated with a semicolon. if several names are associated with an encoding, only the one marked with preferred must be used. formal syntax @charset "<charset>"; examples valid and invalid charset declarations @charset "utf-8"; /* set the encoding of the style sheet to unicode utf-8 */ @charset 'iso-8859-15'; /* invalid, wrong quoting style used */ @charset "utf-8"; /* invalid, more...
negative - CSS: Cascading Style Sheets
e representation. the negative descriptor has effect only if the system value is symbolic, alphabetic, numeric, additive, or extends, if the extended counter style itself uses a negative sign. if the negative descriptor is specified for other systems that don't support negative counter values, then the descriptor is ignored. ...
pad - CSS: Cascading Style Sheets
the pad descriptor can be used with custom counter style definitions when you need the marker representations to have a minimum length. syntax pad: 3 "0"; values <integer> && <symbol> the <integer> specifies a minimum length that all counter representations must reach. the value must be non-negative. if the minimum length is not reached, the representation will be padded with the specified <symbol>. description if a marker representation is smaller than the specified pad length, then the marker will be padded with the specified pad symbol. marker representations longer than the pad length are constructed as normal. pad descriptor takes the minimum marker length as an integer and a symbol to be used for padding as the second parameter. a common usage of the pad descriptor is when y...
speak-as - CSS: Cascading Style Sheets
counter symbol to be either spoken as its numerical value or just represented with an audio cue. syntax /* keyword values */ speak-as: auto; speak-as: bullets; speak-as: numbers; speak-as: words; speak-as: spell-out; /* @counter-style name value */ speak-as: <counter-style-name>; values auto if the value of speak-as is specified as auto, then the effective value of speak-as will be determined based on the value of the system descriptor: if the value of system is alphabetic, the effective value of speak-as will be spell-out. if system is cyclic, the effective value of speak-as will be bullets. if system is extends, the value of speak-as will be the same as if speak-as: auto is specified on the extended style. for all other cases, specifying auto has the same effect as speci...
font-display - CSS: Cascading Style Sheets
syntax /* keyword values */ font-display: auto; font-display: block; font-display: swap; font-display: fallback; font-display: optional; values auto the font display strategy is defined by the user agent. block gives the font face a short block period and an infinite swap period. swap gives the font face an extremely small block period and an infinite swap period. fallback gives the font face an extremely small block period and a short swap period. optional gives the font face an extremely small block period and no swap period. ...
@font-face - CSS: Cascading Style Sheets
-face css at-rule specifies a custom font with which to display text; the font can be loaded from either a remote server or a locally-installed font on the user's own computer. syntax @font-face { font-family: "open sans"; src: url("/fonts/opensans-regular-webfont.woff2") format("woff2"), url("/fonts/opensans-regular-webfont.woff") format("woff"); } descriptors font-display determines how a font face is displayed based on whether and when it is downloaded and ready to use. font-family specifies a name that will be used as the font face value for font properties. font-stretch a font-stretch value. since firefox 61 (and in other modern browsers) this also accepts two values to specify a range that is supported by a font-face, for example font-stretch: 50% 200%; font-style...
device-aspect-ratio - CSS: Cascading Style Sheets
the device-aspect-ratio css media feature can be used to test the width-to-height aspect ratio of an output device. syntax the device-aspect-ratio feature is specified as a <ratio>. it is a range feature, meaning that you can also use the prefixed min-device-aspect-ratio and max-device-aspect-ratio variants to query minimum and maximum values, respectively. examples article { padding: 1rem; } @media screen and (min-device-aspect-ratio: 16/9) { article { padding: 1rem 5vw; } } specifications specification status comment media queries level 4the definition of 'device-aspect-ratio' in that specification. candidate recommendation deprecated in media queries level 4. media queriesthe definition of 'device-aspect-ratio' in that specific...
display-mode - CSS: Cascading Style Sheets
area is used and no user agent chrome is shown. standalone standalone the application will look and feel like a standalone application. this can include the application having a different window, its own icon in the application launcher, etc. in this mode, the user agent will exclude ui elements for controlling navigation, but can include other ui elements such as a status bar. minimal-ui minimal-ui the application will look and feel like a standalone application, but will have a minimal set of ui elements for controlling navigation. the elements will vary by browser. browser browser the application opens in a conventional browser tab or new window, depending on the browser and platform. (none) examples @media all and (display-mode: ful...
grid - CSS: Cascading Style Sheets
Web › CSS › @media › grid
syntax the grid feature is specified as a <mq-boolean> value (0 or 1) representing whether or not the ouput device is grid-based. examples html <p class="unknown">i don't know if you're using a grid device. ...
light-level - CSS: Cascading Style Sheets
normal the device is used in a environment with a light level in the ideal range for the screen, and which does not necessitate any particular adjustment. ...
monochrome - CSS: Cascading Style Sheets
Web › CSS › @media › monochrome
the monochrome css media feature can be used to test the number of bits per pixel in the monochrome frame buffer of the output device. syntax the monochrome feature is specified as an <integer> representing the number of bits per pixel in the monochrome frame buffer. if the device is not a monochrome device, the value is zero. it is a range feature, meaning that you can also use the prefixed min-monochrome and max-monochrome variants to query minimum and maximum values, respectively. examples html <p class="mono">your device supports monochrome pixels!</p> <p class="no-mono">your device doesn't support monochrome pixels.</p> css p { display: none; } /* any monochrome device */ @media (monochrome) { p.mono { display: block; color: #333; } } /* any non-monochrome device ...
prefers-reduced-motion - CSS: Cascading Style Sheets
important: an embedded example at the bottom of this page has a scaling movement that may be problematic for some readers. readers with vestibular motion disorders may wish to enable the reduce motion feature on their device before viewing the animation. syntax no-preference indicates that the user has made no preference known to the system. ...
prefers-reduced-transparency - CSS: Cascading Style Sheets
the prefers-reduced-transparency css media feature is used to detect if the user has requested that the system minimize the amount of transparency used across elements. syntax no-preference indicates that the user has made no preference known to the system. this keyword value evaluates as false in the boolean context. reduce indicates that user has notified the system that they prefer an interface that minimizes the amount of transparent or translucent layer effects. user preferences currently no user agent implements this feature, although various operating systems do support such preferences and if this media query is ever implemented user agents will likely rely on the settings provided by the operating systems. examples note: no browser currently implements this feature s...
@page - CSS: Cascading Style Sheets
Web › CSS › @page
ge rendering is clipped. description you can't change all css properties with @page. you can only change the margins, orphans, widows, and page breaks of the document. attempts to change any other css properties will be ignored. the @page at-rule can be accessed via the css object model interface csspagerule. note: the w3c is discussing how to handle viewport-related <length> units, vh, vw, vmin, and vmax. meanwhile do not use them within a @page at-rule. formal syntax @page <page-selector-list> { <page-body> }where <page-selector-list> = [ <page-selector># ]?<page-body> = <declaration>? [ ; <page-body> ]? | <page-margin-box> <page-body>where <page-selector> = <pseudo-page>+ | <ident> <pseudo-page>*<page-margin-box> = <page-margin-box-type> '{' <declaration-list> '}'where <pseudo-pag...
max-zoom - CSS: Cascading Style Sheets
larger values are zoomed in. smaller values are zoomed out. syntax /* keyword value */ max-zoom: auto; /* <number> values */ max-zoom: 0.8; max-zoom: 2.0; /* <percentage> value */ max-zoom: 150%; values auto the user agent will set the document's upper zoom factor limit. ...
orientation - CSS: Cascading Style Sheets
t defined by @viewport. /* keyword values */ orientation: auto; orientation: portrait; orientation: landscape; for a ua/device where the orientation is changed upon tilting the device, an author can use this descriptor to inhibit the orientation change. syntax values auto the user agent will set the document's orientation automatically, typically based on the device's orientation as determined by an accelerometer (if the device has such a hardware sensor), although there is often a user-controlled, os-level "lock orientation" setting that will trump the accelerometer reading. portrait the document should be locked into portrait orientation. landscape the document should be locked into landscape orientation. formal definition related at-rule@viewportinitial valueautopercentages...
user-zoom - CSS: Cascading Style Sheets
the user-zoom css descriptor controls whether or not the user can change the zoom factor of a document defined by @viewport. /* keyword values */ user-zoom: zoom; user-zoom: fixed; syntax values zoom the user can zoom in or out. fixed the user cannot zoom in or out. accessibility concerns disabling zooming capabilities prevents people experiencing low vision conditions from being able to read and understand page content. mdn understanding wcag, guideline 1.4 explanations understanding success criterion 1.4.4 | understanding wcag 2.0 formal definition related at-rule@viewportinitial valuezoompercentagesrefer to the size of bounding boxcomputed valueas specified formal syntax zoom | fixed examples disabling user zoom @viewport { user-zoom: fixed; } specifications ...
viewport-fit - CSS: Cascading Style Sheets
thin the display. cover the viewport is scaled to fill the device display. it is highly recommended to make use of the safe area inset variables to ensure that important content doesn't end up outside the display. this descriptor hasn't been added to https://github.com/mdn/data/blob/master/css/at-rules.json yet. 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. formal definition related at-rule@viewportinitial valueautocomputed valueas specified formal syntax auto | contain | cover examples scaling viewport to fit device display @viewport { viewport-fit: cover; } specifications specification status comment ...
Alternative style sheets - CSS: Cascading Style Sheets
ndardthe definition of 'meta http-equiv="default-style")' in that specification. living standard css object model (cssom)the definition of 'css style sheet collections' in that specification. working draft the css om specification defines the concepts of the style sheet set name, its disabled flag, and the preferred css style sheet set name. it defines how these are determined, and lets the html specification define the html-specific behaviors by requiring it to define when to create a css style sheet. html 4.01 specificationthe definition of 'alternative style sheets' in that specification. recommendation earlier, the html specification itself defined the concept of preferred and alternate stylesheets. ...
Coordinate systems - CSS: Cascading Style Sheets
finitions and orientations of these coordinate systems using css properties such as transform. however, we'll only talk about the standard coordinate system for now. standard cssom coordinate systems there are four standard coordinate systems used by the css object model, as described below. offset coordinates specified using the "offset" model use the top-left corner of the element being examined, or on which an event has occurred. for example, when a mouse event occurs, the position of the mouse as specified in the event's offsetx and offsety properties are given relative to the top-left corner of the node to which the event has been delivered. the origin is inset by the distances specified by padding-left and padding-top. client the "client" coordinate system uses as its origin the...
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. the behavior of these keyframe animations can be controlled by specifying their timing function, duration, their number of repetitions, and other attributes. reference css properties animation animation-delay animation-direction animation-duration animation-fill-mode animation-iteration-count animation-name animation-play-state animation-timing-function css at-rules @keyframes guides detecting css animation support describes a technique for detecting if a browser supports css animations. using css animations step-by-step tutorial about how to create animations using css. this article describes each relevant css property and at-rule and explains how th...
CSS Box Alignment - CSS: Cascading Style Sheets
is controlled with align-items. the first item overrides the align-items value set on the group by setting align-self to center. flexbox alignment example in this example, three flex items are aligned on the main axis using justify-content and on the cross axis using align-items. the first item overrides the align-items set on the group by setting align-self to center. key concepts and terminology the specification details some alignment terminology to make it easier to discuss these alignment properties outside of their implementation within a particular layout method. there are also some key concepts which are common to all layout methods. relationship to writing modes alignment is linked to writing modes in that when we align an item we do not consider whether we are aligning it...
Mastering margin collapsing - CSS: Cascading Style Sheets
the margins of adjacent siblings are collapsed (except when the latter sibling needs to be cleared past floats). no content separating parent and descendants if there is no border, padding, inline part, block formatting context created, or clearance to separate the margin-top of a block from the margin-top of one or more of its descendant blocks; or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block from the margin-bottom of one or more of its descendant blocks, then those margins collapse. the collapsed margin ends up outside the parent. empty blocks if there is no border, padding, inline content, height, or min-height to separate a block's margin-top from its margin-bottom, then its top and bottom margins collapse. some thi...
Handling Overflow in Multicol - CSS: Cascading Style Sheets
he reader to scroll down to view the next set of columns. 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. one way to avoid this is to only apply the column properties if you know you have enough height. in the example below we have used a min-height query to check the height before applying the column properties. in the final guide in this series we will see how multicol works with the fragmentation spec to give us control over how content breaks between columns. ...
Handling content breaks in multicol - CSS: Cascading Style Sheets
e a figure element. breaks before and after boxes, which would include our heading example above. breaks between lines. breaks inside boxes to control breaks inside boxes use the break-inside property. this property takes values of: auto avoid avoid-page avoid-column avoid-region in the example below, we have applied break-inside to the figure element to prevent the caption from becoming separated from the image. breaks before and after boxes the break-before and break-after properties are used to control breaks before and after elements. they take the following values when in a multicol context: auto avoid avoid-column column in this next example, we are forcing a column break before an h2 element. breaks between lines the orphans and widows properties are also ...
CSS Containment - CSS: Cascading Style Sheets
formation is something that is usually known, and in fact quite obvious, to the web developer creating the page. however browsers cannot guess at your intent and cannot assume that an article will be entirely self-contained. therefore this property gives you a nice way to explain to the browser this fact, and allow it to make performance optimizations based on that knowledge. key concepts and terminology this specification defines only one property, the contain property. the values for this property indicate the type of containment that you want to apply to that element. layout containment article { contain: layout; } layout is normally scoped to the entire document, which means that if you move one element the entire document needs to be treated as if things could have moved anywhere.
Basic concepts of flexbox - CSS: Cascading Style Sheets
taken away. if we do not have enough space in the container to lay out our items and flex-shrink is set to a positive integer the item can become smaller than the flex-basis. as with flex-grow different values can be assigned in order to cause one item to shrink faster than others — an item with a higher value set for flex-shrink will shrink faster than its siblings that have lower values. the minimum size of the item will be taken into account while working out the actual amount of shrinkage that will happen, which means that flex-shrink has the potential to appear less consistent than flex-grow in behavior. we’ll therefore take a more detailed look at how this algorithm works in the article controlling ratios of items along the main axis. note that these values for flex-grow and flex...
Mastering Wrapping of Flex Items - CSS: Cascading Style Sheets
d with flex-direction. if flex-direction is set to row-reverse then the items will start from the end edge of the container and lay themselves out in reverse ordered lines. note that the reversing is only happening in the inline, row direction. we start on the right then go onto the second line and again start from the right. we aren’t reversing in both directions, starting from the bottom coming up the container! single-dimensional layout explained as we have seen from the above examples if our items are allowed to grow and shrink, when there are fewer items in the last row or column then those items grow to fill the available space. there is no method in flexbox to tell items in one row to line up with items in the row above — each flex line acts like a new flex container. it deal...
Ordering Flex Items - CSS: Cascading Style Sheets
nd end lines. remember that the start line relates to writing modes. the row-related examples above demonstrate how row and row-reverse work in a left-to-right language such as english. if you are working in a right-to-left language like arabic then row would start on the right, row-reverse on the left. this can seem like a neat way to display things in reverse order however you should be mindful that the items are only visually displayed in reverse order. the specification says the following on this matter: “note: the reordering capabilities of flex layout intentionally affect only the visual rendering, leaving speech order and navigation based on the source order. this allows authors to manipulate the visual presentation while leaving the source order intact for non-css uas and ...
Block and inline layout in normal flow - CSS: Cascading Style Sheets
ing in an inline formatting context. the behaviour of elements which have a block or inline formatting context is also defined in this specification. for elements with a block formatting context, the spec says: “in a block formatting context, boxes are laid out one after the other, vertically, beginning at the top of a containing block. the vertical distance between two sibling boxes is determined by the 'margin' properties. vertical margins between adjacent block-level boxes in a block formatting context collapse. in a block formatting context, each box's left outer edge touches the left edge of the containing block (for right-to-left formatting, right edges touch).” - 9.4.1 for elements with an inline formatting context: “in an inline formatting context, boxes are laid out h...
Flow Layout and Writing Modes - CSS: Cascading Style Sheets
ts with writing modes in possibly unanticipated ways. the external resources and see also sections of this document link to more writing modes resources. the writing modes specification the css writing modes level 3 specification defines the impact a change the document writing mode has on flow layout. in the writing modes introduction, the specification says, “a writing mode in css is determined by the writing-mode, direction, and text-orientation properties. it is defined primarily in terms of its inline base direction and block flow direction.” the specification defines the inline base direction as the direction in which content is ordered on a line. this defines the start and end of the inline direction. the start is where sentences start and the end is where a line of text ends...
In Flow and Out of Flow - CSS: Cascading Style Sheets
be said to be in flow. appearing on the page in the order that they are in the source. taking an item out of flow all elements are in-flow apart from: floated items items with position: absolute (including position: fixed which acts in the same way) the root element (html) out of flow items create a new block formatting context (bfc) and therefore everything inside them can be seen as a mini layout, separate from the rest of the page. the root element therefore is out of flow, as the container for everything in our document, and establishes the block formatting context for the document. floated items in this example i have a div, and then two paragraphs. i’ve added a background colour to the paragraphs, and then floated the div left. the div is now out of flow. as a float it is...
CSS Grid Layout and Accessibility - CSS: Cascading Style Sheets
find themselves jumping from the top to the bottom of the document due to a reordered item being next in line. the specification warns authors (the csswg term for web developers) not to do this reordering. authors must use order and the grid-placement properties only for visual, not logical, reordering of content. style sheets that use these features to perform logical reordering are non-conforming. what does this mean for designing with grid layout in practice? visual not logical re-ordering any time you reorder things with grid layout – or with flexbox – you only perform visual reordering. the underlying source is what controls things like text to speech, and the tab order of the document. you can see how this works with a very simple example. in this example i have used grid to...
Implementing image sprites in CSS - CSS: Cascading Style Sheets
lock; height: 20px; width: 20px; } a background position can be added either as two x, y values after the url()() in the background, or as background-position. for example: #btn1 { background-position: -20px 0px; } #btn2 { background-position: -40px 0px; } this would move the element with the id 'btn1' 20 pixels to the left and the element with the id 'btn2' 40 pixels to the left (assuming they have the class toolbtn assigned and are affected by the image rule above). similarly, you can also make hover states with: #btn:hover { background-position: <pixels shifted right>px <pixels shifted down>px; } ...
Logical properties for margins, borders and padding - CSS: Cascading Style Sheets
es and values you will see there are a huge number of properties listed. this is mostly due to the fact that there are four longhand values each for margin, border, and padding side, plus all the shorthand values. mappings for margins, borders, and padding the specification details mappings for each logical value to a physical counterpart. in the table below i have given these mapped values assuming that the writing-mode in use is horizontal-tb — with a left to right direction. the inline direction therefore runs horizontally — left to right — and margin-inline-start would be equivalent to margin-left. 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 b...
Stacking without the z-index property - CSS: Cascading Style Sheets
in the example below, elements #1 through #4 are positioned elements. element #5 is static, and so is drawn below the other four elements, even though it comes later in the html markup. source code for the example html <div id="abs1" class="absolute"> <b>div #1</b><br />position: absolute;</div> <div id...
The stacking context - CSS: Cascading Style Sheets
nder div#5 (z-index 1) because div #5 belongs to div #3, which has an higher z-index value. div #3's z-index is 4, but this value is independent from z-index of div #4, div #5 and div #6, because it belongs to a different stacking context. an easy way to figure out the rendering order of stacked elements along the z axis is to think of it as a "version number" of sorts, where child elements are minor version numbers underneath their parent's major version numbers. this way we can easily see how an element with a z-index of 1 (div #5) is stacked above an element with a z-index of 2 (div #2), and how an element with a z-index of 6 (div #4) is stacked below an element with a z-index of 5 (div #1). in our example (sorted according to the final rendering order): root div #2 - z-i...
Using the :target pseudo-class in selectors - CSS: Cascading Style Sheets
see also :target original document information author(s): eric meyer, standards evangelist, netscape communications original copyright information: copyright © 2001-2003 netscape. all rights reserved. note: this reprinted article was originally part of the devedge site. ...
Using CSS transforms - CSS: Cascading Style Sheets
om left;" src="https://udn.realityripple.com/samples/6d/6633f3efc0.png"> skewing and translating here is the mdn logo, skewed by 10 degrees and translated by 150 pixels on the x-axis. <img style="transform: skewx(10deg) translatex(150px); transform-origin: bottom left;" src="https://udn.realityripple.com/samples/6d/6633f3efc0.png"> 3d specific css properties performing css transformations in 3d space is a bit more complex. you have to start by configuring the 3d space by giving it a perspective, then you have to configure how your 2d elements will behave in that space. perspective the first element to set is the perspective. the perspective is what gives us the 3d impression. the farther from the viewer the elements are, the smaller they are. setting perspe...
CSS Transitions - CSS: Cascading Style Sheets
css transitions is a module of css that lets you create gradual transitions between the values of specific css properties. the behavior of these transitions can be controlled by specifying their timing function, duration, and other attributes. 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. this article describes each relevant css property and explains how they interact with each other. specifications specification status comment css transitions working draft initial definition. ...
CSS data types - CSS: Cascading Style Sheets
Web › CSS › CSS Types
see also css units and values introduction to css: values and ...
Animatable CSS properties - CSS: Cascading Style Sheets
e-start left letter-spacing line-clamp line-height margin margin-block-end margin-block-start margin-bottom margin-inline-end margin-inline-start margin-left margin-right margin-top mask mask-border mask-position mask-size max-block-size max-height max-inline-size max-lines max-width min-block-size min-height min-inline-size min-width object-position offset offset-anchor offset-distance offset-path offset-position offset-rotate opacity order outline outline-color outline-offset outline-width padding padding-block-end padding-block-start padding-bottom padding-inline-end p...
Comments - CSS: Cascading Style Sheets
Web › CSS › Comments
nt below is used to disable specific styling */ /* span { color: blue; font-size: 1.5em; } */ notes the /* */ comment syntax is used for both single and multiline comments. there is no other way to specify comments in external style sheets. however, when using the <style> element, you may use <!-- --> to hide css from older browsers, although this is not recommended. as with most programming languages that use the /* */ comment syntax, comments cannot be nested. in other words, the first instance of */ that follows an instance of /* closes the comment. specifications css 2.1 syntax and basic data types #comments ...
Inline formatting context - CSS: Cascading Style Sheets
arting on the left. in a vertical writing mode they would be laid out vertically starting at the top. in the example below, the two (<div>) elements with the black borders form a block formatting context, inside which each word participates in an inline formatting context. the boxes in the horizontal writing mode run horizontally, and the vertical writing mode boxes run vertically. boxes forming a line are contained by a rectangular area called a line box. this box will be large enough to contain all of the inline boxes in that line; when there is no more room in the inline direction another line will be created. therefore a paragraph is a set of inline line boxes, stacked in the block direction. when an inline box is split, margins, borders, and padding have no visual effect where the...
Grid wrapper - CSS: Cascading Style Sheets
ern is useful for aligning grid content within a central wrapper, while also allowing items to break out and align to the edge of the containing element or page when desired. requirements items placed on the grid should be able to align to a horizontally-centered max-width wrapper and/or the outer edges of the grid. recipe download this example choices made this recipe uses the css grid minmax() function to define the grid track sizes in the grid-template-columns property. for the central columns with a maximum width we can set a minimum value of 0 or greater and a maximum value that specifies the maximum size the column tracks will grow to. using a numeric unit (pixels, ems, rems) will create a fixed maximum size for the central wrapper, whereas using percentage values or viewport ...
Sticky footers - CSS: Cascading Style Sheets
in this recipe. requirements the sticky footer pattern needs to meet the following requirements: footer sticks to the bottom of the viewport when content is short. if the content of the page extends past the viewport bottom, the footer then sits below the content as normal. 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. the .wrapper has a minimum height of 100% which means it is as tall as the container it is in. we then create a single column ...
Layout mode - CSS: Cascading Style Sheets
there are several of them: normal flow — all elements are part of normal flow until you do something to take them out of it. normal flow includes block layout, designed for laying out boxes such as paragraphs and inline layout, which lays out inline items such as text. table layout, designed for laying out tables. float layout, designed to cause an item to position itself left or right with the rest of the content in normal flow wrapping around it. ...
Testing media queries programmatically - CSS: Cascading Style Sheets
hods and properties. once you've created a mediaquerylist object, you can check the result of the query or receive notifications when the result changes. creating a media query list before you can evaluate the results of a media query, you need to create the mediaquerylist object representing the query. to do this, use the window.matchmedia method. ...
Using Media Queries for Accessibility - CSS: Cascading Style Sheets
ular disorders, epilepsy, and migraine and scotopic sensitivity. also, this method of switching animation off according to the user's preference can also benefit users with low battery or low-end phones or computers. syntax no-preference indicates that the user has made no preference known to the system. reduce indicates that user has notified the system that they prefer an interface that minimizes the amount of movement or animation, preferably to the point where all non-essential movement is removed. example this example has an annoying animation unless you turn on reduce motion in your accessibility preferences. html <div class="animation">animated box</div> css .animation { -webkit-animation: vibrate 0.3s linear infinite both; animation: vibrate 0.3s linear infinite bo...
Media queries - CSS: Cascading Style Sheets
ou 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. testing media queries programmatically describes how to use media queries in your javascript code to determine the state of a device, and to set up listeners that notify your code when the results of media queries change (such as when the user rotates the screen or resizes the browser). using media queries for accessibility learn how media queries can help users understand your website better. specifications specification status comment media queries level 5 editor's d...
Privacy and the :visited selector - CSS: Cascading Style Sheets
before about 2010, the css :visited selector allowed websites to uncover a user's browsing history and figure out what sites the user had visited. this was done through window.getcomputedstyle and other techniques. this process was quick to execute, and made it possible not only to determine where the user had been on the web, but could also be used to guess a lot of information about the user's identity. to mitigate this problem, browsers have limited the amount of information that can be obtained from visited links. little white lies to preserve users' privacy, firefox and other browsers will lie to web applications under certain circumstances: the window.getcomputedstyle method, and similar functions such as element.queryselector, will always return values indicating that a user has...
Shorthand properties - CSS: Cascading Style Sheets
d property that's able to define the values of background-color, background-image, background-repeat, and background-position. 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. that sounds anecdotal, but it really means that it overrides previously set values. therefore: background-color: red; background: url(images/bg.gif) no-repeat left top; will not set the color of the background to red but to background-color's default, transparent, as the second rule has precedence. only the indi...
Syntax - CSS: Cascading Style Sheets
Web › CSS › Syntax
bracket). blocks sometimes can be nested, so opening and closing braces must be matched. such blocks are naturally called declaration blocks and declarations inside them are separated by a semi-colon, ';' (u+003b semicolon). a declaration block may be empty, that is containing null declaration. white spaces around declarations are ignored. the last declaration of a block doesn't need to be terminated by a semi-colon, though it is often considered good style to do it as it prevents forgetting to add it when extending the block with another declaration. a css declaration block is visualized in the diagram below. note: the content of a css declaration block, that is a list of semi-colon-separated declarations, without the initial and closing braces, can be put inside an html style attrib...
Cubic Bezier Generator - CSS: Cascading Style Sheets
/ 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; canvas.onmouseup = mouseup; } else { alert('you need safari or firefox 1.5+ to see this demo.'); } } function cx(x) { return x * scaling + rulers; } function reversex(x) { return (x - rulers) / scaling; } function lx(x) { //used when drawing vertical li...
CSS Tutorials - CSS: Cascading Style Sheets
Web › CSS › Tutorials
u to define configurations of style, as keyframes, and to transition between them defining an animation. css transitions css3 transitions allow you to define an animation between several styles and to control the way this transition happens. css transforms transforms allow you to change the position of elements by modifying their coordinate space: it allows for translating, rotating, and deforming them in the 2d or 3d spaces. css gradients gradients are images that transition smoothly from one color to another. there are several types of gradients allowed in css: linear or radial, repeating or not. this tutorial describes how to use them. advanced-level css tutorials css also got new features allowing you to create complex layouts. though the simplest way to achieve such layout, they...
Using CSS custom properties (variables) - CSS: Cascading Style Sheets
ur"></div> </div> </div> ... with the following css: .two { --test: 10px; } .three { --test: 2em; } in this case, the results of var(--test) are: for the class="two" element: 10px for the class="three" element: 2em for the class="four" element: 10px (inherited from its parent) for the class="one" element: invalid value, which is the default value of any custom property keep in mind that these are custom properties, not actual variables like you might find in other programming languages. the value is computed where it is needed, not stored for use in other rules. for instance, you cannot set a property for an element and expect to retrieve it in a sibling's descendant's rule. the property is only set for the matching selector and its descendants, like any normal css. custo...
Value definition syntax - CSS: Cascading Style Sheets
separate component that are of the same type, but belong to different properties. both symbols appear literally in a value definition. data types basic data types some kind of data are used throughout css, and are defined once for all values in the specification. called basic data types, they are represented with their name surrounded by the symbol '<' and '>': <angle>, <string>, … non-terminal data types less common data types, called non-terminal data types, are also surrounded by '<' and '>'. non-terminal data types are of two kinds: data types sharing the same name of a property, put between quotes. in this case, the data type shares the same set of values as the property. they are often used in the definition of shorthand properties. data type not sharing the same name of ...
Visual formatting model - CSS: Cascading Style Sheets
ation box generation is the part of the css visual formatting model that creates boxes from the document's elements. generated boxes are of different types, which affect their visual formatting. the type of the box generated depends on the value of the css display property. initially defined in css2, the display property is extended in the css display module level 3. in addition, some of the terminologies around the display have been updated and clarified in the years since css2. css takes your source document and renders it onto a canvas. to do this, it generates an intermediary structure, the box tree, which represents the formatting structure of the rendered document. each box in the box tree represents its corresponding element (or pseudo-element) in space and/or time on the canvas, wh...
Actual value - CSS: Cascading Style Sheets
is the used value of that property after any necessary approximations have been applied. for example, a user agent that can only render borders with a whole-number pixel width may round the thickness of the border to the nearest integer. 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. next, the computed value is calculated according to the specification (for example, a span with position: absolute will have its computed display changed to block). then, layout is calculated, resulting in the used value. finally, the used value is transformed according to the limitations of the local environment, res...
align-content - CSS: Cascading Style Sheets
t: center; /* can be changed in the live sample */ background-color: #8c8c8c; } .flex { display: flex; flex-wrap: wrap; } .grid { display: grid; grid-template-columns: repeat(auto-fill, 50px); } div > div { box-sizing: border-box; border: 2px solid #8c8c8c; width: 50px; display: flex; align-items: center; justify-content: center; } #item1 { background-color: #8cffa0; min-height: 30px; } #item2 { background-color: #a0c8ff; min-height: 50px; } #item3 { background-color: #ffa08c; min-height: 40px; } #item4 { background-color: #ffff8c; min-height: 60px; } #item5 { background-color: #ff8cff; min-height: 70px; } #item6 { background-color: #8cffff; min-height: 50px; font-size: 30px; } select { font-size: 16px; } .row { margin-top: 10px; ...
align-items - CSS: Cascading Style Sheets
s: center; /* can be changed in the live sample */ background-color: #8c8c8c; } .flex { display: flex; flex-wrap: wrap; } .grid { display: grid; grid-template-columns: repeat(auto-fill, 50px); } div > div { box-sizing: border-box; border: 2px solid #8c8c8c; width: 50px; display: flex; align-items: center; justify-content: center; } #item1 { background-color: #8cffa0; min-height: 30px; } #item2 { background-color: #a0c8ff; min-height: 50px; } #item3 { background-color: #ffa08c; min-height: 40px; } #item4 { background-color: #ffff8c; min-height: 60px; } #item5 { background-color: #ff8cff; min-height: 70px; } #item6 { background-color: #8cffff; min-height: 50px; font-size: 30px; } select { font-size: 16px; } .row { margin-top: 10px; ...
align-self - CSS: Cascading Style Sheets
ed as if the alignment mode were start. unsafe regardless of the relative sizes of the item and alignment container, the given alignment value is honored. formal definition initial valueautoapplies toflex items, grid items, and absolutely-positioned boxesinheritednocomputed valueauto computes to itself on absolutely-positioned elements, and to the computed value of align-items on the parent (minus any legacy keywords) on all other boxes, or start if the box has no parent. its behavior depends on the layout model, as described for justify-self. otherwise the specified value.animation typediscrete formal syntax auto | normal | stretch | <baseline-position> | <overflow-position>? <self-position>where <baseline-position> = [ first | last ]? baseline<overflow-position> = unsafe | safe<self-...
animation-name - CSS: Cascading Style Sheets
ng-vertically; /* multiple animations */ animation-name: test1, animation4; animation-name: none, -moz-specific, sliding; /* global values */ animation-name: initial animation-name: inherit animation-name: unset values none a special keyword denoting no keyframes. it can be used to deactivate an animation without changing the ordering of the other identifiers, or to deactivate animations coming from the cascade. <custom-ident> a name identifying the animation. this identifier is composed of a combination of case-sensitive letters a to z, numbers 0 to 9, underscores (_), and/or dashes (-). the first non-dash character must be a letter. also, two dashes are forbidden at the beginning of the identifier. furthermore, the identifier can't be none, unset, initial, or inherit. note: when...
animation-play-state - CSS: Cascading Style Sheets
the animation-play-state css property sets whether an animation is running or paused. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. resuming a paused animation will start the animation from where it left off at the time it was paused, rather than starting over from the beginning of the animation sequence. syntax /* single animation */ animation-play-state: running; animation-play-state: paused; /* multiple animations */ animation-play-state: paused, running, running; /* global values */ animation-play-state: inherit; animation-play-state: initial; animation-play-state: unset; values running the animatio...
appearance (-moz-appearance, -webkit-appearance) - CSS: Cascading Style Sheets
moz-win-media-toolbox firefox removed in firefox 64. -moz-window-button-box firefox removed in firefox 64. -moz-window-button-box-maximized firefox removed in firefox 64. -moz-window-button-close firefox removed in firefox 64. -moz-window-button-maximize firefox removed in firefox 64. -moz-window-button-minimize firefox removed in firefox 64. -moz-window-button-restore firefox removed in firefox 64. -moz-window-frame-bottom firefox removed in firefox 64. -moz-window-frame-left firefox removed in firefox 64. -moz-window-frame-right firefox removed in firefox 64. -moz-window-titlebar firefox remove...
background-attachment - CSS: Cascading Style Sheets
ckground doesn't move with the element. (this is not compatible with background-clip: text.) local the background is fixed relative to the element's contents. if the element has a scrolling mechanism, the background scrolls with the element's contents, and the background painting area and background positioning area are relative to the scrollable area of the element rather than to the border framing them. scroll the background is fixed relative to the element itself and does not scroll with its contents. (it is effectively attached to the element's border.) formal definition initial valuescrollapplies toall elements. it also applies to ::first-letter and ::first-line.inheritednocomputed valueas specifiedanimation typediscrete formal syntax <attachment>#where <attachment> = scroll | f...
background-color - CSS: Cascading Style Sheets
background-image that is specified, although the color will still be visible through any transparency in the image. accessibility concerns it is important to ensure that the contrast ratio between the background color and the color of the text placed over it is high enough that people experiencing low vision conditions will be able to read the content of the page. color contrast ratio is determined by comparing the luminance of the text and background color values. in order to meet current web content accessibility guidelines (wcag), a ratio of 4.5:1 is required for text content and 3:1 for larger text such as headings. large text is defined as 18.66px and bold or larger, or 24px or larger. webaim: color contrast checker mdn understanding wcag, guideline 1.4 explanations understandin...
background-position-x - CSS: Cascading Style Sheets
hat the left edge of the background image is aligned with the left edge of the container, and a value of 100% means that the right edge of the background image is aligned with the right edge of the container, thus a value of 50% horizontally centers the background image. ...
background-position-y - CSS: Cascading Style Sheets
that the top edge of the background image is aligned with the top edge of the container, and a value of 100% means that the bottom edge of the background image is aligned with the bottom edge of the container, thus a value of 50% vertically centers the background image. ...
background-position - CSS: Cascading Style Sheets
equal to the container size for a given axis, then a percentage position for that axis will have no effect because the "container-image difference" will be zero. you will need to offset using absolute values. formal definition initial value0% 0%applies toall elements. ...
background-size - CSS: Cascading Style Sheets
cales the background image in the corresponding direction such that its intrinsic proportions are maintained. <length> stretches the image in the corresponding dimension to the specified length. negative values are not allowed. <percentage> stretches the image in the corresponding dimension to the specified percentage of the background positioning area. the background positioning area is determined by the value of background-origin (by default, the padding box). however, if the background's background-attachment value is fixed, the positioning area is instead the entire viewport. negative values are not allowed. intrinsic dimensions and proportions the computation of values depends on the image's intrinsic dimensions (width and height) and intrinsic proportions (width-to-height ratio).
background - CSS: Cascading Style Sheets
ound-position: 0% 0%background-size: auto autobackground-repeat: repeatbackground-origin: padding-boxbackground-clip: border-boxbackground-attachment: scrollbackground-color: transparentapplies toall elements. ...
<basic-shape> - CSS: Cascading Style Sheets
ve values for either radius are invalid. percentage values here are resolved against the used width (for the rx value) and the used height (for the ry value) of the reference box. the position argument defines the center of the ellipse. this defaults to center if omitted. polygon() polygon( [<fill-rule>,]? [<shape-arg> <shape-arg>]# ) <fill-rule> represents the filling rule used to determine the interior of the polygon. possible values are nonzero and evenodd. default value when omitted is nonzero. each pair argument in the list represents xi and yi - the x and y axis coordinates of the ith vertex of the polygon. path() path( [<fill-rule>,]? <string>) the optional <fill-rule> represents the filling rule used to determine the interior of the path. possible values are nonzer...
block-size - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax /* <length> values */ block-size: 300px; block-size: 25em; /* <percentage> values */ block-size: 75%; /* keyword values */ block-size: max-content; block-size: min-content; block-size: fit-content(20em); block-size: auto; /* global values */ block-size: inherit; block-size: initial; block-size: unset; if the writing mode is vertically oriented, the value of block-size relates to the width of the element; otherwise, it relates to the height of the element. a related property is inline-size, which defines the other dimension of the element. initial valuea...
border-end-end-radius - CSS: Cascading Style Sheets
corner will be an ellipse */ border-end-end-radius: 1em 2em; /* global values */ border-end-end-radius: inherit; border-end-end-radius: initial; border-end-end-radius: unset; for instance, in a horizontal-tb writing mode this property corresponds to the border-bottom-right-radius property. syntax values <length-percentage> denotes the size of the circle radius or the semi-major and semi-minor axes of the ellipse. as absolute length it can be expressed in any unit allowed by the css <length> data type. percentages for the horizontal axis refer to the width of the box, percentages for the vertical axis refer to the height of the box. negative values are invalid. formal definition initial value0applies toall elements; but user agents are not required to apply to table and inline-tab...
border-end-start-radius - CSS: Cascading Style Sheets
er will be an ellipse */ border-end-start-radius: 1em 2em; /* global values */ border-end-start-radius: inherit; border-end-start-radius: initial; border-end-start-radius: unset; for instance, in a horizontal-tb writing mode this property corresponds to the border-top-right-radius property. syntax values <length-percentage> denotes the size of the circle radius or the semi-major and semi-minor axes of the ellipse. as absolute length it can be expressed in any unit allowed by the css <length> data type. percentages for the horizontal axis refer to the width of the box, percentages for the vertical axis refer to the height of the box. negative values are invalid. formal definition initial value0applies toall elements; but user agents are not required to apply to table and inline-tab...
border-radius - CSS: Cascading Style Sheets
o use for the border in the bottom-right corner of the element's box. it is used only in the three- and four-value syntaxes. bottom-left is a <length> or a <percentage> denoting a radius to use for the border in the bottom-left corner of the element's box. it is used only in the four-value syntax. <length> denotes the size of the circle radius, or the semi-major and semi-minor axes of the ellipse, using length values. negative values are invalid. <percentage> denotes the size of the circle radius, or the semi-major and semi-minor axes of the ellipse, using percentage values. percentages for the horizontal axis refer to the width of the box; percentages for the vertical axis refer to the height of the box. negative values are invalid. for example: border-radius: ...
border-start-end-radius - CSS: Cascading Style Sheets
will be an ellipse */ border-start-end-radius: 1em 2em; /* global values */ border-start-end-radius: inherit; border-start-end-radius: initial; border-start-end-radius: unset; for instance, in a horizontal-tb writing mode this property corresponds to the border-bottom-left-radius property. syntax values <length-percentage> denotes the size of the circle radius or the semi-major and semi-minor axes of the ellipse. as absolute length it can be expressed in any unit allowed by the css <length> data type. percentages for the horizontal axis refer to the width of the box, percentages for the vertical axis refer to the height of the box. negative values are invalid. formal definition initial value0applies toall elements; but user agents are not required to apply to table and inline-tab...
border-start-start-radius - CSS: Cascading Style Sheets
be an ellipse */ border-start-start-radius: 1em 2em; /* global values */ border-start-start-radius: inherit; border-start-start-radius: initial; border-start-start-radius: unset; for instance, in a horizontal-tb writing mode this property corresponds to the border-top-left-radius property. syntax values <length-percentage> denotes the size of the circle radius or the semi-major and semi-minor axes of the ellipse. as absolute length it can be expressed in any unit allowed by the css <length> data type. percentages for the horizontal axis refer to the width of the box, percentages for the vertical axis refer to the height of the box. negative values are invalid. formal definition initial value0applies toall elements; but user agents are not required to apply to table and inline-tab...
box-flex-group - CSS: Cascading Style Sheets
the previous flex group. once there are no more flex groups, and there is still space remaining, the extra space is divided within the containing box according to the box-pack property. if the box would overflow after the preferred space of the children has been computed, then space is removed from flexible elements in a manner similar to that used when adding extra space. each flex group is examined in turn and space is removed according to the ratio of the flexibility of each element. elements do not shrink below their minimum widths. syntax the box-flex-group property is specified as any positive <integer>. formal definition initial value1applies toin-flow children of box elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <integer> examples simple u...
box-ordinal-group - CSS: Cascading Style Sheets
n the computed box-direction is normal, a box will display its elements starting from the lowest numbered ordinal group and ensure that those elements appear to the left (for horizontal boxes) or at the top (for vertical boxes) of the container. elements with the same ordinal group are flowed in the order they appear in the source document tree. in the reverse direction, the ordinal groups are examined in the same order, except the elements appear reversed. syntax the box-ordinal-group property is specified as any positive <integer>. formal definition initial value1applies tochildren of box elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <integer> examples basic usage example in an older version of the spec, box-ordinal-group was included to allow yo...
box-sizing - CSS: Cascading Style Sheets
nt's width and height. if you set an element's width to 100 pixels, that 100 pixels will include any border or padding you added, and the content box will shrink to absorb that extra width. this typically makes it much easier to size elements. note: it is often useful to set box-sizing to border-box to layout elements. this makes dealing with the sizes of elements much easier, and generally eliminates a number of pitfalls you can stumble on while laying out your content. 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. syntax the box-sizing property is specified as a single keyword chosen...
break-after - CSS: Cascading Style Sheets
k values */ break-after: avoid-region; break-after: region; /* global values */ break-after: inherit; break-after: initial; break-after: unset; each possible break point (in other words, each element boundary) is affected by three properties: the break-after value of the previous element, the break-before value of the next element, and the break-inside value of the containing element. to determine if a break must be done, the following rules are applied: if any of the three concerned values is a forced break value (always, left, right, page, column, or region), it has precedence. if more than one of them are such a break, the one of the element that appears the latest in the flow is taken (i.e., the break-before value has precedence over the break-after value, which itself has preceden...
break-before - CSS: Cascading Style Sheets
ues */ break-before: avoid-region; break-before: region; /* global values */ break-before: inherit; break-before: initial; break-before: unset; each possible break point (in other words, each element boundary) is affected by three properties: the break-after value of the previous element, the break-before value of the next element, and the break-inside value of the containing element. to determine if a break must be done, the following rules are applied: if any of the three concerned values is a forced break value (always, left, right, page, column, or region), it has precedence. if more than one of them are such a break, the one of the element that appears the latest in the flow is taken (i.e., the break-before value has precedence over the break-after value, which itself has preceden...
break-inside - CSS: Cascading Style Sheets
break-inside: avoid-column; break-inside: avoid-region; /* global values */ break-inside: inherit; break-inside: initial; break-inside: unset; each possible break point (in other words, each element boundary) is affected by three properties: the break-after value of the previous element, the break-before value of the next element, and the break-inside value of the containing element. to determine if a break must be done, the following rules are applied: if any of the three concerned values is a forced break value (always, left, right, page, column, or region), it has precedence. if more than one of them are such a break, the value of the element that appears the latest in the flow is used. thus, the break-before value has precedence over the break-after value, which in turn has preced...
calc() - CSS: Cascading Style Sheets
Web › CSS › calc
's look at some css: input { padding: 2px; display: block; width: calc(100% - 1em); } #formbox { width: calc(100% / 6); border: 1px solid black; padding: 4px; } here, the form itself is established to use 1/6 of the available window width. then, to ensure that input fields retain an appropriate size, we use calc() again to establish that they should be the width of their container minus 1em. then, the following html makes use of this css: <form> <div id="formbox"> <label>type something:</label> <input type="text"> </div> </form> nested calc() with css variables you can also use calc() with css variables. consider the following code: .foo { --widtha: 100px; --widthb: calc(var(--widtha) / 2); --widthc: calc(var(--widthb) / 2); width: var(--widthc); } afte...
clip-path - CSS: Cascading Style Sheets
Web › CSS › clip-path
s="container viewbox"> <svg viewbox="0 0 192 192"> <g class="none"> <rect x="24" y="24" width="144" height="144" /> <text x="96" y="91">i love</text> <text x="96" y="109" class="em">clipping</text> </g> </svg> </div> </div> </div> <div class="note">clip-path: url(#mypath)<br><br> assuming the following clippath definition: <pre> &lt;svg&gt; &lt;clippath id="mypath" clippathunits="objectboundingbox"&gt; &lt;path d="m0.5,1 c 0.5,1,0,0.7,0,0.3 a 0.25,0.25,1,1,1,0.5,0.3 a 0.25,0.25,1,1,1,1,0.3 c 1,0.7,0.5,1,0.5,1 z" /&gt; &lt;/clippath&gt; &lt;/svg&gt;</pre> </div> <div class="row"> <div class="cell"> <span>html</span> <div ...
color-adjust - CSS: Cascading Style Sheets
syntax color-adjust: economy; color-adjust: exact; the color-adjust property's value must be one of the following keywords. ...
color - CSS: Cascading Style Sheets
Web › CSS › color
tually a type of <image>. values <color> sets the color of the textual and decorative parts of the element. accessibility concerns it is important to ensure that the contrast ratio between the color of the text and the background the text is placed over is high enough that people experiencing low vision conditions will be able to read the content of the page. color contrast ratio is determined by comparing the luminosity of the text and background color values. in order to meet current web content accessibility guidelines (wcag), a ratio of 4.5:1 is required for text content and 3:1 for larger text such as headings. large text is defined as 18.66px and bold or larger, or 24px or larger. webaim: color contrast checker mdn understanding wcag, guideline 1.4 explanations understandi...
column-count - CSS: Cascading Style Sheets
d in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax /* keyword value */ column-count: auto; /* <integer> value */ column-count: 3; /* global values */ column-count: inherit; column-count: initial; column-count: unset; values auto the number of columns is determined by other css properties, such as column-width. <integer> is a strictly positive <integer> describing the ideal number of columns into which the content of the element will be flowed. if the column-width is also set to a non-auto value, it merely indicates the maximum allowed number of columns. formal definition initial valueautoapplies toblock containers except table wrapper boxesinherited...
Computed value - CSS: Cascading Style Sheets
rty's computed value typically involves converting relative values (such as those in em units or percentages) to absolute values. for example, if an element has specified values font-size: 16px and padding-top: 2em, then the computed value of padding-top is 32px (double the font size). however, for some properties (those where percentages are relative to something that may require layout to determine, such as width, margin-right, text-indent, and top), percentage-specified values turn into percentage-computed values. additionally, unitless numbers specified on the line-height property become the computed value, as specified. the relative values that remain in the computed value become absolute when the used value is determined. note: the getcomputedstyle() dom api returns the resolved valu...
conic-gradient() - CSS: Cascading Style Sheets
ient syntax provides for positioning the center of the gradient anywhere within, or even outside, the image. the values for the position are similar to the syntax for 2-value background-position. the gradient arc is the circumference of the gradient. the starting point of the gradient or arc is north, or 12:00pm. the gradient is then rotated by the from angle. the colors of the gradient are determined by the angled color stops, their starting points, ending points, and, in between, and optional angled color-stop points. the transitions between colors can be altered with color hints between adjacent colors' color stops. customizing gradients by adding more angled color-stop points on the gradient arc, you can create a highly customized transition between multiple colors. a color-stop's posi...
contain - CSS: Cascading Style Sheets
Web › CSS › contain
nt renders as normal, with no containment applied. strict indicates that all containment rules except style are applied to the element. this is equivalent to contain: size layout paint. content indicates that all containment rules except size and style are applied to the element. this is equivalent to contain: layout paint. size indicates that the element can be sized without the need to examine its descendants' sizes. layout indicates that nothing outside the element may affect its internal layout and vice versa. style indicates that, for properties that can have effects on more than just an element and its descendants, those effects don't escape the containing element. note that this value is marked "at-risk" in the spec and may not be supported everywhere. paint indicates that ...
counter-increment - CSS: Cascading Style Sheets
you may specify as many counters to increment as you want, with each name or name-number pair separated by a space. the keyword value none. values <custom-ident> the name of the counter to increment. <integer> the value to add to the counter. defaults to 1 if not specified. none no counter must be incremented. this is used as the defau...
counter-reset - CSS: Cascading Style Sheets
you may specify as many counters to reset as you want, with each name or name-number pair separated by a space. the keyword value none. values <custom-ident> the name of the counter to reset. <integer> the value to reset the counter to on each occurrence of the element. defaults to 0 if not specified. none no counter reset is to be per...
counter-set - CSS: Cascading Style Sheets
you may specify as many counters to reset as you want, with each name or name-number pair separated by a space. the keyword value none. values <custom-ident> the name of the counter to set. <integer> the value to set the counter to on each occurrence of the element. defaults to 0 if not specified. if there isn't currently a counter of th...
<dimension> - CSS: Cascading Style Sheets
Web › CSS › dimension
is abbreviated "s" not "sec". specifications specification status comment css values and units module level 4the definition of '<dimension>' in that specification. editor's draft adds cap, ic, lh, rlh, vi, vb css values and units module level 3the definition of '<dimension>' in that specification. candidate recommendation adds ch, rem, vw, vw, vmin, vmax, q css level 2 (revision 1)the definition of '<dimension>' in that specification. recommendation defined under numbers and length css level 1the definition of '<dimension>' in that specification. recommendation initial definition under "length units" ...
<display-inside> - CSS: Cascading Style Sheets
these keywords are used as values of the display property, and can be used for legacy purposes as a single keyword, or as defined in the level 3 specification alongside a value from the <display-outside> keywords. syntax valid <display-inside> values: flow the element lays out its contents using flow layout (block-and-inline layout). if its outer display type is inline or run-in, and it is participating in a block or inline formatting context, then it generates an inline box. ...
display - CSS: Cascading Style Sheets
Web › CSS › display
et the inner value to flow. this will result in expected behavior; for example if you specify an element to be block, you would expect that the children of that element would participate in block and inline normal flow layout. inside <display-inside> these keywords specify the element’s inner display type, which defines the type of formatting context that its contents are laid out in (assuming it is a non-replaced element). valid <display-inside> values: flow the element lays out its contents using flow layout (block-and-inline layout). if its outer display type is inline or run-in, and it is participating in a block or inline formatting context, then it generates an inline box. otherwise it generates a block container box. depending on the value of other properties (such a...
drop-shadow() - CSS: Cascading Style Sheets
creates a shadow that conforms to the shape (alpha channel) of the image itself. syntax drop-shadow(offset-x offset-y blur-radius color) the drop-shadow() function accepts a parameter of type <shadow> (defined in the box-shadow property), with the exception that the inset keyword and spread parameters are not allowed. parameters offset-x offset-y (required) two <length> values that determine the shadow offset. offset-x specifies the horizontal distance, where negative values place the shadow to the left of the element. offset-y specifies the vertical distance, where negative values place the shadow above the element. if both values are 0, the shadow is placed directly behind the element. blur-radius (optional) the shadow's blur radius, specified as a <length>. the larger the value...
hue-rotate() - CSS: Cascading Style Sheets
se clone https://github.com/mdn/interactive-examples and send us a pull request. syntax hue-rotate(angle) parameters angle the relative change in hue of the input sample, specified as an <angle>. a value of 0deg leaves the input unchanged. a positive hue rotation increases the hue value, while a negative rotation decreases the hue value. the lacuna value for interpolation is 0. there is no minimum or maximum value; hue-rotate(ndeg) evaluates to n modulo 360. examples hue-rotate(-90deg) /* same as 270deg rotation */ hue-rotate(0deg) /* no effect */ hue-rotate(90deg) /* 90deg rotation */ hue-rotate(.5turn) /* 180deg rotation */ hue-rotate(405deg) /* same as 45deg rotation */ specifications specification status filter effects module level 1the defini...
flex-grow - CSS: Cascading Style Sheets
Web › CSS › flex-grow
single <number>. values <number> see <number>. negative values are invalid. defaults to 0. description this property specifies how much of the remaining space in the flex container should be assigned to the item (the flex grow factor). the main size is either width or height of the item which is dependent on the flex-direction value. the remaining space is the size of the flex container minus the size of all flex items' sizes together. if all sibling items have the same flex grow factor, then all items will receive the same share of remaining space, otherwise it is distributed according to the ratio defined by the different flex grow factors. flex-grow is used alongside the other flex properties flex-shrink and flex-basis, and normally defined using the flex shorthand to ensure all...
font-kerning - CSS: Cascading Style Sheets
kerning defines how letters are spaced. in well-kerned fonts, this feature makes character spacing more uniform and pleasant to read than it would otherwise be. in the image below, for instance, the examples on the left do not use kerning, while the ones on the right do: syntax the font-kerning property is specified as one of the keyword values listed below. values auto the browser determines whether font kerning should be used or not. for example, some browsers will disable kerning on small fonts, since applying it could harm the readability of text. normal font kerning information stored in the font must be applied. none font kerning information stored in the font is disabled. formal definition initial valueautoapplies toall elements. it also applies to ::first-letter and :...
font-style - CSS: Cascading Style Sheets
the "slnt" variation is used to implement varying slant angles for oblique, and the "ital" variation with a value of 1 is used to implement italic values. see font-variation-settings. for the example below to work, you'll need a browser that supports the css fonts level 4 syntax in which font-style: oblique can accept an <angle>. ...
font-variant-numeric - CSS: Cascading Style Sheets
opentype values pnum. tabular-nums activating the set of figures where numbers are all of the same size, allowing them to be easily aligned like in tables. it corresponds to the opentype values tnum. <numeric-fraction-values> these values controls the glyphs used to display fractions. two values are possible: diagonal-fractions activating the set of figures where the numerator and denominator are made smaller and separated by a slash. it corresponds to the opentype values frac. stacked-fractions activating the set of figures where the numerator and denominator are made smaller, stacked and separated by a horizontal line. it corresponds to the opentype values afrc. formal definition initial valuenormalapplies toall elements. it also applies to ::first-letter and ::first-lin...
font-variation-settings - CSS: Cascading Style Sheets
t" (slant) font-style: oblique + angle "ital" font-style: italic "opsz" font-optical-sizing custom axes can be anything the font designer wants to vary in their font, for example ascender or descender heights, the size of serifs, or anything else they can imagine. any axis can be used as long as it is given a unique 4-character axis. some will end up becoming more common, and may even become registered over time. note: registered axis tags are identified using lower-case tags, whereas custom axes should be given upper-case tags. note that font designers aren't forced follow this practice in any way, and some won't. the important takeaway here is that axis tags are case-sensitive. in order to use variable fonts on your operating system, you need t...
hyphens - CSS: Cascading Style Sheets
Web › CSS › hyphens
specified points within the text, or let the browser automatically insert hyphens where appropriate. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. hyphenation rules are language-specific. in html, the language is determined by the lang attribute, and browsers will hyphenate only if this attribute is present and the appropriate hyphenation dictionary is available. in xml, the xml:lang attribute must be used. note: the rules defining how hyphenation is performed are not explicitly defined by the specification, so the exact hyphenation may vary from browser to browser. syntax /* keyword values */ hyphens: none; ...
image-set() - CSS: Cascading Style Sheets
Web › CSS › image-set
resolution declaration — from which the browser picks the most appropriate for the device and settings. resolution can be used as a proxy for filesize — a user agent on a slow mobile connection with a high-resolution screen may prefer to receive lower-resolution images rather than waiting for a higher resolution image to load. image-set() allows the author to provide options rather than determining what each individual user needs. syntax image-set() = image-set( <image-set-option># ) where <image-set-option> = [ <image> | <string> ] <resolution> and <string> is an <url> values most commonly you'll see an url() <string> value, but the <image> can be any image type except for an image set. the image-set() function can not be nested inside another image-set() function. <resoluti...
inline-size - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax /* <length> values */ inline-size: 300px; inline-size: 25em; /* <percentage> values */ inline-size: 75%; /* keyword values */ inline-size: max-content; inline-size: min-content; inline-size: fit-content(20em); inline-size: auto; /* global values */ inline-size: inherit; inline-size: initial; inline-size: unset; if the writing mode is vertically oriented, the value of inline-size relates to the height of the element; otherwise, it relates to the width of the element. a related property is block-size, which defines the other dimension of the element. values t...
isolation - CSS: Cascading Style Sheets
Web › CSS › isolation
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. this property is especially helpful when used in conjunction with mix-blend-mode. syntax /* keyword values */ isolation: auto; isolation: isolate; /* global values */ isolation: inherit; isolation: initial; isolation: unset; the isolation property is specified as one of the keyword values listed below. values auto a new stacking context is created only if one of the properties applied to the element requires it. ...
letter-spacing - CSS: Cascading Style Sheets
will make the word(s) the styling is applied to unreadable. for text styled with a very large positive value, the letters will be so far apart that the word(s) will appear like a series of individual, unconnected letters. for text styled with a very large negative value, the letters will overlap each other to the point where the word(s) may be unrecognizable. legible letter-spacing must be determined on a case-by-case basis, as different font families have different character widths. there is no one value that can ensure all font families automatically maintain their legibility. mdn understanding wcag, guideline 1.4 explanations understanding success criterion 1.4.8 | w3c understanding wcag 2.0 formal definition initial valuenormalapplies toall elements. it also applies to ::first-l...
linear-gradient() - CSS: Cascading Style Sheets
points. each point on the axis is a distinct color; to create a smooth gradient, the linear-gradient() function draws a series of colored lines perpendicular to the gradient line, each one matching the color of the point where it intersects the gradient line. the gradient line is defined by the center of the box containing the gradient image and by an angle. the colors of the gradient are determined by two or more points: the starting point, the ending point, and, in between, optional color-stop points. the starting point is the location on the gradient line where the first color begins. the ending point is the point where the last color ends. each of these two points is defined by the intersection of the gradient line with a perpendicular line passing from the box corner which is in the ...
margin-left - CSS: Cascading Style Sheets
n-left: unset; the margin-left property is specified as the keyword auto, or a <length>, or a <percentage>. its value can be positive, zero, or negative. values <length> the size of the margin as a fixed value. <percentage> the size of the margin as a percentage, relative to the width of the containing block. auto the left margin receives a share of the unused horizontal space, as determined mainly by the layout mode that is used. if the values of margin-left and margin-right are both auto, the calculated space is evenly distributed. this table summarizes the different cases: value of display value of float value of position computed value of auto comment inline, inline-block, inline-table any static or relative 0 inlin...
margin-right - CSS: Cascading Style Sheets
ight: unset; the margin-right property is specified as the keyword auto, or a <length>, or a <percentage>. its value can be positive, zero, or negative. values <length> the size of the margin as a fixed value. <percentage> the size of the margin as a percentage, relative to the width of the containing block. auto the right margin receives a share of the unused horizontal space, as determined mainly by the layout mode that is used. if the values of margin-left and margin-right are both auto, the calculated space is evenly distributed. this table summarizes the different cases: value of display value of float value of position computed value of auto comment inline, inline-block, inline-table any static or relative 0 inlin...
mask-border-slice - CSS: Cascading Style Sheets
e to form the corners of the final border image. zones 5-8 are edge regions. these are repeated, scaled, or otherwise modified in the final border image to match the dimensions of the element. zone 9 is the middle region. it is discarded by default, but is used like a background image if the keyword fill is set. the mask-border-repeat, mask-border-width, and mask-border-outset properties determine how these regions are used to form the final mask border. formal definition initial value0applies toall elements; in svg, it applies to container elements excluding the defs element and all graphics elementsinheritednopercentagesrefer to size of the mask border imagecomputed valueas specifiedanimation typediscrete formal syntax <number-percentage>{1,4} fill?where <number-percentage> = <numbe...
mask-border - CSS: Cascading Style Sheets
er-outset'> the distance of the border mask from the element's outside edge. up to four values may be specified. see mask-border-outset. <'mask-border-repeat'> defines how the edge regions of the source image are adjusted to fit the dimensions of the border mask. up to two values may be specified. see mask-border-repeat. <'mask-border-mode'> defines whether the source image is treated as a luminance mask or alpha mask. see mask-border-mode. formal definition initial valueas each of the properties of the shorthand:mask-border-mode: alphamask-border-outset: 0mask-border-repeat: stretchmask-border-slice: 0mask-border-source: nonemask-border-width: autoapplies toall elements; in svg, it applies to container elements excluding the defs element and all graphics elementsinheritednopercentage...
mask-clip - CSS: Cascading Style Sheets
Web › CSS › mask-clip
the painted content of an element must be restricted to this area. ...
mask-origin - CSS: Cascading Style Sheets
mask-origin: unset; for elements rendered as a single box, this property specifies the mask positioning area. in other words, this property specifies the origin position of an image specified by the mask-image css property. for elements rendered as multiple boxes, such as inline boxes on several lines or boxes on several pages, it specifies which boxes box-decoration-break operates upon to determine the mask positioning area. syntax one or more of the keyword values listed below, separated by commas. values content-box the position is relative to the content box. padding-box the position is relative to the padding box. for single boxes 0 0 is the upper left corner of the padding edge, 100% 100% is the lower right corner. border-box the position is relative to the border box. mar...
mask-position - CSS: Cascading Style Sheets
r values representing a 2d position regarding the edges of the element's box. relative or absolute offsets can be given. note that the position can be set outside of the element's box. ...
max-inline-size - CSS: Cascading Style Sheets
stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax /* <length> values */ max-inline-size: 300px; max-inline-size: 25em; /* <percentage> values */ max-inline-size: 75%; /* keyword values */ max-inline-size: auto; max-inline-size: max-content; max-inline-size: min-content; max-inline-size: fit-content(20em); /* global values */ max-inline-size: inherit; max-inline-size: initial; max-inline-size: unset; values the max-inline-size property takes the same values as the max-width and max-height properties. formal definition initial value0applies tosame as width and heightinheritednopercentagesinline-size of containing blockcomputed valuesame as max-width...
<number> - CSS: Cascading Style Sheets
Web › CSS › number
actional component. syntax the syntax of <number> extends the syntax of <integer>. a fractional value is represented by a . followed by one or more decimal digits, and may be appended to an integer. there is no unit associated with numbers. interpolation when animated, values of the <number> css data type are interpolated as real, floating-point numbers. the speed of the interpolation is determined by the timing function associated with the animation. examples valid numbers 12 a raw <integer> is also a <number>. 4.01 positive fraction -456.8 negative fraction 0.0 zero +0.0 zero, with a leading + -0.0 zero, with a leading - .60 fractional number without a leading zero 10e3 scientific notation -3.4e-2 complicated scientific no...
offset-path - CSS: Cascading Style Sheets
pse(), inset(), polygon(), or path(). path() a path string defined with svg coordinate syntax. none specifies no motion path at all. description this property defines a path an animated element can follow. an offset path is either a specified path with one or multiple sub-paths or the geometry of a not-styled basic shape. the element’s exact position on the offset path is determined by the offset-distance property. each shape or path must define an initial position for the computed value of 0 for offset-distance and an initial direction which specifies the rotation of the object to the initial position. early versions of the spec called this property motion-path. it was changed to offset-path because the property describes static positions, not motion. formal definition ...
opacity - CSS: Cascading Style Sheets
Web › CSS › opacity
, use the background property instead. for example: background: rgba(0, 0, 0, 0.4); accessibility concerns if text opacity is adjusted, it is important to ensure that the contrast ratio between the color of the text and the background the text is placed over is high enough that people experiencing low vision conditions will be able to read the content of the page. color contrast ratio is determined by comparing the luminosity of the opacity-adjusted text and background color values. in order to meet current web content accessibility guidelines (wcag), a ratio of 4.5:1 is required for text content and 3:1 for larger text such as headings. large text is defined as 18.66px and bold or larger, or 24px or larger. webaim: color contrast checker mdn understanding wcag, guideline 1.4 explanat...
outline-color - CSS: Cascading Style Sheets
ppearance of an outline. accessibility concerns custom focus styles commonly involve making adjustments to the outline property. if the color of the outline is adjusted, it is important to ensure that the contrast ratio between it and the background the outline is placed over is high enough that people experiencing low vision conditions will be able to perceive it. color contrast ratio is determined by comparing the luminosity of the text and background color values. in order to meet current web content accessibility guidelines (wcag), a ratio of 4.5:1 is required for text content and 3:1 for larger text such as headings. large text is defined as 18.66px and bold or larger, or 24px or larger. webaim: color contrast checker mdn understanding wcag, guideline 1.4 explanations understandi...
outline-style - CSS: Cascading Style Sheets
-width is the sum of the two lines and the space between them. groove the outline looks as though it were carved into the page. ridge the opposite of groove: the outline looks as though it were extruded from the page. inset the outline makes the box look as though it were embedded in the page. outset the opposite of inset: the outline makes the box look as though it were coming out of the page. formal definition initial valuenoneapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | <'border-style'> examples setting outline style to auto the auto value indicates a custom outline style — typically a style [that] is either a user interface default for the platform, or perhaps a style that is richer than can be des...
overflow-anchor - CSS: Cascading Style Sheets
scroll anchoring behavior is enabled by default in any browser that supports it. therefore, changing the value of this property is typically only required if you are experiencing problems with scroll anchoring in a document or part of a document and need to turn the behavior off. ...
overflow-wrap - CSS: Cascading Style Sheets
al word break points (such as a space between two words). anywhere to prevent overflow, an otherwise unbreakable string of characters — like a long word or url — may be broken at any point if there are no otherwise-acceptable break points in the line. no hyphenation character is inserted at the break point. soft wrap opportunities introduced by the word break are considered when calculating min-content intrinsic sizes. break-word the same as the anywhere value, with normally unbreakable words allowed to be broken at arbitrary points if there are no otherwise acceptable break points in the line, but soft wrap opportunities introduced by the word break are not considered when calculating min-content intrinsic sizes. formal definition initial valuenormalapplies tonon-replaced inline e...
paint-order - CSS: Cascading Style Sheets
lt order relative to one another. when two values are specified, they will be painted in the order they are specified in, followed by the unspecified one. note: in the case of this property, markers are only appropriate when drawing svg shapes involving the use of the marker-* properties (e.g. marker-start) and <marker> element. they do not apply to html text, so in that case, you can only determine the order of stroke and fill. values normal paint the different items in normal paint order. stroke, fill, markers specify some or all of these values in the order you want them to be painted in. formal definition initial valuenormalapplies totext elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax normal | [ fill | stroke | markers ] examples reve...
<percentage> - CSS: Cascading Style Sheets
<number> followed by the percentage sign (%). optionally, it may be preceded by a single + or - sign, although negative values are not valid for all properties. as with all css dimensions, there is no space between the symbol and the number. interpolation when animated, values of the <percentage> data type are interpolated as real, floating-point numbers. the speed of the interpolation is determined by the timing function associated with the animation. examples width and margin-left <div style="background-color:navy;"> <div style="width:50%; margin-left:20%; background-color:chartreuse;"> width: 50%, left margin: 20% </div> <div style="width:30%; margin-left:60%; background-color:pink;"> width: 30%, left margin: 60% </div> </div> the above html will output: font-si...
perspective-origin - CSS: Cascading Style Sheets
it is used as the vanishing point by the perspective property. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. the perspective-origin and perspective properties are attached to the parent of a child transformed in 3-dimensional space, unlike the perspective() transform function which is placed on the element being transformed. ...
place-self - CSS: Cascading Style Sheets
along the cross axis. formal definition initial valueas each of the properties of the shorthand:align-self: autojustify-self: autoapplies toblock-level boxes, absolutely-positioned boxes, and grid itemsinheritednocomputed valueas each of the properties of the shorthand:align-self: auto computes to itself on absolutely-positioned elements, and to the computed value of align-items on the parent (minus any legacy keywords) on all other boxes, or start if the box has no parent. its behavior depends on the layout model, as described for justify-self. otherwise the specified value.justify-self: as specifiedanimation typediscrete formal syntax <'align-self'> <'justify-self'>? examples simple demonstration in the following example we have a simple 2 x 2 grid layout. initially the grid contain...
radial-gradient() - CSS: Cascading Style Sheets
r to the ending shape (and potentially beyond). the ending shape may be either a circle or an ellipse. color-stop points are positioned on a virtual gradient ray that extends horizontally from the center towards the right. percentage-based color-stop positions are relative to the intersection between the ending shape and this gradient ray, which represents 100%. each shape is a single color determined by the color on the gradient ray it intersects. examples simple gradient <div class="radial-gradient"></div> .radial-gradient { width: 240px; 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-...
<ratio> - CSS: Cascading Style Sheets
Web › CSS › ratio
e optional. the first number represents the width, while the second represents the height. in media queries level 4, the <ratio> date type is updated to consist of a strictly positive <number> followed by a forward slash ('/', unicode u+002f solidus) and a second strictly positive <number>. in addition a single <number> as a value is allowable. examples use in a media query @media screen and (min-aspect-ratio: 16/9) { ... } common aspect ratios ratio usage 4/3 traditional tv format in the 20th century. 16/9 modern "widescreen" tv format. 185/100 = 91/50 the most common movie format since the 1960s. 239/100 "widescreen," anamorphic movie format. specifications specification statu...
<resolution> - CSS: Cascading Style Sheets
of css in to css px, 1dppx is equivalent to 96dpi, which corresponds to the default resolution of images displayed in css as defined by image-resolution. x alias for dppx. note: although the number 0 is always the same regardless of unit, the unit may not be omitted. in other words, 0 is invalid and does not represent 0dpi, 0dpcm, or 0dppx. examples use in a media query @media print and (min-resolution: 300dpi) { ... } valid resolutions 96dpi 50.82dpcm 3dppx invalid resolutions 72 dpi spaces are not allowed between the number and the unit. ten dpi the number must use digits only. 0 the unit is required. specifications specification status comment css values and units module level 4the definition of '<resolution>' in that specificati...
row-gap (grid-row-gap) - CSS: Cascading Style Sheets
Web › CSS › row-gap
-examples and send us a pull request. css grid layout initially defined the grid-row-gap property. this prefixed property is being replaced by row-gap. however, in order to support browsers that implemented grid-row-gap and not row-gap for grid, you will need to use the prefixed property as in the interactive example above. syntax /* <length> values */ row-gap: 20px; row-gap: 1em; row-gap: 3vmin; row-gap: 0.5cm; /* <percentage> value */ row-gap: 10%; /* global values */ row-gap: inherit; row-gap: initial; row-gap: unset; values <length-percentage> is the width of the gutter separating the rows. <percentage> values are relative to the dimension of the element. formal definition initial valuenormalapplies tomulti-column elements, flex containers, grid containersinheritednopercen...
scroll-behavior - CSS: Cascading Style Sheets
syntax /* keyword values */ scroll-behavior: auto; scroll-behavior: smooth; /* global values */ scroll-behavior: inherit; scroll-behavior: initial; scroll-behavior: unset; the scroll-behavior property is specified as one of the keyword values listed below. values auto the scrolling box scrolls instantly. smooth the scrolling box scrolls in a smooth fashion using a user-agent-defined timing function over a user-agent-defined period of time. user agents should follow platform conventions, if any. formal definition initial valueautoapplies toscrolling boxesinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | smooth examples setting smooth scroll behavior html <nav> <a href="#page-1">1</a> <a href="#page-2">2</a> <a href="#page-3">3</a> </nav...
scroll-margin-block-end - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
scroll-margin-block-start - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
scroll-margin-block - CSS: Cascading Style Sheets
0px; scroll-margin-block: 1em .5em ; /* global values */ scroll-margin-block: inherit; scroll-margin-block: initial; scroll-margin-block: unset; values <length> an outset from the corresponding edge of the scroll container. description the scroll-margin values represent outsets defining the scroll snap area that is used for snapping this box to the snapport. the scroll snap area is determined by taking the transformed border box, finding its rectangular bounding box (axis-aligned in the scroll container’s coordinate space), then adding the specified outsets. formal definition initial value0applies toall elementsinheritednocomputed valueas specifiedanimation typeby computed value type formal syntax <length>{1,2} specifications specification status comment ...
scroll-margin-bottom - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
scroll-margin-inline-end - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
scroll-margin-inline-start - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. ...
scroll-margin-inline - CSS: Cascading Style Sheets
scroll-margin-inline: 1em .5em ; /* global values */ scroll-margin-inline: inherit; scroll-margin-inline: initial; scroll-margin-inline: unset; values <length> an outset from the corresponding edge of the scroll container. description the scroll-margin values represent outsets defining the scroll snap area that is used for snapping this box to the snapport. the scroll snap area is determined by taking the transformed border box, finding its rectangular bounding box (axis-aligned in the scroll container’s coordinate space), then adding the specified outsets. formal definition initial value0applies toall elementsinheritednocomputed valueas specifiedanimation typeby computed value type formal syntax <length>{1,2} examples simple demonstration this example implements something...
scroll-margin-left - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
scroll-margin-right - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
scroll-margin-top - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
scroll-padding-block-end - CSS: Cascading Style Sheets
to; /* <length> values */ scroll-padding-block-end: 10px; scroll-padding-block-end: 1em; scroll-padding-block-end: 10%; /* global values */ scroll-padding-block-end: inherit; scroll-padding-block-end: initial; scroll-padding-block-end: unset; values <length-percentage> an inwards offset from the block end edge of the scrollport, as a valid length or a percentage. auto the offset is determind by the user agent. this will generally be 0px, but a user agent is able to detect and do something else if a non-zero value is more appropriate. formal definition initial valueautoapplies toscroll containersinheritednopercentagesrelative to the scroll container's scrollportcomputed valueas specifiedanimation typeby computed value type formal syntax auto | <length-percentage>where <length-pe...
scroll-padding-block-start - CSS: Cascading Style Sheets
h> values */ scroll-padding-block-start: 10px; scroll-padding-block-start: 1em; scroll-padding-block-start: 10%; /* global values */ scroll-padding-block-start: inherit; scroll-padding-block-start: initial; scroll-padding-block-start: unset; values <length-percentage> an inwards offset from the block start edge of the scrollport, as a valid length or a percentage. auto the offset is determind by the user agent. this will generally be 0px, but a user agent is able to detect and do something else if a non-zero value is more appropriate. formal definition initial valueautoapplies toscroll containersinheritednopercentagesrelative to the scroll container's scrollportcomputed valueas specifiedanimation typeby computed value type formal syntax auto | <length-percentage>where <length-pe...
scroll-padding-block - CSS: Cascading Style Sheets
dding-block: auto; /* <length> values */ scroll-padding-block: 10px; scroll-padding-block: 1em .5em; scroll-padding-block: 10%; /* global values */ scroll-padding-block: inherit; scroll-padding-block: initial; scroll-padding-block: unset; values <length-percentage> an inwards offset from the corresponding edge of the scrollport, as a valid length or a percentage. auto the offset is determind by the user agent. this will generally be 0px, but a user agent is able to detect and do something else if a non-zero value is more appropriate. formal definition initial valueautoapplies toscroll containersinheritednopercentagesrelative to the scroll container's scrollportcomputed valueas specifiedanimation typeby computed value type formal syntax [ auto | <length-percentage> ]{1,2}where <...
scroll-padding-bottom - CSS: Cascading Style Sheets
ll-padding-bottom: auto; /* <length> values */ scroll-padding-bottom: 10px; scroll-padding-bottom: 1em; scroll-padding-bottom: 10%; /* global values */ scroll-padding-bottom: inherit; scroll-padding-bottom: initial; scroll-padding-bottom: unset; values <length-percentage> an inwards offset from the bottom edge of the scrollport, as a valid length or a percentage. auto the offset is determind by the user agent. this will generally be 0px, but a user agent is able to detect and do something else if a non-zero value is more appropriate. formal definition initial valueautoapplies toscroll containersinheritednopercentagesrelative to the scroll container's scrollportcomputed valueas specifiedanimation typeby computed value type formal syntax auto | <length-percentage>where <length-pe...
scroll-padding-inline-end - CSS: Cascading Style Sheets
<length> values */ scroll-padding-inline-end: 10px; scroll-padding-inline-end: 1em; scroll-padding-inline-end: 10%; /* global values */ scroll-padding-inline-end: inherit; scroll-padding-inline-end: initial; scroll-padding-inline-end: unset; values <length-percentage> an inwards offset from the inline end edge of the scrollport, as a valid length or a percentage. auto the offset is determind by the user agent. this will generally be 0px, but a user agent is able to detect and do something else if a non-zero value is more appropriate. formal definition initial valueautoapplies toscroll containersinheritednopercentagesrelative to the scroll container's scrollportcomputed valueas specifiedanimation typeby computed value type formal syntax auto | <length-percentage>where <length-per...
scroll-padding-inline-start - CSS: Cascading Style Sheets
es */ scroll-padding-inline-start: 10px; scroll-padding-inline-start: 1em; scroll-padding-inline-start: 10%; /* global values */ scroll-padding-inline-start: inherit; scroll-padding-inline-start: initial; scroll-padding-inline-start: unset; values <length-percentage> an inwards offset from the inline start edge of the scrollport, as a valid length or a percentage. auto the offset is determind by the user agent. this will generally be 0px, but a user agent is able to detect and do something else if a non-zero value is more appropriate. formal definition initial valueautoapplies toscroll containersinheritednopercentagesrelative to the scroll container's scrollportcomputed valueas specifiedanimation typeby computed value type formal syntax auto | <length-percentage>where <length-pe...
scroll-padding-inline - CSS: Cascading Style Sheets
nline: auto; /* <length> values */ scroll-padding-inline: 10px; scroll-padding-inline: 1em .5em; scroll-padding-inline: 10%; /* global values */ scroll-padding-inline: inherit; scroll-padding-inline: initial; scroll-padding-inline: unset; values <length-percentage> an inwards offset from the corresponding edge of the scrollport, as a valid length or a percentage. auto the offset is determind by the user agent. this will generally be 0px, but a user agent is able to detect and do something else if a non-zero value is more appropriate. formal definition initial valueautoapplies toscroll containersinheritednopercentagesrelative to the scroll container's scrollportcomputed valueas specifiedanimation typeby computed value type formal syntax [ auto | <length-percentage> ]{1,2}where <...
scroll-padding-left - CSS: Cascading Style Sheets
d values */ scroll-padding-left: auto; /* <length> values */ scroll-padding-left: 10px; scroll-padding-left: 1em; scroll-padding-left: 10%; /* global values */ scroll-padding-left: inherit; scroll-padding-left: initial; scroll-padding-left: unset; values <length-percentage> an inwards offset from the left edge of the scrollport, as a valid length or a percentage. auto the offset is determind by the user agent. this will generally be 0px, but a user agent is able to detect and do something else if a non-zero value is more appropriate. formal definition initial valueautoapplies toscroll containersinheritednopercentagesrelative to the scroll container's scrollportcomputed valueas specifiedanimation typeby computed value type formal syntax auto | <length-percentage>where <length-per...
scroll-padding-right - CSS: Cascading Style Sheets
es */ scroll-padding-right: auto; /* <length> values */ scroll-padding-right: 10px; scroll-padding-right: 1em; scroll-padding-right: 10%; /* global values */ scroll-padding-right: inherit; scroll-padding-right: initial; scroll-padding-right: unset; values <length-percentage> an inwards offset from the top edge of the scrollport, as a valid length or a percentage. auto the offset is determind by the user agent. this will generally be 0px, but a user agent is able to detect and do something else if a non-zero value is more appropriate. formal definition initial valueautoapplies toscroll containersinheritednopercentagesrelative to the scroll container's scrollportcomputed valueas specifiedanimation typeby computed value type formal syntax auto | <length-percentage>where <length-pe...
scroll-padding-top - CSS: Cascading Style Sheets
* keyword values */ scroll-padding-top: auto; /* <length> values */ scroll-padding-top: 10px; scroll-padding-top: 1em; scroll-padding-top: 10%; /* global values */ scroll-padding-top: inherit; scroll-padding-top: initial; scroll-padding-top: unset; values <length-percentage> an inwards offset from the top edge of the scrollport, as a valid length or a percentage. auto the offset is determind by the user agent. this will generally be 0px, but a user agent is able to detect and do something else if a non-zero value is more appropriate. formal definition initial valueautoapplies toscroll containersinheritednopercentagesrelative to the scroll container's scrollportcomputed valueas specifiedanimation typeby computed value type formal syntax auto | <length-percentage>where <length-pe...
scroll-padding - CSS: Cascading Style Sheets
/* keyword values */ scroll-padding: auto; /* <length> values */ scroll-padding: 10px; scroll-padding: 1em .5em 1em 1em; scroll-padding: 10%; /* global values */ scroll-padding: inherit; scroll-padding: initial; scroll-padding: unset; values <length-percentage> an inwards offset from the corresponding edge of the scrollport, as a valid <length> or a <percentage>. auto the offset is determind by the user agent. this will generally be 0px, but the user agent is free to detect and do something else if a non-zero value is more appropriate. formal definition initial valueautoapplies toscroll containersinheritednopercentagesrelative to the scroll container's scrollportcomputed valueas specifiedanimation typeby computed value type formal syntax [ auto | <length-percentage> ]{1,4}where...
scroll-snap-stop - CSS: Cascading Style Sheets
nap positions. always the scroll container must not "pass over" a possible snap position; and must snap to the first of this elements' snap positions. formal definition initial valuenormalapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax normal | always examples snapping in different axes this example is duplicated from scroll-snap-type with minor variances. css /* setup */ :root, body { height: 100%; display: flex; align-items: center; justify-content: space-between; flex-flow: column nowrap; font-family: monospace; } .container { display: flex; overflow: auto; outline: 1px dashed lightgray; flex: none; } .container.x { width: 100%; height: 128px; flex-flow: row nowrap; } .container.y { width: 256px; he...
shape-image-threshold - CSS: Cascading Style Sheets
mage as the value for shape-outside. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. any pixels whose alpha component's value is greater than the threshold are considered to be part of the shape for the purposes of determining its boundaries. for example, a value of 0.5 means that the shape will enclose all the pixels that are more than 50% opaque. /* <number> value */ shape-image-threshold: 0.7; /* global values */ shape-image-threshold: inherit; shape-image-threshold: initial; shape-image-threshold: unset; syntax values <alpha-value> sets the threshold used for extracting a shape from an image. the shape ...
<shape> - CSS: Cascading Style Sheets
Web › CSS › shape
gle relative to the top border of the element's box. left is a <length> representing the offset for the left of the rectangle relative to the left border of the element's box. interpolation when animated, values of the <shape> data type are interpolated over their top, right, bottom, and left components, each treated as a real, floating-point number. the speed of the interpolation is determined by the timing function associated with the animation. example img.clip04 { clip: rect(10px, 20px, 20px, 10px); } specifications specification status comment css level 2 (revision 1)the definition of '<shape>' in that specification. recommendation defines with the clip property. browser compatibility the compatibility table on this page is generat...
Specified value - CSS: Cascading Style Sheets
if the document's style sheet doesn't specify a value but it is an inherited property, the value will be taken from the parent element. if none of the above pertain, the element's initial value will be used. ...
table-layout - CSS: Cascading Style Sheets
the width of the first row of cells. cells in subsequent rows do not affect column widths. under the "fixed" layout method, the entire table can be rendered once the first table row has been downloaded and analyzed. this can speed up rendering time over the "automatic" layout method, but subsequent cell content might not fit in the column widths provided. cells use the overflow property to determine whether to clip any overflowing content, but only if the table has a known width; otherwise, they won't overflow the cells. formal definition initial valueautoapplies totable and inline-table elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | fixed examples fixed-width tables with text-overflow this example uses a fixed table layout, combined with th...
text-decoration-color - CSS: Cascading Style Sheets
; text-decoration-color: unset; values <color> the color of the line decoration. accessibility concerns it is important to ensure that the contrast ratio between the color of the text, the background the text is placed over, and the text decoration line is high enough that people experiencing low vision conditions will be able to read the content of the page. color contrast ratio is determined by comparing the luminosity of the text and background color values. color alone should not be used to convey meaning. for example, change of text and text-decoration-color alone is not enough to indicate a link has focus. webaim: color contrast checker mdn understanding wcag, guideline 1.4 explanations understanding success criterion 1.4.3 | w3c understanding wcag 2.0 formal definition...
text-decoration-line - CSS: Cascading Style Sheets
ied as none, or one or more space-separated values from the list below. values none produces no text decoration. underline each line of text has a decorative line beneath it. overline each line of text has a decorative line above it. line-through each line of text has a decorative line going through its middle. blink the text blinks (alternates between visible and invisible). conforming user agents may simply not blink the text. this value is deprecated in favor of css animations. formal definition initial valuenoneapplies toall elements. it also applies to ::first-letter and ::first-line.inheritednocomputed valueas specifiedanimation typediscrete formal syntax none | [ underline | overline | line-through | blink ] | spelling-error | grammar-error examples <p class="wavy...
text-decoration-thickness - CSS: Cascading Style Sheets
oosing an appropriate thickness. <length> specifies the thickness of the text decoration line as a <length>, overriding the font file suggestion or the browser default. <percentage> specifies the thickness of the text decoration line as a <percentage> of 1em in the current font. a percentage inherits as a relative value, and so therefore scales with changes in the font. the browser must use a minimum of 1 device pixel. for a given application of this property, the thickness is constant across the whole box it is applied to, even if there are child elements with a different font size. formal definition initial valueautoapplies toall elements. it also applies to ::first-letter and ::first-line.inheritednopercentagesrefer to the font size of the element itselfcomputed valueas specifiedani...
text-overflow - CSS: Cascading Style Sheets
the string itself, it is clipped. fade this keyword clips the overflowing inline content and applies a fade-out effect near the edge of the line box with complete transparency at the edge. fade( <length> | <percentage> ) this function clips the overflowing inline content and applies a fade-out effect near the edge of the line box with complete transparency at the edge. the argument determines the distance over which the fade effect is applied. the <percentage> is resolved against the width of the line box. values lower than 0 are clipped to 0. values greater than the width of the line box are clipped to the width of the line box. formal definition initial valueclipapplies toblock container elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax [ clip ...
text-rendering - CSS: Cascading Style Sheets
geometric precision. this enables kerning and optional ligatures. geometricprecision the browser emphasizes geometric precision over rendering speed and legibility. certain aspects of fonts — such as kerning — don't scale linearly. so this value can make text using those fonts look good. in svg, when text is scaled up or down, browsers calculate the final size of the text (which is determined by the specified font size and the applied scale) and request a font of that computed size from the platform's font system. but if you request a font size of, say, 9 with a scale of 140%, the resulting font size of 12.6 doesn't explicitly exist in the font system, so the browser rounds the font size to 12 instead. this results in stair-step scaling of text. but the geometricprecision property...
top - CSS: Cascading Style Sheets
Web › CSS › top
working draft adds behavior for sticky positioning. css level 2 (revision 1)the definition of 'top' in that specification. recommendation initial definition. ...
rotate() - CSS: Cascading Style Sheets
its result is a <transform-function> data type. the fixed point that the element rotates around — mentioned above — is also known as the transform origin. this defaults to the center of the element, but you can set your own custom transform origin using the transform-origin property. syntax the amount of rotation created by rotate() is specified by an <angle>. if positive, the movement will be clockwise; if negative, it will be counter-clockwise. a rotation by 180° is called point reflection. ...
rotate3d() - CSS: Cascading Style Sheets
its result is a <transform-function> data type. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. in 3d space, rotations have three degrees of liberty, which together describe a single axis of rotation. the axis of rotation is defined by an [x, y, z] vector and pass by the origin (as defined by the transform-origin property). ...
rotateX() - CSS: Cascading Style Sheets
its result is a <transform-function> data type. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. the axis of rotation passes through an origin, defined by the transform-origin css property. note: rotatex(a) is equivalent to rotate3d(1, 0, 0, a). note: unlike rotations in the 2d plane, the composition of 3d rotations is usually not commutative. ...
rotateY() - CSS: Cascading Style Sheets
its result is a <transform-function> data type. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. the axis of rotation passes through an origin, defined by the transform-origin css property. note: rotatey(a) is equivalent to rotate3d(0, 1, 0, a). note: unlike rotations in the 2d plane, the composition of 3d rotations is usually not commutative. ...
rotateZ() - CSS: Cascading Style Sheets
its result is a <transform-function> data type. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. the axis of rotation passes through an origin, defined by the transform-origin css property. note: rotatez(a) is equivalent to rotate(a) or rotate3d(0, 0, 1, a). note: unlike rotations in the 2d plane, the composition of 3d rotations is usually not commutative. ...
scale() - CSS: Cascading Style Sheets
efault value is sx, resulting in a uniform scaling that preserves the element's aspect ratio. cartesian coordinates on ℝ2 homogeneous coordinates on ℝℙ2 cartesian coordinates on ℝ3 homogeneous coordinates on ℝℙ3 sx0 0sy sx000sy0001 sx000sy0001 sx0000sy0000100001 [sx 0 0 sy 0 0] accessibility concerns scaling/zooming animations are problematic for accessibility, as they are a common trigger for certain types of migraine. if you need to include such animations on your website, you should provide a control to allow users to turn off animations, preferrably site-wide. also, consider making use of the prefers-reduced-motion media feature — use it to write a media query that will turn off animations if the use...
transform - CSS: Cascading Style Sheets
Web › CSS › transform
) is one of multiple function values, it must be listed first. values <transform-function> one or more of the css transform functions to be applied. the transform functions are multiplied in order from left to right, meaning that composite transforms are effectively applied in order from right to left. none specifies that no transform should be applied. accessibility concerns scaling/zooming animations are problematic for accessibility, as they are a common trigger for certain types of migraine. if you need to include such animations on your website, you should provide a control to allow users to turn off animations, preferrably site-wide. also, consider making use of the prefers-reduced-motion media feature — use it to write a media query that will turn off animations if the use...
unicode-bidi - CSS: Cascading Style Sheets
for example, if a block of content contains both left-to-right and right-to-left text, the user-agent uses a complex unicode algorithm to decide how to display the text. the unicode-bidi property overrides this algorithm and allows the developer to control the text embedding. the unicode-bidi and direction properties are the only properties that are not affected by the all shorthand. note: this property is intended for document type definition (dtd) designers. web designers and similar authors should not override it. ...
Used value - CSS: Cascading Style Sheets
display, font-size, or line-height), the computed values and used values are the same. the following are the css 2.1 properties that do depend on layout, so they have a different computed value and used value: (taken from css 2.1 changes: specified, computed, and actual values): background-position bottom, left, right, top height, width margin-bottom, margin-left, margin-right, margin-top min-height, min-width padding-bottom, padding-left, padding-right, padding-top text-indent specification specification status comment css level 2 (revision 2)the definition of 'used value' in that specification. working draft no change. css level 2 (revision 1)the definition of 'used value' in that specification. recommendation initial de...
user-modify - CSS: Cascading Style Sheets
/* keyword values */ user-modify: read-only; user-modify: read-write; user-modify: write-only; /* global values */ user-modify: inherit; user-modify: initial; user-modify: unset; this property has been replaced by the contenteditable attribute. syntax the -moz-user-modify property is specified as one of the keyword values from the list below. values read-only default value. contents are read-only. read-write the user is able to read and write contents. ...
user-select - CSS: Cascading Style Sheets
implement the property as inherited, which violates the behavior described in the spec, and this will bring some issues. until now, chromium chooses to fix the issues, make the final behavior meets the specifications. syntax none the text of the element and its sub-elements is not selectable. note that the selection object can contain these elements. ...
visibility - CSS: Cascading Style Sheets
remove it from the accessibility tree. this will cause the element and all its descendant elements to no longer be announced by screen reading technology. interpolation visibility values are interpolable between visible and not-visible. one of the start or ending values must therefore be visible or no interpolation can happen. the value is interpolated as a discrete step, where values of the timing function between 0 and 1 map to visible and other values of the timing function (which occur only at the start/end of the transition or as a result of cubic-bezier() functions with y values outside of [0, 1]) map to the closer endpoint. notes support for visibility: collapse is missing or partially incorrect in some modern browsers. it may not be correctly treated like visibility: hidden on ...
will-change - CSS: Cascading Style Sheets
n a stylesheet implies that the targeted elements are always a few moments away from changing and the browser will keep the optimizations for much longer time than it would have otherwise. so it is a good practice to switch will-change on and off using script code before and after the change occurs. don't apply will-change to elements to perform premature optimization. if your page is performing well, don't add the will-change property to elements just to wring out a little more speed. will-change is intended to be used as something of a last resort, in order to try to deal with existing performance problems. it should not be used to anticipate performance problems. excessive use of will-change will result in excessive memory use and will cause more complex rendering to occur as the bro...
writing-mode - CSS: Cascading Style Sheets
stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. this property specifies the block flow direction, which is the direction in which block-level containers are stacked, and the direction in which inline-level content flows within a block container. thus, it also determines the ordering of block-level content. syntax /* keyword values */ writing-mode: horizontal-tb; writing-mode: vertical-rl; writing-mode: vertical-lr; /* global values */ writing-mode: inherit; writing-mode: initial; writing-mode: unset; the writing-mode property is specified as one of the values listed below. the flow direction in horizontal scripts is also affected by the directionality of t...
zoom - CSS: Cascading Style Sheets
Web › CSS › zoom
om affects the layout size of the element. /* keyword values */ zoom: normal; zoom: reset; /* <percentage> values */ zoom: 50%; zoom: 200%; /* <number> values */ zoom: 1.1; zoom: 0.7; /* global values */ zoom: inherit; zoom: initial; zoom: unset; syntax values normal render this element at its normal size. reset do not (de)magnify this element if the user applies non-pinch-based zooming (e.g. by pressing ctrl-- or ctrl++ keyboard shortcuts) to the document. only supported by webkit (and possibly blink). <percentage> zoom factor. 100% is equivalent to normal. values larger than 100% zoom in. values smaller than 100% zoom out. <number> zoom factor. equivalent to the corresponding percentage (1.0 = 100% = normal). values larger than 1.0 zoom in. values smaller than 1.0 zoom ou...
math:lowest() - EXSLT
Web › EXSLT › math › lowest
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()). a node has this minimum value if converting its string value to a number equals the minimum value. syntax math:lowest(nodeset) parameters nodeset the node-set whose lowest value is to be returned. returns a result tree fragment consisting of copies of the nodes returned by math:min(). specifications exslt - math:lowest ...
Math (math) - EXSLT
Web › EXSLT › math
r working with numeric values and comparing nodes. the namespace for the math package is http://exslt.org/math. 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. ...
set:has-same-node() - EXSLT
syntax set:has-same-node(nodeset1, nodeset2) parameters nodeset1 the first node set to check. nodeset2 the second node set to check. ...
Sets (set) - EXSLT
Web › EXSLT › set
space for these functions is http://exslt.org/sets. set:difference()set:difference() returns the difference between two node-sets. in other words, it returns a node-set whose nodes are in one node-set but not in the other.set:distinct()set:distinct() returns a subset of the nodes in the specified node-set, returning only nodes with unique string values.set:has-same-node()set:has-same-node() determines whether two node-sets have any nodes in common.set:intersection()set:intersection() returns the intersection of two node-sets. in other words, it returns a node-set containing all the nodes that exits in both nodeset1 and nodeset2.set:leading()set:leading() returns the nodes in one node-set that come before the first node in the other node-set.set:trailing()set:trailing() returns the nodes in o...
str:split() - EXSLT
Web › EXSLT › str › split
syntax str:split(string, pattern) parameters string the string to split. pattern the pattern indicating where to split the string. returns a node-set of token elements, each containing one token from the string. ...
str:tokenize() - EXSLT
Web › EXSLT › str › tokenize
syntax str:tokenize(string, delimiters) parameters string the string to tokenize. delimiters each character in this string is used as a word separator while tokenizing. returns a node-set of token elements, each containing one token from the string. ...
Strings (str) - EXSLT
Web › EXSLT › str
ce: xslt elements, exslt functions, xpath functions, xpath axes the exslt strings package provides functions that allow the manipulation of strings. the namespace for the strings package is http://exslt.org/strings. 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. ...
EXSLT
basic functions that expand upon the capabilities of xslt. the namespace for the common package is http://exslt.org/common. functions exsl:node-set() exsl:object-type() math the exslt math package provides functions for working with numeric values and comparing nodes. the namespace for the math package is http://exslt.org/math. 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. the exslt regular expressions namespace is http://exslt.org/regular-expressions. functions regexp:match() regexp:replace() regexp:test() sets the exslt sets package offers functions that let you perform set manip...
Getting Started - Developer guides
urposes, the above is a somewhat simplified version of the code to be used for creating an xmlhttp instance. for a more realistic example, see step 3 of this article. after making a request, you will receive a response back. at this stage, you need to tell the xmlhttp request object which javascript function will handle the response, by setting the onreadystatechange property of the object and naming it after the function to call when the request changes state, like this: httprequest.onreadystatechange = nameofthefunction; note that there are no parentheses or parameters after the function name, because you're assigning a reference to the function, rather than actually calling it. alternatively, instead of giving a function name, you can use the javascript technique of defining functions o...
Web Audio playbackRate explained - Developer guides
ginal rate.) a complete example let's create a <video> element first, and set up video and playback rate controls in html: <video id="myvideo" controls> <source src="https://udn.realityripple.com/samples/6f/08625b424a.m4v" type='video/mp4' /> <source src="https://udn.realityripple.com/samples/5b/8cd6da9c65.webm" type='video/webm' /> </video> <form> <input id="pbr" type="range" value="1" min="0.5" max="4" step="0.1" > <p>playback rate <span id="currentpbr">1</span></p> </form> and apply some javascript to it: window.onload = function () { var v = document.getelementbyid("myvideo"); var p = document.getelementbyid("pbr"); var c = document.getelementbyid("currentpbr"); p.addeventlistener('input',function(){ c.innerhtml = p.value; v.playbackrate = p.value; },fals...
Block formatting context - Developer guides
f the <div> now runs through the float. as explained in the guide to in-flow and out of flow elements, the float has been taken out of flow so the background and border of the <div> only contain the content and not the float. using overflow: auto setting overflow: auto or set other values than the initial value of overflow: visible created a new bfc containing the float. our <div> now becomes a mini-layout inside our layout. any child element will be contained inside it. 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. there are some occasions in which you will find you get unwanted scrollbars or clipped shadows when you use this property purely to create a bfc. in addition, it ...
Challenge solutions - Developer guides
solution the following rule achieves this effect: ul { border: 10px solid lightblue; width: 100px; } layout default image position fixed image position challenge change your sample document, doc2.html, adding this tag to it near the end, just before </body>: <img id="fixed-pin" src="yellow-pin.png" alt="yellow map pin"> predict where the image will appear in...
Graphics on the Web - Developer guides
ize. view all... 3d graphics webgl a guide to getting started with webgl, the 3d graphics api for the web. this technology lets you use standard opengl es in web content. video using html5 audio and video embedding video and/or audio in a web page and controlling its playback. webrtc the rtc in webrtc stands for real-time communications, a technology that enables audio/video streaming and data sharing between browser clients (peers). ...
Rich-Text Editing in Mozilla - Developer guides
><\/head><body onload=\"print();\">" + odoc.innerhtml + "<\/body><\/html>"); oprntwin.document.close(); } </script> <style type="text/css"> .intlink { cursor: pointer; } img.intlink { border: 0; } #toolbar1 select { font-size:10px; } #textbox { width: 540px; height: 200px; border: 1px #000000 solid; padding: 12px; overflow: scroll; } #textbox #sourcetext { padding: 0; margin: 0; min-width: 498px; min-height: 200px; } #editmode label { cursor: pointer; } </style> </head> <body onload="initdoc();"> <form name="compform" method="post" action="sample.php" onsubmit="if(validatemode()){this.mydoc.value=odoc.innerhtml;return true;}return false;"> <input type="hidden" name="mydoc"> <div id="toolbar1"> <select onchange="formatdoc('formatblock',this[this.selectedindex].value);this.s...
Making content editable - Developer guides
><\/head><body onload=\"print();\">" + odoc.innerhtml + "<\/body><\/html>"); oprntwin.document.close(); } </script> <style type="text/css"> .intlink { cursor: pointer; } img.intlink { border: 0; } #toolbar1 select { font-size:10px; } #textbox { width: 540px; height: 200px; border: 1px #000000 solid; padding: 12px; overflow: scroll; } #textbox #sourcetext { padding: 0; margin: 0; min-width: 498px; min-height: 200px; } #editmode label { cursor: pointer; } </style> </head> <body onload="initdoc();"> <form name="compform" method="post" action="sample.php" onsubmit="if(validatemode()){this.mydoc.value=odoc.innerhtml;return true;}return false;"> <input type="hidden" name="mydoc"> <div id="toolbar1"> <select onchange="formatdoc('formatblock',this[this.selectedindex].value);this.s...
HTML5 Parser - Developer guides
Web › Guide › HTML › HTML5 › HTML5 Parser
xample, firefox-only intranets or webkit-oriented mobile sites), then you might have tags that match this pattern, and they will behave differently with gecko 2. calling document.write() during parsing prior to html5, gecko and webkit allowed calls to document.write() during parsing to insert content into the source stream. this behavior was inherently racy, as the content was inserted into a timing-dependent point in the source stream. if the call happened after the parser was done, the inserted content replaced the document. in ie, such calls are either ignored or imply a call to document.open(), replacing the document. in html5, document.write() can only be called from a script that is created by a <script> tag that does not have the async or defer attributes set. with the html5 parser, ...
Introduction to HTML5 - Developer guides
avior was undefined. essentially, it meant that all browsers behaved differently, which is no longer the case. now, faced with errors in the mark-up, all compliant browsers must behave exactly in the same way. this requirement helps web developers quite a bit. while it is true that all modern browsers now use these html5 parsing rules, non-html5-compliant browsers are still used by some. keep in mind that it's still highly recommended that one writes valid mark-up, as such code is easier to read and maintain, and it greatly decreases the prominence of incompatibilities that exists in various older browsers. don't worry — you don't have to change anything on your website. the web browsers' developers have done everything for you! ...
Introduction to Web development - Developer guides
mprehensive, regularly updated guide to javascript for all levels of learning from beginner to advanced. crockford on javascript — an in-depth video series on the javascript language. eloquent javascript — a comprehensive guide to intermediate and advanced javascript methodologies intermediate a re-introduction to javascript — a recap on the javascript programming language aimed at intermediate-level developers essential javascript design patterns — an introduction to essential javascript design patterns introduction to object-oriented javascript — learn about the javascript object model. christian heilmann's javascript best practices — learn about some of the obvious and (not so) obvious best practices when writing javascript. ...
Separate sites for mobile and desktop - Developer guides
llows for completely different user experiences on desktop and mobile — they’re two different sites, after all! the bad unfortunately, this approach is not without its drawbacks. for starters, you are now maintaining two different pages for every page on your site that you would like to expose to mobile users. if you are using a cms, it is possible to arrange your site templates in a way that minimizes this duplication. however any time that there is a difference between the mobile and desktop templates, there is a potential source of complication in your code. similarly, this increases the implementation time of any new site features, since you must now code two sets of front-end logic. even more important than that, though, is the fact that user-agent detection is inherently flawed, and...
Mobile Web Development - Developer guides
Web › Guide › Mobile
sort to parsing the browser's user agent string to try to distinguish between desktops, tablets, and phones, to serve different content to each type of device. if you do this, make sure your algorithm is correct, and you aren't serving the wrong type of content to a device because you don't understand a particular browser's user agent string. see this guide to using the user agent string to determine device type. test on multiple browsers test your web site on multiple browsers. this means testing on multiple platforms — at least ios and android. test mobile safari on the iphone using the ios simulator test opera and firefox using the android sdk. see these additional instructions for running firefox for android using the android emulator. ...
Printing - Developer guides
provides tips and techniques for helping your web content print better. 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. you can use this to adjust the user interface presented during printing (such as by displaying or hiding user interface elements during the print process). note: you can also use window.onbeforeprint and window.onafterprint to assign handlers for these events, but using eventtarget.addeventlistener() is preferred. examples here are some common examples. open ...
The Unicode Bidirectional Text Algorithm - Developer guides
ndering unicode text. understanding this algorithm in at least basic terms is helpful when you're striving to produce localization-ready web content or apps. 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 e...
The Web Open Font Format (WOFF) - Developer guides
Web › Guide › WOFF
andwidth and will load faster than if they used equivalent uncompressed truetype or opentype files. many font vendors that are unwilling to license their truetype or opentype format fonts for use on the web will license woff format fonts. this improves availability of fonts to site designers. both proprietary and free software browser vendors like the woff format, so it has the potential of becoming a truly universal, interoperable font format for the web, unlike other current font formats. there are two versions of woff; woff and woff2, they mostly differ in regard to the compression algorithm used. in @font-face they are identified by the 'woff' and respectively 'woff2' format descriptor. using woff you can use the @font-face css property to use woff fonts for text in web content. it ...
Developer guides
>, webgl or web audio api to modify audio and video directly, for example adding reverb/compression effects to audio, or grayscale/sepia filters to video. this article provides a reference to explain what you need to do. events developer guide events refer to two things: a design pattern used for the asynchronous handling of various incidents which occur in the lifetime of a web page; and the naming, characterization, and use of a large number of incidents of different types. ajax ajax is a term that defines a group of technologies allowing web applications to make quick, incremental updates to the user interface without reloading the entire browser page. this makes the application faster and more responsive to user actions. graphics on the web modern web sites and applications often ne...
HTML attribute: crossorigin - HTML: Hypertext Markup Language
et to 'include'. "" setting the attribute name to an empty value, like crossorigin or crossorigin="", is the same as anonymous. by default (that is, when the attribute is not specified), cors is not used at all. the "anonymous" keyword means that there will be no exchange of user credentials via cookies, client-side ssl certificates or http authentication as described in the terminology section of the cors specification, unless it is in the same origin. an invalid keyword and an empty string will be handled as the anonymous keyword. example: crossorigin with the script element you can use the following <script> element to tell a browser to execute the https://example.com/example-framework.js script without sending user-credentials. <script src="https://example.com/examp...
HTML attribute: maxlength - HTML: Hypertext Markup Language
the maxlength attribute defines the maximum number of characters (as utf-16 code units) the user can enter into an <input> or <textarea>. this must be an integer value 0 or higher. if no maxlength is specified, or an invalid value is specified, the input or textarea has no maximum length. any maxlength value must be greater than or equal to the value of minlength, if present and valid. the input will fail constraint validation if the length of the text value of the field is greater than maxlength utf-16 code units long. constraint validation is only applied when the value is changed by the user. constraint validation while the browser will generally prevent user from entering more text than the maxlength attribute allows, should the length be longer than the maxlength allows, the read-on...
HTML attribute: multiple - HTML: Hypertext Markup Language
equired and optional input, data formats, and other relevant information. 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. don't do that. if you do change the appearance of a select, and even if you don't, make sure to inform the user that more than one option can be selected by another method. ...
<a>: The Anchor element - HTML: Hypertext Markup Language
Web › HTML › Element › a
" links how-to: use skip navigation links mdn / understanding wcag, guideline 2.4 explanations understanding success criterion 2.4.1 size and proximity size interactive elements, like links, should provide an area large enough that it is easy to activate them. this helps a variety of people, including those with motor control issues and those using imprecise inputs such as a touchscreen. a minimum size of 44×44 css pixels is recommended. text-only links in prose content are exempt from this requirement, but it’s still a good idea to make sure enough text is hyperlinked to be easily activated. understanding success criterion 2.5.5: target size target size and 2.5.5 quick test: large touch targets proximity interactive elements, like links, placed in close visual proximity sh...
<abbr>: The Abbreviation element - HTML: Hypertext Markup Language
Web › HTML › Element › abbr
ult accessibility concerns spelling out the acronym or abbreviation in full the first time it is used on a page is beneficial for helping people understand it, especially if the content is technical or industry jargon. example <p>javascript object notation (<abbr>json</abbr>) is a lightweight data-interchange format.</p> this is especially helpful for people who are unfamiliar with the terminology or concepts discussed in the content, people who are new to the language, and people with cognitive concerns. specifications specification status comment html living standardthe definition of '<abbr>' in that specification. living standard html5the definition of '<abbr>' in that specification. recommendation html 4.01 specificatio...
<area> - HTML: Hypertext Markup Language
Web › HTML › Element › area
te, if present, indicates that the author intends the hyperlink to be used for downloading a resource. see <a> for a full description of the download attribute. href the hyperlink target for the area. its value is a valid url. this attribute may be omitted; if so, the <area> element does not represent a hyperlink. hreflang indicates the language of the linked resource. allowed values are determined by bcp47. use this attribute only if the href attribute is present. ping contains a space-separated list of urls to which, when the hyperlink is followed, post requests with the body ping will be sent by the browser (in the background). typically used for tracking. referrerpolicy a string indicating which referrer to use when fetching the resource: "no-referrer" meaning that the refer...
<basefont> - HTML: Hypertext Markup Language
Web › HTML › Element › basefont
ze as either a numeric or relative value. numeric values range from 1 to 7 with 1 being the smallest and 3 the default. usage notes do not use this element! though once (imprecisely) normalized in html 3.2, it wasn't supported in all major browsers. further, browsers, and even successive versions of browsers, never implemented it in the same way: practically, using it has always brought indeterminate results. the <basefont> element was deprecated in the standard at the same time as all elements related to styling only. starting with html 4, html does not convey styling information anymore (outside the <style> element or the style attribute of each element). in html5, this element has been removed completely. for any new web development, styling should be written using css only. the forme...
<bdi>: The Bidirectional Isolate element - HTML: Hypertext Markup Language
Web › HTML › Element › bdi
itted aria roles any dom interface htmlelement attributes like all other html elements, this element supports the global attributes, except that the dir attribute behaves differently than normal: it defaults to auto, meaning its value is never inherited from the parent element. this means that unless you specify a value of either rtl or ltr for dir, the user agent will determine the correct directionality to use based on the contents of the <bdi>. examples no <bdi> with only ltr this example lists the winners of a competition using <span> elements only. when the names only contain ltr text the results look fine: <ul> <li><span class="name">henrietta boffin</span> - 1st place</li> <li><span class="name">jerry cruncher</span> - 2nd place</li> </ul> body { bord...
<col> - HTML: Hypertext Markup Language
Web › HTML › Element › col
bute, the effect can be achieved by combining adequate css attribute selectors like [colspan=n], though this is not trivial. width this attribute specifies a default width for each column in the current column group. in addition to the standard pixel and percentage values, this attribute might take the special form 0*, which means that the width of each column in the group should be the minimum width necessary to hold the column's contents. relative widths such as 0.5* also can be used. examples please see the <table> page for examples on <col>. specifications specification status comment html living standardthe definition of '<col>' in that specification. living standard html5the definition of '<col>' in that specification. recomm...
<colgroup> - HTML: Hypertext Markup Language
Web › HTML › Element › colgroup
ntal alignment of each column cell content will be handled. possible values are: left, aligning the content to the left of the cell center, centering the content in the cell right, aligning the content to the right of the cell justify, inserting spaces into the textual content so that the content is justified in the cell char, aligning the textual content on a special character with a minimal offset, defined by the char and charoff attributes. if this attribute is not set, the left value is assumed. the descendant <col> elements may override this value using their own align attribute. note: do not try to set the text-align property on a selector giving a <colgroup> element. because <td> elements are not descendant of the <colgroup> element, they won't inherit it. if ...
<data> - HTML: Hypertext Markup Language
Web › HTML › Element › data
itted aria roles any dom interface htmldataelement attributes this element's attributes include the global attributes. value this attribute specifies the machine-readable translation of the content of the element. examples the following example displays product names but also associates each name with a product number. <p>new products</p> <ul> <li><data value="398">mini ketchup</data></li> <li><data value="399">jumbo ketchup</data></li> <li><data value="400">mega jumbo ketchup</data></li> </ul> specifications specification status comment html living standardthe definition of '<data>' in that specification. living standard no change from html5 html5the definition of '<data>' in that specification. recommendation...
<del>: The Deleted Text element - HTML: Hypertext Markup Language
Web › HTML › Element › del
the starting and ending tag are mandatory. permitted parents any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles any dom interface htmlmodelement attributes this element's attributes include the global attributes. cite a uri for a resource that explains the change (for example, meeting minutes). datetime this attribute indicates the time and date of the change and must be a valid date string with an optional time. if the value cannot be parsed as a date with an optional time string, the element does not have an associated time stamp. for the format of the string without a time, see date strings. the format of the string if it includes both date and time is covered in local date a...
<dfn>: The Definition element - HTML: Hypertext Markup Language
Web › HTML › Element › dfn
arents any element that accepts phrasing content. implicit aria role term permitted aria roles any dom interface htmlelement attributes this element's attributes include the global attributes. in html5, the title attribute has special meaning, as noted below. usage notes there are some not-entirely-obvious aspects to using the <dfn> element. we examine those here. specifying the term being defined the term being defined is identified following these rules: if the <dfn> element has a title attribute, the value of the title attribute is considered to be the term being defined. the element must still have text within it, but that text may be an abbreviation (perhaps using <abbr>) or another form of the term. if the <dfn> contains a single c...
<fieldset>: The Field Set element - HTML: Hypertext Markup Language
Web › HTML › Element › fieldset
e are several special styling considerations for <fieldset>. its display value is block by default, and it establishes a block formatting context. if the <fieldset> is styled with an inline-level display value, it will behave as inline-block, otherwise it will behave as block. by default there is a 2px groove border surrounding the contents, and a small amount of default padding. the element has min-inline-size: min-content by default. if a <legend> is present, it is placed over the block-start border. the <legend> shrink-wraps, and also establishes a formatting context. the display value is blockified. (for example, display: inline behaves as block.) there will be an anonymous box holding the contents of the <fieldset>, which inherits certain properties from the <fieldset>. if the <fields...
<figure>: The Figure with Optional Caption element - HTML: Hypertext Markup Language
Web › HTML › Element › figure
txt+= "cookies enabled: " + navigator.cookieenabled + "; "; txt+= "platform: " + navigator.platform + "; "; txt+= "user-agent header: " + navigator.useragent + "; "; console.log("navigatorexample", txt); } </pre> </figure> quotations <figure> <figcaption><cite>edsger dijkstra:</cite></figcaption> <blockquote>if debugging is the process of removing software bugs, then programming must be the process of putting them in.</blockquote> </figure> poems <figure> <p style="white-space:pre"> bid me discourse, i will enchant thine ear, or like a fairy trip upon the green, or, like a nymph, with long dishevell'd hair, dance on the sands, and yet no footing seen: love is a spirit all compact of fire, not gross to sink, but light, and will aspire.</p> <figcaption><cit...
<html>: The HTML Document / Root element - HTML: Hypertext Markup Language
Web › HTML › Element › html
document. default value is "http://www.w3.org/1999/xhtml". this is required in documents parsed with xml parsers, and optional in text/html documents. example <!doctype html> <html lang="en"> <head>...</head> <body>...</body> </html> accessibility concerns providing a lang attribute with a valid ietf identifying language tag on the <html> element will help screen reading technology determine the proper language to announce. the identifying language tag should describe the language used by the majority of the content of the page. without it, screen readers will typically default to the operating system's set language, which may cause mispronunciations. including a valid lang declaration on the <html> element also ensures that important metadata contained in the page's <head>, such a...
<i>: The Idiomatic Text element - HTML: Hypertext Markup Language
Web › HTML › Element › i
the source for this interactive example is stored in a github repository. ...
<input type="button"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › button
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). the top two controls allow you to choose the color and size of the drawing pen. the button, when clicked, invokes a function that clears the canvas. ...
<input type="datetime"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › datetime
this feature has been removed from whatwg html, and is no longer supported in browsers. instead, browsers are implementing (and developers are encouraged to use) <input type="datetime-local">. ...
<input type="image"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › image
ou submit a form using a button created with <input type="image">, two extra data points are submitted to the server automatically by the browser — x and y. you can see this in action in our x y coordinates example. when you click on the image to submit the form, you'll see the data appended to the url as parameters, for example ?x=52&y=55. if the image input has a name attribute, then keep in mind that the specified name is prefixed on every attribute, so if the name is position, then the returned coordinates would be formatted in the url as ?position.x=52&position.y=55. this, of course, applies to all other attributes as well. these are the x and y coordinates of the image that the mouse clicked on to submit the form, where (0,0) is the top-left of the image. these can be used when the ...
<input type="radio"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › radio
he radio group is not included in the submitted form data at all, since there is no value to report. it's fairly uncommon to actually want to allow the form to be submitted without any of the radio buttons in a group selected, so it is usually wise to have one default to the checked state. see selecting a radio button by default below. let's add a little bit of code to our example so we can examine the data generated by this form. the html is revised to add a <pre> block to output the form data into: <form> <p>please select your preferred contact method:</p> <div> <input type="radio" id="contactchoice1" name="contact" value="email"> <label for="contactchoice1">email</label> <input type="radio" id="contactchoice2" name="contact" value="phone"> <lab...
<input type="submit"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › submit
te is also available on <input type="image"> and <button> elements. using submit buttons <input type="submit"> buttons are used to submit forms. if you want to create a custom button and then customize the behavior using javascript, you need to use <input type="button">, or better still, a <button> element. if you choose to use <button> elements to create the buttons in your form, keep this in mind: if there's only one <button> inside the <form>, that button will be treated as the "submit" button. so you should be in the habit of expressly specifying which button is the submit button. a simple submit button we'll begin by creating a form with a simple submit button: <form> <div> <label for="example">let's submit some text</label> <input id="example" type="text" name="text"> ...
<ins> - HTML: Hypertext Markup Language
Web › HTML › Element › ins
ending tag are mandatory. permitted parents any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles any dom interface htmlmodelement attributes this element includes the global attributes. cite this attribute defines the uri of a resource that explains the change, such as a link to meeting minutes or a ticket in a troubleshooting system. datetime this attribute indicates the time and date of the change and must be a valid date with an optional time string. if the value cannot be parsed as a date with an optional time string, the element does not have an associated time stamp. for the format of the string without a time, see format of a valid date string. the format of the string if i...
<li> - HTML: Hypertext Markup Language
Web › HTML › Element › li
thub.com/mdn/interactive-examples and send us a pull request. content categories none. permitted content flow content. tag omission the end tag can be omitted if the list item is immediately followed by another <li> element, or if there is no more content in its parent element. permitted parents an <ul>, <ol>, or <menu> element. though not a conforming usage, the obsolete <dir> can also be a parent. implicit aria role listitem when child of an ol, ul or menu permitted aria roles menuitem, menuitemcheckbox, menuitemradio, option, none, presentation, radio, separator, tab, treeitem dom interface htmllielement attributes this element includes the global attributes. value this integer attribute indic...
<listing> - HTML: Hypertext Markup Language
Web › HTML › Element › listing
ween the start and end tags without interpreting the html in between and using a monospaced font. the html 2 standard recommended that lines shouldn't be broken when not greater than 132 characters. note: do not use this element. it is deprecated since html 3.2 and was neither implemented by all browsers, nor in a consistent way. even more it is obsoleted in html5 and may be rendered by conforming user-agents as the <pre> element, which will interpret the internal html! instead use the <pre> element or if semantically adequate the <code> element, eventually escaping the html '<' and '>' so that they don't get interpreted. 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...
<main> - HTML: Hypertext Markup Language
Web › HTML › Element › main
the main content area consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. a document mustn't have more than one <main> element that doesn't have the hidden attribute specified. content categories flow content, palpable content. permitted content flow content. ...
<nav>: The Navigation Section element - HTML: Hypertext Markup Language
Web › HTML › Element › nav
tion links; typically the <footer> element often has a list of links that don't need to be in a <nav> element. a document may have several <nav> elements, for example, one for site navigation and one for intra-page navigation. aria-labelledby can be used in such case to promote accessibility, see example. user agents, such as screen readers targeting disabled users, can use this element to determine whether to omit the initial rendering of navigation-only content. examples in this example, a <nav> block is used to contain an unordered list (<ul>) of links. with appropriate css, this can be presented as a sidebar, navigation bar, or drop-down menu. <nav class="menu"> <ul> <li><a href="#">home</a></li> <li><a href="#">about</a></li> <li><a href="#">contact</a></li> </ul> <...
<ol>: The Ordered List element - HTML: Hypertext Markup Language
Web › HTML › Element › ol
or letter. the <ol> and <ul> elements may nest as deeply as desired, alternating between <ol> and <ul> however you like. the <ol> and <ul> elements both represent a list of items. the difference is with the <ol> element, the order is meaningful. for example: steps in a recipe turn-by-turn directions the list of ingredients in decreasing proportion on nutrition information labels to determine which list to use, try changing the order of the list items; if the meaning changes, use the <ol> element — otherwise you can use <ul>. 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 abo...
<small>: the side comment element - HTML: Hypertext Markup Language
Web › HTML › Element › small
specification. recommendation html 4.01 specificationthe definition of '<small>' in that specification. recommendation notes although the <small> element, like the <b> and <i> elements, may be perceived to violate the principle of separation between structure and presentation, all three are valid in html5. authors are encouraged to use their best judgement when determining whether to use <small> or css. ...
<spacer> - HTML: Hypertext Markup Language
Web › HTML › Element › spacer
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. firefox, which is the descendant of netscape's browsers, removed support for <spacer> in version 4. attributes like all other html elements, this element supports the global attributes. type this attribute determines type of spacer. possible values are horizontal, vertical and block. size this attribute can be used for defining size of spacer in pixels when type is horizontal or vertical. width this attribute can be used for defining width of spacer in pixels when type is block. height this attribute can be used for defining height of spacer in pixels when type is block. align this attribute determi...
<strong>: The Strong Importance element - HTML: Hypertext Markup Language
Web › HTML › Element › strong
a coincidence that they both have the same default styling (boldface) in most browsers (although some older browsers actually underline <strong>). each element is meant to be used in certain types of scenarios, and if you want to bold text simply for decoration, you should instead actually use the css font-weight property. the intended meaning or purpose of the enclosed text should be what determines which element you use. communicating meaning is what semantics are all about. <em> vs. <strong> adding to the confusion is the fact that while html 4 defined <strong> as simply indicating a stronger emphasis, html 5 defines <strong> as representing "strong importance for its contents." this is an important distinction to make. while <em> is used to change the meaning of a sentence as spoken ...
<td>: The Table Data Cell element - HTML: Hypertext Markup Language
Web › HTML › Element › td
ll be handled. possible values are: left: the content is aligned to the left of the cell. center: the content is centered in the cell. right: the content is aligned to the right of the cell. justify (with text only): the content is stretched out inside the cell so that it covers its entire width. char (with text only): the content is aligned to a character inside the <th> element with minimal offset. this character is defined by the char and charoff attributes unimplemented (see bug 2212). the default value when this attribute is not specified is left. note: to achieve the same effect as the left, center, right or justify values, apply the css text-align property to the element. to achieve the same effect as the char value, give the text-align property the same value ...
<tfoot>: The Table Foot element - HTML: Hypertext Markup Language
Web › HTML › Element › tfoot
horizontal alignment of each cell content will be handled. possible values are: left, aligning the content to the left of the cell center, centering the content in the cell right, aligning the content to the right of the cell justify, inserting spaces into the textual content so that the content is justified in the cell char, aligning the textual content on a special character with a minimal offset, defined by the char and charoff attributes unimplemented (see bug 2212). if this attribute is not set, the left value is assumed. note: do not use this attribute as it is obsolete (not supported) in the latest standard. to achieve the same effect as the left, center, right or justify values, use the css text-align property on it. to achieve the same effect as the char val...
<th> - HTML: Hypertext Markup Language
Web › HTML › Element › th
ll be handled. possible values are: left: the content is aligned to the left of the cell. center: the content is centered in the cell. right: the content is aligned to the right of the cell. justify (with text only): the content is stretched out inside the cell so that it covers its entire width. char (with text only): the content is aligned to a character inside the <th> element with minimal offset. this character is defined by the char and charoff attributes. the default value when this attribute is not specified is left. note: do not use this attribute as it is obsolete in the latest standard. to achieve the same effect as the left, center, right or justify values, apply the css text-align property to the element. to achieve the same effect as the char value, give ...
<thead>: The Table Head element - HTML: Hypertext Markup Language
Web › HTML › Element › thead
horizontal alignment of each cell content will be handled. possible values are: left, aligning the content to the left of the cell center, centering the content in the cell right, aligning the content to the right of the cell justify, inserting spaces into the textual content so that the content is justified in the cell char, aligning the textual content on a special character with a minimal offset, defined by the char and charoff attributes unimplemented (see bug 2212). if this attribute is not set, the left value is assumed. note: do not use this attribute as it is obsolete (not supported) in the latest standard. to achieve the same effect as the left, center, right or justify values, use the css text-align property on it. to achieve the same effect as the char val...
<time> - HTML: Hypertext Markup Language
Web › HTML › Element › time
it may represent one of the following: a time on a 24-hour clock. a precise date in the gregorian calendar (with optional time and timezone information). a valid time duration. the source for this interactive example is stored in a github repository. ...
<title>: The Document Title element - HTML: Hypertext Markup Language
Web › HTML › Element › title
shes a page whose title (as displayed at the top of the window or in the window's tab) as "awesome interesting stuff". accessibility concerns it is important to provide a title value that describes the page's purpose. a common navigation technique for users of assistive technology is to read the page title and infer the content the page contains. this is because navigating into a page to determine its content can be a time consuming and potentially confusing process. example <title>menu - blue house chinese food - foodyum: online takeout today!</title> to help the user, update the page title value to reflect significant page state changes (such as form validation problems). example <title>2 errors - your order - blue house chinese food - foodyum: online takeout today!</title> md...
<tt>: The Teletype Text element (obsolete) - HTML: Hypertext Markup Language
Web › HTML › Element › tt
content. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts phrasing content. permitted aria roles any dom interface htmlelement attributes this element only includes the global attributes examples basic example this example uses <tt> to show text entered into, and output by, a terminal application. <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", "c...
<ul>: The Unordered List element - HTML: Hypertext Markup Language
Web › HTML › Element › ul
he html description of the page, but in its associated css, using the list-style-type property. the <ul> and <ol> elements may be nested as deeply as desired. moreover, the nested lists may alternate between <ol> and <ul> without restriction. the <ol> and <ul> elements both represent a list of items. they differ in that, with the <ol> element, the order is meaningful. as a rule of thumb to determine which one to use, try changing the order of the list items; if the meaning is changed, the <ol> element should be used, otherwise you can use <ul>. examples simple example <ul> <li>first item</li> <li>second item</li> <li>third item</li> </ul> the above html will output: nesting a list <ul> <li>first item</li> <li>second item <!-- look, the closing </li> tag is not placed h...
accesskey - HTML: Hypertext Markup Language
ther combinations. certain accesskey values may not be present on certain keyboards, especially when internationalization is a concern. so adapting to specific languages could cause further problems. 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. informing the user that accesskeys are present, so that they are aware of the functionality. if the system lacks a method of notifying the user about this feature, the user might accidentally activate accesskeys. because of these issues, it is generally advised not to use accesskeys for most general-purpose websites and web apps. webaim: keyboard accessibility - accesskey specifications s...
dir - HTML: Hypertext Markup Language
onality of the text is semantically related to its content and not to its presentation, it is recommended that web developers use this attribute instead of the related css properties when possible. that way, the text will display correctly even on a browser that doesn't support css or has the css deactivated. the auto value should be used for data with an unknown directionality, like data coming from user input, eventually stored in a database. browsers might allow users to change the directionality of <input> and <textarea>s in order to assist with authoring content. chrome and safari provide a directionality option in the contextual menu of input fields while internet explorer and edge use the key combinations ctrl + left shift and ctrl + right shift. firefox uses ctrl/cmd + shi...
id - HTML: Hypertext Markup Language
-examples and send us a pull request. this attribute's value is an opaque string: this means that web authors should not rely on it to convey human-readable information (although having your ids somewhat human-readable can be useful for code comprehension, e.g. consider ticket-18659 versus r45tgfe-freds&$@). id's value must not contain whitespace (spaces, tabs etc.). browsers treat non-conforming ids that contain whitespace as if the whitespace is part of the id. in contrast to the class attribute, which allows space-separated values, elements can only have one single id value. note: using characters except ascii letters, digits, '_', '-' and '.' may cause compatibility problems, as they weren't allowed in html 4. though this restriction has been lifted in html5, an id should start wit...
itemprop - HTML: Hypertext Markup Language
numeric data, the meter element and its value attribute can be used. a meter element <div itemscope itemtype="http://schema.org/product"> <span itemprop="name">panasonic white 60l refrigerator</span> <img src="panasonic-fridge-60l-white.jpg" alt=""> <div itemprop="aggregaterating" itemscope itemtype="http://schema.org/aggregaterating"> <meter itemprop="ratingvalue" min=0 value=3.5 max=5>rated 3.5/5</meter> (based on <span itemprop="reviewcount">11</span> customer reviews) </div> </div> similarly, for date- and time-related data, the time element and its datetime attribute can be used. an item with one property, "birthday", whose value is a date <div itemscope> i was born on <time itemprop="birthday" datetime="2009-05-10">may 10th 2009</...
itemtype - HTML: Hypertext Markup Language
ecified. the itemid attribute can only be specified on elements which have both an itemscope attribute and an itemtype attribute specified. they must only be specified on elements with an itemscope attribute, whose itemtype attribute specifies a vocabulary not supporting global identifiers for items, as defined by that vocabulary's specification. the exact meaning of a global identifier is determined by the vocabulary's specification. it is left to such specifications to define whether multiple items of the same global identifier (whether on the same page or different pages) are allowed to exist, and what processing rules for that vocabulary are, with respect to handling the case of multiple items with the same id. simple example html <div itemscope itemtype="http://schema.org/product">...
lang - HTML: Hypertext Markup Language
tion of 'lang' in that specification. living standard no change from latest snapshot, html 5.1 html 5.1the definition of 'lang' in that specification. recommendation snapshot of html living standard, no change from html5 html5the definition of 'lang' in that specification. recommendation snapshot of html living standard, behavior with xml:lang and language determination algorithm defined. it also is a true global attribute. html 4.01 specificationthe definition of 'lang' in that specification. recommendation supported on all elements but <applet>, <base>, <basefont>, <br>, <frame>, <frameset>, <iframe>, <param>, and <script>. ...
x-ms-format-detection - HTML: Hypertext Markup Language
existing links, such as ones with the tel: scheme, are unaffected. links created through format detection do not appear in the dom. this proprietary property is specific to internet explorer and microsoft edge. syntax <html x-ms-format-detection="none"> value all all supported data formats are detected. ...
Inline elements - HTML: Hypertext Markup Language
html (hypertext markup language) elements historically were categorized as either "block-level" elements or "inline-level" elements. since this is a presentational characteristic it is nowadays specified by css in the flow layout. inline elements are those which only occupy the space bounded by the tags defining the element, instead of breaking the flow of the content. in this article, we'll examine html inline-level elements and how they differ from block-level elements. an inline element does not start on a new line and only takes up as much width as necessary. inline vs. block-level elements: a demonstration this is most easily demonstrated with a simple example. first, some simple css that we'll be using: .highlight { background-color:#ee3; } inline let's look at the following...
Link types: dns-prefetch - HTML: Hypertext Markup Language
see using dns-prefetch for more details. specifications specification status comment html living standardthe definition of 'dns-prefetch' in that specification. living standard ...
Link types: prerender - HTML: Hypertext Markup Language
specifications specification status comment html living standardthe definition of 'prerender' in that specification. living standard ...
Link types - HTML: Hypertext Markup Language
he next-most appropriate, and so on. note: apple's ios does not use this link type, nor the sizes attribute, like others mobile browsers do, to select a webpage icon for web clip or a start-up placeholder. instead it uses the non-standard apple-touch-icon and apple-touch-startup-image respectively. the shortcut link type is often seen before icon, but this link type is non-conforming, ignored and web authors must not use it anymore. <link> <a>, <area>, <form> import html imports <link> <a>, <area>, <form> index obsolete since html5 indicates that the page is part of a hierarchical structure and that the hyperlink leads to the top level resource of that structure. if one or several up link types are also present, the number of th...
Preloading content with rel="preload" - HTML: Hypertext Markup Language
n accept media types or full-blown media queries, allowing you to do responsive preloading! ...
Quirks Mode and Standards Mode - HTML: Hypertext Markup Language
emulates nonstandard behavior in navigator 4 and internet explorer 5. this is essential in order to support websites that were built before the widespread adoption of web standards. in full standards mode, the behavior is (hopefully) the behavior described by the html and css specifications. in almost standards mode, there are only a very small number of quirks implemented. how do browsers determine which mode to use? for html documents, browsers use a doctype in the beginning of the document to decide whether to handle it in quirks mode or standards mode. to ensure that your page uses full standards mode, make sure that your page has a doctype like in this example: <!doctype html> <html lang="en"> <head> <meta charset=utf-8> <title>hello world!</title> </head> <body> </bo...
Microformats - HTML: Hypertext Markup Language
microformats use supporting vocabularies to describe objects and name-value pairs to assign values to their properties. ...
HTTP authentication - HTTP
sic authname "access to the staging site" authuserfile /path/to/.htpasswd require valid-user the .htaccess file references a .htpasswd file in which each line consists of a username and a password separated by a colon (:). you cannot see the actual passwords as they are hashed (using md5-based hashing, in this case). note that you can name your .htpasswd file differently if you like, but keep in mind this file shouldn't be accessible to anyone. (apache is usually configured to prevent access to .ht* files). aladdin:$apr1$zjtqbb3f$if9gdyaglmrs2fuinjhsz. user2:$apr1$o04r.y2h$/vekesphvinbbyjukxita/ restricting access with nginx and basic authentication for nginx, you will need to specify a location that you are going to protect and the auth_basic directive that provides the name to the pass...
Resource URLs - HTTP
u open the view source page (view page source or view selection source), you will find it requires viewsource.css through a resource: uri. resources that have to be exposed to web content have been moved to a new location named resource://content-accessible/, which is isolated and only contains non-sensitive resources. in this way we can keep essential resources exposed and have most threats eliminated. note: it is recommended that web and extension developers don’t try to use resource urls anymore. their usage was hacky at best, and most usage won’t work any more. specifications resource: is not defined in any specification. ...
Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’ - HTTP
nable their use. to fix this problem on the client side, revise the code to not request 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". to eliminate this error by changing the server's configuration, adjust the server's configuration to set the access-control-allow-credentials header's value to true. ...
Reason: CORS header 'Access-Control-Allow-Origin' missing - HTTP
if the server is under your control, add the origin of the requesting site to the set of domains permitted access by adding it to the access-control-allow-origin header's value. ...
CORS errors - HTTP
Web › HTTP › CORS › Errors
ror message will be something similar to the following: cross-origin request blocked: the same origin policy disallows reading the remote resource at https://some-url-here. (reason: additional information here). note: for security reasons, specifics about what went wrong with a cors request are not available to javascript code. all the code knows is that an error occurred. the only way to determine what specifically went wrong is to look at the browser's console for details. cors error messages firefox's console displays messages in its console when requests fail due to cors. part of the error text is a "reason" message that provides added insight into what went wrong. the reason messages are listed below; click the message to open an article explaining the error in more detail and off...
Content negotiation - HTTP
ent wants to obtain a resource, the client requests it using its url. the server uses this url to choose one of the variants it provides – each variant being called a representation – and returns a specific representation to the client. the overall resource, as well as each of the representations, have a specific url. how a specific representation is chosen when the resource is called is determined by content negotiation and there are several ways of negotiating between the client and the server. the determination of the best suited representation is made through one of two mechanisms: specific http headers by the client (server-driven negotiation or proactive negotiation), which is the standard way of negotiating a specific kind of resource. the 300 (multiple choices) or 406 (not ...
Using HTTP cookies - HTTP
Web › HTTP › Cookies
ent from a secure origin. this is weaker than the __host- prefix. cookies with these prefixes that are not compliant with their restrictions are rejected by the browser. note that this ensures that if a subdomain were to create a cookie with a prefix, it would either be confined to the subdomain or be ignored completely. as the application server checks for a specific cookie name only when determining if the user is authenticated or a csrf token is correct, this effectively acts as a defence measure against session fixation. on the application server, the web application must check for the full cookie name including the prefix—user agents do not strip the prefix from the cookie before sending it in a request's cookie header. for more information about cookie prefixes and the current s...
Accept-Charset - HTTP
rom this request header, it can theoretically send back a 406 not acceptable error code. but for a better user experience, this is rarely done and the accept-charset header is ignored. in early versions of http/1.1, a default character encoding was defined: iso-8859-1. this is no longer recommended, and now each content-type may have its own default. utf-8 is now well-supported and the overwhelmingly preferred character encoding. to guarantee better privacy through less configuration-based entropy, all browsers omit the accept-charset header: internet explorer 8+, safari 5+, opera 11+, firefox 10+ and chrome 27+ no longer send it. header type request header forbidden header name yes syntax accept-charset: <charset> // multiple types, weighted with the qua...
Accept-Language - HTTP
the accept-language request http header advertises which languages the client is able to understand, and which locale variant is preferred. (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. browsers set adequate values for this header according to their user interface language and even if a user can change it, this happens rarely (and is frowned upon as it leads to fingerprinting). this header is a hint to be used when the server has no way of determining the language via another way, like a specific url, that is controlled by an explicit user decision. it is recommended that the server never...
Alt-Svc - HTTP
Web › HTTP › Headers › Alt-Svc
or draft 25 of the http/3 protocol. <alt-authority> the quoted string specifying the alternative authority which consists of an optional host override, a colon, and a mandatory port number. ma=<max-age>optional the number of seconds for which the alternative service is considered fresh. if omitted, it defaults to 24 hours. alternative service entries can be cached for up to <max-age> seconds, minus the age of the response (from the age header). if the cached entry expires, the client can no longer use this alternative service for new connections. persist=1optional usually cached alternative service entries are cleared on network configuration changes. use of the persist=1 parameter ensures that the entry is not deleted through such changes. multiple entries can be specified in a singl...
Clear-Site-Data - HTTP
icates that the server wishes to clear all types of data for the origin of the response. if more data types are added in future versions of this header, they will also be covered by it. examples sign out of web site if a user signs out of your website or service, you might want to remove locally stored data. ...
Content-Location - HTTP
ument. the server could also consider other content negotiation headers, such as accept-language. pointing to a new document (http 201 created) say you're creating a new blog post through a site's api: put /new/post host: example.com content-type: text/markdown # my first blog post! i made this through `example.com`'s api. i hope it worked. the site returns a generic success message confirming the post was published. the server specifies where the new post is with content-location: http/1.1 201 created content-type: text/plain; charset=utf-8 content-location: /my-first-blog-post ✅ success! indicating the url of a transaction's result say you have a <form> for sending money to another user of a site. <form action="/send-payment" method="post"> <p> <label>who do you want t...
CSP: referrer - HTTP
ed. the origin is sent as referrer to a-priori as-much-secure destination (https->https), but isn't sent to a less secure destination (https->http). "origin" only send the origin of the document as the referrer in all cases. the document https://example.com/page.html will send the referrer https://example.com/. "origin-when-cross-origin" / "origin-when-crossorigin" send a full url when performing a same-origin request, but only send the origin of the document for other cases. "unsafe-url" send a full url (stripped from parameters) when performing a same-origin or cross-origin request. this policy will leak origins and paths from tls-protected resources to insecure origins. carefully consider the impact of this setting. examples content-security-policy: referrer "none"; specificatio...
CSP: report-uri - HTTP
t to. examples see content-security-policy-report-only for more information and examples. content-security-policy: default-src https:; report-uri /csp-violation-report-endpoint/ /csp-violation-report-endpoint/ could for example run a php something like the following that logs the json detailing the violation and, if the violation is the first one added to the log file, sends an email to an administrator: <?php // start configure $log_file = dirname(__file__) . '/csp-violations.log'; $log_file_size_limit = 1000000; // bytes - once exceeded no further entries are added $email_address = 'admin@example.com'; $email_subject = 'content-security-policy violation'; // end configuration $current_domain = preg_replace('/www\./i', '', $_server['server_name']); $email_subject = $email_subject . '...
Content-Security-Policy - HTTP
with a few exceptions, policies mostly involve specifying server origins and script endpoints. this helps guard against cross-site scripting attacks (xss). for more information, see the introductory article on content security policy (csp). header type response header forbidden header name no syntax content-security-policy: <policy-directive>; <policy-directive> where <policy-directive> consists of: <directive> <value> with no internal punctuation. ...
Digest - HTTP
Web › HTTP › Headers › Digest
e defined in rfc 3230 and rfc 5843, and include sha-256 and sha-512. some of the supported algorithms, including unixsum and md5 are subject to collisions and are thus not suitable for applications in which collision-resistance is important. <digest-value> the result of applying the digest algorithm to the resource representation and encoding the result. the choice of digest algorithm also determines the encoding to use: for example sha-256 uses base64 encoding. examples digest: sha-256=x48e9qookqqrvdts8nojrjn3owduoywxbf7kbu9dbpe= digest: sha-256=x48e9qookqqrvdts8nojrjn3owduoywxbf7kbu9dbpe=,unixsum=30637 specifications specification title draft-ietf-httpbis-digest-headers-latest resource digests for http this header was originally defined in ...
ETag - HTTP
Web › HTTP › Headers › ETag
specific version of a resource. it lets caches be more efficient and save bandwidth, as a web server does not need to resend a full response if the content has not changed. additionally, etags help prevent simultaneous updates of a resource from overwriting each other ("mid-air collisions"). if the resource at a given url changes, a new etag value must be generated. a comparison of them can determine whether two representations of a resource are the same. etags are therefore similar to fingerprints, and might also be used for tracking purposes by some servers. they might also be set to persist indefinitely by a tracking server. header type response header forbidden header name no syntax etag: w/"<etag_value>" etag: "<etag_value>" directives w/ optional ...
Forwarded - HTTP
volved in the path of the request. the alternative and de-facto standard versions of this header are the x-forwarded-for, x-forwarded-host and x-forwarded-proto headers. this header is used for debugging, statistics, and generating location-dependent content and by design it exposes privacy sensitive information, such as the ip address of the client. therefore the user's privacy must be kept in mind when deploying this header. 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. this can be either: an ip address (v4 or v6, optionally with a port, and ipv6 quoted...
Keep-Alive - HTTP
spec requirements and won’t load any response which contains them. header type general header forbidden header name yes syntax keep-alive: parameters directives parameters a comma-separated list of parameters, each consisting of an identifier and a value separated by the equal sign ('='). the following identifiers are possible: timeout: indicating the minimum amount of time an idle connection has to be kept opened (in seconds). note that timeouts longer than the tcp timeout may be ignored if no keep-alive tcp message is set at the transport level. max: indicating the maximum number of requests that can be sent on this connection before closing it. unless 0, this value is ignored for non-pipelined connections as another request will be sent in th...
Retry-After - HTTP
aking a follow-up request. there are three main cases this header is used: when sent with a 503 (service unavailable) response, this indicates how long the service is expected to be unavailable. when sent with a 429 (too many requests) response, this indicates how long to wait before making a new request. when sent with a redirect response, such as 301 (moved permanently), this indicates the minimum time that the user agent is asked to wait before issuing the redirected request. header type response header forbidden header name no syntax retry-after: <http-date> retry-after: <delay-seconds> directives <http-date> a date after which to retry. see the date header for more details on the http date format. <delay-seconds> a non-negative decimal integ...
SameSite cookies - HTTP
le "^(.*)\.ht$" "index.php?nav=$1 [nc,l,qsa,co=rewriterule;01;https://www.example.org;30/;samesite=none;secure] rewriterule "^(.*)\.htm$" "index.php?nav=$1 [nc,l,qsa,co=rewriterule;02;https://www.example.org;30/;samesite=none;secure] rewriterule "^(.*)\.html$" "index.php?nav=$1 [nc,l,qsa,co=rewriterule;03;https://www.example.org;30/;samesite=none;secure] [...] rewriterule "^admin/(.*)\.html$" "admin/index.php?nav=$1 [nc,l,qsa,co=rewriterule;09;https://www.example.org:30/;samesite=strict;secure] specifications specification title rfc 6265, section 4.1: set-cookie http state management mechanism draft-ietf-httpbis-rfc6265bis-05 cookie prefixes, same-site cookies, and strict secure cookies ...
Strict-Transport-Security - HTTP
ttp request and redirecting you to a clone of your bank's site instead of the real thing. now your private data is exposed to the hacker. strict transport security resolves this problem; as long as you've accessed your bank's web site once using https, and the bank's web site uses strict transport security, your browser will know to automatically use only https, which prevents hackers from performing this sort of man-in-the-middle attack. how the browser handles it the first time your site is accessed using https and it returns the strict-transport-security header, the browser records this information, so that future attempts to load the site using http will automatically use https instead. when the expiration time specified by the strict-transport-security header elapses, the next attemp...
Trailer - HTTP
Web › HTTP › Headers › Trailer
tal signature, or post-processing status. the te request header needs to be set to "trailers" to allow trailer fields. header type response header forbidden header name yes syntax trailer: header-names directives header-names http header fields which will be present in the trailer part of chunked messages. these header fields are disallowed: message framing headers (e.g., transfer-encoding and content-length), routing headers (e.g., host), request modifiers (e.g., controls and conditionals, like cache-control, max-forwards, or te), authentication headers (e.g., authorization or set-cookie), or content-encoding, content-type, content-range, and trailer itself. examples chunked transfer encoding using a trailing header in this exampl...
Vary - HTTP
Web › HTTP › Headers › Vary
it is used by the server to indicate which headers it used when selecting a representation of a resource in a content negotiation algorithm. the vary header should be set on a 304 not modified response exactly like it would have been set on an equivalent 200 ok response. header type response header forbidden header name no syntax vary: * vary: <header-name>, <header-name>, ... directives * each request for a url is supposed to be treated as a unique and uncacheable request. ...
X-Forwarded-For - HTTP
s, server access logs contain the ip address of the proxy or load balancer only. to see the original ip address of the client, the x-forwarded-for request header is used. this header is used for debugging, statistics, and generating location-dependent content and by design it exposes privacy sensitive information, such as the ip address of the client. therefore the user's privacy must be kept in mind when deploying this header. a standardized version of this header is the http forwarded header. x-forwarded-for is also an email-header indicating that an email-message was forwarded from another account. header type request header forbidden header name no syntax x-forwarded-for: <client>, <proxy1>, <proxy2> directives <client> the client ip address <pro...
X-Forwarded-Host - HTTP
the x-forwarded-host (xfh) header is a de-facto standard header for identifying the original host requested by the client in the host http request header. host names and ports of reverse proxies (load balancers, cdns) may differ from the origin server handling the request, in that case the x-forwarded-host header is useful to determine which host was originally used. this header is used for debugging, statistics, and generating location-dependent content and by design it exposes privacy sensitive information, such as the ip address of the client. therefore the user's privacy must be kept in mind when deploying this header. a standardized version of this header is the http forwarded header. header type request header forbidden header name no syntax x-forwar...
X-Forwarded-Proto - HTTP
the x-forwarded-proto (xfp) header is a de-facto standard header for identifying the protocol (http or https) that a client used to connect to your proxy or load balancer. your server access logs contain the protocol used between the server and the load balancer, but not the protocol used between the client and the load balancer. to determine the protocol used between the client and the load balancer, the x-forwarded-proto request header can be used. a standardized version of this header is the http forwarded header. header type request header forbidden header name no syntax x-forwarded-proto: <protocol> directives <protocol> the forwarded protocol (http or https). examples x-forwarded-proto: https other non-standard forms: # microsoft front-end-h...
Proxy servers and tunneling - HTTP
quested resource and can be used to open a tunnel. this is how a client behind an http proxy can access websites using ssl (i.e. https, port 443). note, however, that not all proxy servers support the connect method or limit it to port 443 only. see also the http tunnel article on wikipedia. proxy auto-configuration (pac) a proxy auto-configuration (pac) file is a javascript function that determines whether web browser requests (http, https, and ftp) go directly to the destination or are forwarded to a web proxy server. the javascript function contained in the pac file defines the function: the auto-config file should be saved to a file with a .pac filename extension: proxy.pac and the mime type set to: application/x-ns-proxy-autoconfig the file consists of a function called findproxy...
HTTP Public Key Pinning (HPKP) - HTTP
ormation for a given period of time. when the client visits the server again, it expects at least one certificate in the certificate chain to contain a public key whose fingerprint is already known via hpkp. if the server delivers an unknown public key, the client should present a warning to the user. firefox and chrome disable pin validation for pinned hosts whose validated certificate chain terminates at a user-defined trust anchor (rather than a built-in trust anchor). this means that for users who imported custom root certificates all pinning violations are ignored. enabling hpkp to enable this feature for your site, you need to return the public-key-pins http header when your site is accessed over https: public-key-pins: pin-sha256="base64=="; max-age=expiretime [; includesubdomains]...
Redirections in HTTP - HTTP
abled. when possible, use http redirects and don't add <meta> element redirects. if someone changes the http redirects but forgets to change the html redirects, the redirects will no longer be identical, which could cause an infinite loop or other nightmares. use cases there are numerous use cases for redirects, but as performance is impacted with every redirect, their use should be kept to a minimum. domain aliasing ideally, there is one location, and therefore one url, for each resource. but there are reasons for alternative names for a resource: expanding the reach of your site a common case is when a site resides at www.example.com, but accessing it from example.com should also work. redirections for example.com to www.example.com are thus set up. you might also redirect from co...
HTTP resources and specifications - HTTP
this page lists relevant resources about http. ...
203 Non-Authoritative Information - HTTP
Web › HTTP › Status › 203
the 203 response is similar to the value 214, meaning transformation applied, of the warning header code, which has the additional advantage of being applicable to responses with any status code. ...
400 Bad Request - HTTP
Web › HTTP › Status › 400
the hypertext transfer protocol (http) 400 bad request response status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). the client should not repeat this request without modification. status 400 bad request specifications specification title rfc 7231, section 6.5.1: 400 bad request hypertext transfer protocol (http/1.1): semantics and content ...
500 Internal Server Error - HTTP
Web › HTTP › Status › 500
the hypertext transfer protocol (http) 500 internal server error server error response code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request. this error response is a generic "catch-all" response. usually, this indicates the server cannot find a better 5xx error code to response. sometimes, server administrators log error responses like the 500 status code with more details about the request to prevent the error from happening again in the future. status 500 internal server error specifications specification title rfc 7231, section 6.6.1: 500 internal server error hypertext transfer protocol (http/1.1): semantics and content ...
508 Loop Detected - HTTP
Web › HTTP › Status › 508
the hypertext transfer protocol (http) 508 loop detected response status code may be given in the context of the web distributed authoring and versioning (webdav) protocol. it indicates that the server terminated an operation because it encountered an infinite loop while processing a request with "depth: infinity". this status indicates that the entire operation failed. status 508 loop detected specifications specification title rfc 5842, section 7.2: 508 loop detected web distributed authoring and versioning ...
HTTP response status codes - HTTP
Web › HTTP › Status
ost famous one due to its frequent occurrence on the web. 405 method not allowed the request method is known by the server but has been disabled and cannot be used. for example, an api may forbid delete-ing a resource. the two mandatory methods, get and head, must never be disabled and should not return this error code. 406 not acceptable this response is sent when the web server, after performing server-driven content negotiation, doesn't find any content that conforms to the criteria given by the user agent. 407 proxy authentication required this is similar to 401 but authentication is needed to be done by a proxy. 408 request timeout this response is sent on an idle connection by some servers, even without any previous request by the client. it means that the server would like to s...
CSS Houdini
h great power comes great responsibility! with houdini you could invent your own masonry, grid, or regions implementation, but doing so is not necessarily the best idea. the css working group does a lot of work to ensure every feature is performant, handles all edge cases, and considers security, privacy, and accessibility. as you extend css with houdini, make sure to keep these considerations in mind, and start small before moving on to more ambitious projects. the houdini apis below you can find links to the main reference pages covering the apis that fall under the houdini umbrella, along with links to guides to help you if you need guidance in learning how to use them. start by reading houdini, an introduction — this provides a brief history of houdini and an overview of its many f...
Enumerability and ownership of properties - JavaScript
enumerable properties are those properties whose internal enumerable flag is set to true, which is the default for properties created via simple assignment or via a property initializer (properties defined via object.defineproperty and such default enumerable to false). enumerable properties show up in for...in loops unless the property's key is a symbol. ownership of properties is determined by whether the property belongs to the object directly and not to its prototype chain. properties of an object can also be retrieved in total. there are a number of built-in means of detecting, iterating/enumerating, and retrieving object properties, with the chart showing below which are available. some sample code follows which demonstrates how to obtain the missing categories. property enumerabil...
Control flow and error handling - JavaScript
name and message properties to get a more refined message. the name property provides the general class of error (such as domexception or error), while message generally provides a more succinct message than one would get by converting the error object to a string. if you are throwing your own exceptions, in order to take advantage of these properties (such as if your catch block doesn't discriminate between your own exceptions and system ones), you can use the error constructor. for example: function dosomethingerrorprone() { if (ourcodemakesamistake()) { throw (new error('the message')); } else { dosomethingtogetajavascripterror(); } } ⋮ try { dosomethingerrorprone(); } catch (e) { // now, we actually use `console.error()` console.error(e.name); // ...
Keyed collections - JavaScript
keys are held weakly, meaning that they are a target of garbage collection (gc) if there is no other reference to the object anymore. the weakmap api is the same as the map api. one difference to map objects is that weakmap keys are not enumerable (i.e., there is no method giving you a list of the keys). if they were, the list would depend on the state of garbage collection, introducing non-determinism. for more information and example code, see also "why weakmap?" on the weakmap reference page. one use case of weakmap objects is to store private data for an object, or to hide implementation details. the following example is from nick fitzgerald's blog post "hiding implementation details with ecmascript 6 weakmaps". the private data and methods belong inside the object and are stored in th...
Assertions - JavaScript
ample, /(?<=jack)sprat/ matches "sprat" only if it is preceded by "jack". /(?<=jack|tom)sprat/ matches "sprat" only if it is preceded by "jack" or "tom". however, neither "jack" nor "tom" is part of the match results. (?<!y)x negative lookbehind assertion: matches "x" only if "x" is not preceded by "y". for example, /(?<!-)\d+/ matches a number only if it is not preceded by a minus sign. /(?<!-)\d+/.exec('3') matches "3". /(?<!-)\d+/.exec('-3') match is not found because the number is preceded by the minus sign. examples general boundary-type overview example // using regex boundaries to fix buggy string. buggymultiline = `tey, ihe light-greon apple tangs on ihe greon traa`; // 1) use ^ to fix the matching at the begining of the string, and right after newl...
Quantifiers - JavaScript
the preceding item "x" 1 or more times. equivalent to {1,}. for example, /a+/ matches the "a" in "candy" and all the "a"'s in "caaaaaaandy". x? matches the preceding item "x" 0 or 1 times. for example, /e?le?/ matches the "el" in "angel" and the "le" in "angle." if used immediately after any of the quantifiers *, +, ?, or {}, makes the quantifier non-greedy (matching the minimum number of times), as opposed to the default, which is greedy (matching the maximum number of times). x{n} where "n" is a positive integer, matches exactly "n" occurrences of the preceding item "x". for example, /a{2}/ doesn't match the "a" in "candy", but it matches all of the "a"'s in "caandy", and the first two "a"'s in "caaandy". x{n,} where "n" is...
JavaScript Guide - JavaScript
indexed collections arrays typed arrays keyed collections map weakmap set weakset working with objects objects and properties creating objects defining methods getter and setter details of the object model prototype-based oop creating object hierarchies inheritance promises guarantees chaining error propagation composition timing iterators and generators iterators iterables generators meta programming proxy handlers and traps revocable proxy reflect javascript modules exporting importing default exports renaming features aggregating modules dynamic module loading next » ...
Inheritance and the prototype chain - JavaScript
guess the location of the method in the memory when calling an instance in advance, but setting the prototype dynamically disrupts all these optimizations and can even force some browsers to recompile for deoptimization your code just to make it work according to the specs. not supported in ie10 and below. prototype and object.getprototypeof javascript is a bit confusing for developers coming from java or c++, as it's all dynamic, all runtime, and it has no classes at all. it's all just instances (objects). even the "classes" we simulate are just a function object. you probably already noticed that our function a has a special property called prototype. this special property works with the javascript new operator. the reference to the prototype object is copied to the internal [[pro...
JavaScript language resources - JavaScript
this was the first version of the ecmascript standard. ecma-262 2nd edition pdf august 1998 ecmascript language specification. this is the second revision of the ecmascript standard; also iso standard 16262. ecma-262 3rd edition pdf december 1999 ecmascript language specification. this is the third revision of the ecmascript standard; corresponds to ...
Private class fields - JavaScript
there is however an experimental proposal to allow defining private class fields using a hash # prefix is added. syntax class classwithprivatefield { #privatefield } class classwithprivatemethod { #privatemethod() { return 'hello world' } } class classwithprivatestaticfield { static #private_static_field } examples private static fields private fields are accessible on the class constructor from inside the class declaration itself. the limitation of static variables being called by only static methods still holds. ...
The legacy Iterator protocol - JavaScript
lements a next() method with the following semantics, and throws stopiteration at the end of iteration. property value next a zero arguments function that returns an value. difference between legacy and es2015 iterator protocols the value was returned directly as a return value of calls to next, instead of the value property of a placeholder object iteration termination was expressed by throwing a stopiteration object. simple example with the old protocol function makeiterator(array){ var nextindex = 0; return { next: function(){ if(nextindex < array.length){ return array[nextindex++]; else throw new stopiteration(); } } } var it = makeiterator(['yo', 'ya']); console.log(it.
Warning: -file- is being assigned a //# sourceMappingURL, but already has one - JavaScript
already has one." occurs when a source map has been specified more than once for a given javascript source. message warning: -file- is being assigned a //# sourcemappingurl, but already has one. error type a warning. javascript execution won't be halted. what went wrong? a source map has been specified more than once for a given javascript source. javascript sources are often combined and minified to make delivering them from the server more efficient. with source maps, the debugger can map the code being executed to the original source files. 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/pat...
SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead - JavaScript
ntaxerror: using //@ to indicate sourceurl pragmas is deprecated. use //# instead warning: syntaxerror: using //@ to indicate sourcemappingurl pragmas is deprecated. use //# instead error type a warning that a syntaxerror occurred. javascript execution won't be halted. what went wrong? there is a deprecated source map syntax in a javascript source. javascript sources are often combined and minified to make delivering them from the server more efficient. with source maps, the debugger can map the code being executed to the original source files. the source map specification changed the syntax due to a conflict with ie whenever it was found in the page after //@cc_on was interpreted to turn on conditional compilation in the ie jscript engine. the conditional compilation comment in ie is...
SyntaxError: illegal character - JavaScript
position in the code. message syntaxerror: invalid character (edge) syntaxerror: illegal character (firefox) syntaxerror: invalid or unexpected token (chrome) error type syntaxerror what went wrong? there is an invalid or unexpected token that doesn't belong at this position in the code. use an editor that supports syntax highlighting and carefully check your code against mismatches like a minus sign ( - ) versus a dash ( – ) or simple quotes ( " ) vs non-standard quotation marks ( “ ). examples mismatched characters some characters look similar, but will cause the parser to fail interpreting your code. famous examples of this are quotes, the minus or semicolon (greek questionmark (u+37e) looks same). “this looks like a string”; // syntaxerror: illegal character ...
RangeError: invalid array length - JavaScript
let b = new array(math.pow(2, 32) - 1); b.length = b.length + 1; // set 2^32 to the length property valid cases [ math.pow(2, 40) ] // [ 1099511627776 ] [ -1 ] // [ -1 ] new arraybuffer(math.pow(2, 32) - 1) new arraybuffer(0) let a = []; a.length = math.max(0, a.length - 1); let b = new array(math.pow(2, 32) - 1); b.length = math.min(0xffffffff, b.length + 1); // 0xffffffff is the hexadecimal notation for 2^32 - 1 // which can also be written as (-1 >>> 0) ...
RangeError: invalid date - JavaScript
invalid time value (chrome) rangeerror: provided date is not in valid range (chrome) error type rangeerror what went wrong? a string leading to an invalid date has been provided to date or date.parse(). examples invalid cases unrecognizable strings or dates containing illegal element values in iso formatted strings usually return nan. however, depending on the implementation, non–conforming iso format strings, may also throw rangeerror: invalid date, like the following cases in firefox: new date('foo-bar 2014'); new date('2014-25-23').toisostring(); new date('foo-bar 2014').tostring(); this, however, returns nan in firefox: date.parse('foo-bar 2014'); // nan for more details, see the date.parse() documentation. valid cases new date('05 october 2011 14:48 utc'); new date(1317...
SyntaxError: missing name after . operator - JavaScript
; var i = 2; obj.[foo].[bar] // syntaxerror: missing name after . operator obj.foo."bar"+i; // syntaxerror: missing name after . operator to fix this code, you need to access the object like this: obj.foo.bar; // "baz" // or alternatively obj["foo"]["bar"]; // "baz" // computed properties require square brackets obj.foo["bar" + i]; // "baz2" property access vs. concatenation if you are coming from another programming language (like php), it is also easy to mix up the dot operator (.) and the concatenation operator (+). console.log("hello" . "world"); // syntaxerror: missing name after . operator instead you need to use a plus sign for concatenation: console.log("hello" + "world"); ...
TypeError: variable "x" redeclares argument - JavaScript
me variable name occurs as a function parameter and is then redeclared using a var assignment in a function body again. message typeerror: variable "x" redeclares argument (firefox) error type typeerror warning in strict mode only. what went wrong? the same variable name occurs as a function parameter and is then redeclared using a var assignment in a function body again. this might be a naming conflict and thus javascript warns about it. this error occurs as a warning in strict mode code only. in non-strict code, the redeclaration is silently ignored. examples invalid cases in this case, the variable "arg" redeclares the argument. 'use strict'; function f(arg) { var arg = 'foo'; } valid cases to fix this warning, the var statement can just be omitted, because the variable e...
TypeError: cannot use 'in' operator to search for 'x' in 'y' - JavaScript
dge) typeerror: right-hand side of 'in' should be an object, got 'x' (firefox) typeerror: cannot use 'in' operator to search for 'x' in 'y' (firefox, chrome) error type typeerror what went wrong? the in operator can only be used to check if a property is in an object. you can't search in strings, or in numbers, or other primitive types. examples searching in strings unlike in other programming languages (e.g. python), you can't search in strings using the in operator. "hello" in "hello world"; // typeerror: cannot use 'in' operator to search for 'hello' in 'hello world' instead you will need to use string.prototype.indexof(), for example. "hello world".indexof("hello") !== -1; // true the operand can't be null or undefined make sure the object you are inspecting isn't actually nu...
JavaScript error reference - JavaScript
axerror: missing ] after element listsyntaxerror: missing formal parametersyntaxerror: missing name after . ...
Functions - JavaScript
nitialize return value as string var numzeros = totallen - numstr.length; // calculate no. of zeros for (var i = 1; i <= numzeros; i++) { numstr = "0" + numstr; } return numstr; } the following statements call the padzeros function. var result; result = padzeros(42,4); // returns "0042" result = padzeros(42,2); // returns "42" result = padzeros(5,4); // returns "0005" determining whether a function exists you can determine whether a function exists by using the typeof operator. in the following example, a test is performed to determine if the window object has a property called nofunc that is a function. if so, it is used; otherwise, some other action is taken. if ('function' === typeof window.nofunc) { // use nofunc() } else { // do something else } note ...
Array.prototype.fill() - JavaScript
) { // steps 1-2. if (this == null) { throw new typeerror('this is null or not defined'); } var o = object(this); // steps 3-5. var len = o.length >>> 0; // steps 6-7. var start = arguments[1]; var relativestart = start >> 0; // step 8. var k = relativestart < 0 ? math.max(len + relativestart, 0) : math.min(relativestart, len); // steps 9-10. var end = arguments[2]; var relativeend = end === undefined ? len : end >> 0; // step 11. var finalvalue = relativeend < 0 ? math.max(len + relativeend, 0) : math.min(relativeend, len); // step 12. while (k < finalvalue) { o[k] = value; k++; } // step 13. ret...
Array.prototype.toSource() - JavaScript
the following values: for the built-in array object, tosource returns the following string indicating that the source code is not available: function array() { [native code] } for instances of array, tosource returns a string representing the source code. this method is usually called internally by javascript and not explicitly in code. you can call tosource while debugging to examine the contents of an array. examples examining the source code of an array to examine the source code of an array: var alpha = new array('a', 'b', 'c'); alpha.tosource(); //returns ['a', 'b', 'c'] specifications not part of any standard. implemented in javascript 1.3. ...
ArrayBuffer.isView() - JavaScript
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax arraybuffer.isview(value) parameters value the value to be checked. return value true if the given argument is one of the arraybuffer views; otherwise, false. ...
Atomics.isLockFree() - JavaScript
it returns true, if the given size is one of the bytes_per_element property of integer typedarray types. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax atomics.islockfree(size) parameters size the size in bytes to check. return value a boolean indicating whether the operation is lock free. ...
Atomics - JavaScript
ue at the specified index of the array with the provided value. returns the old value at that index. atomics.compareexchange() stores a value at the specified index of the array, if it equals a value. returns the old value. atomics.exchange() stores a value at the specified index of the array. returns the old value. atomics.islockfree(size) an optimization primitive that can be used to determine whether to use locks or atomic operations. 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). experts only. atomics.load() returns the value at the specified index of the array. atomics.notify() notifies agents that are waiting on the specified index of the array. returns the number of agents t...
BigInt.prototype.toLocaleString() - JavaScript
.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,123,456,789 // limit to three significant digits console.log(bigint.tolocalestring('en-in', { maximumsignificantdigits: 3 })); // → 1,23,00,00,00,00,00,00,000 specifications specification ecmascript (ecma-262)the definition of 'bigint.prototype.tolocalestring()...
BigInt64Array - JavaScript
nd. see also array.prototype.find(). bigint64array.prototype.findindex() returns the found index in the array if an element in the array satisfies the provided testing function, or -1 if not found. see also array.prototype.findindex(). bigint64array.prototype.foreach() calls a function for each element in the array. see also array.prototype.foreach(). bigint64array.prototype.includes() determines whether a typed array includes a certain element, returning true or false as appropriate. see also array.prototype.includes(). bigint64array.prototype.indexof() returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. see also array.prototype.indexof(). bigint64array.prototype.join() joins all elements of an array into a string. se...
BigUint64Array - JavaScript
see also array.prototype.find(). biguint64array.prototype.findindex() returns the found index in the array if an element in the array satisfies the provided testing function, or -1 if not found. see also array.prototype.findindex(). biguint64array.prototype.foreach() calls a function for each element in the array. see also array.prototype.foreach(). biguint64array.prototype.includes() determines whether a typed array includes a certain element, returning true or false as appropriate. see also array.prototype.includes(). biguint64array.prototype.indexof() returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. see also array.prototype.indexof(). biguint64array.prototype.join() joins all elements of an array into a string. ...
Date.prototype.getTime() - JavaScript
active example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax dateobj.gettime() return value a number representing the milliseconds elapsed between 1 january 1970 00:00:00 utc and the given date. reduced time precision to offer protection against timing attacks and fingerprinting, the precision of new date().gettime() might get rounded depending on browser settings. in firefox, the privacy.reducetimerprecision preference is enabled by default and defaults to 20µs in firefox 59; in 60 it will be 2ms. // reduced time precision (2ms) in firefox 60 new date().gettime(); // 1519211809934 // 1519211810362 // 1519211811670 // ... // reduced time ...
Date.prototype.getUTCMilliseconds() - JavaScript
not to be confused with unix epoch time. ...
Date.now() - JavaScript
ting the milliseconds elapsed since the unix epoch. polyfill this method was standardized in ecma-262 5th edition. 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. in firefox, the privacy.reducetimerprecision preference is enabled by default and defaults to 20µs in firefox 59; in 60 it will be 2ms. // reduced time precision (2ms) in firefox 60 date.now() // 1519211809934 // 1519211810362 // 1519211811670 // ... // reduced time precision with `priv...
Date.parse() - JavaScript
gnized as an iso format string and it contains invalid values, it will return nan in all browsers compliant with es5 and later: // iso string with invalid values new date('2014-25-23').toisostring(); // throws "rangeerror: invalid date" in all es5-compliant browsers spidermonkey's implementation-specific heuristic can be found in jsdate.cpp. the string "10 06 2014" is an example of a non-conforming iso format and thus falls back to a custom routine. see also this rough outline on how the parsing works. new date('10 06 2014'); will be treated as a local date of 6 october, 2014, and not 10 june, 2014. other examples: new date('foo-bar 2014').tostring(); // returns: "invalid date" date.parse('foo-bar 2014'); // returns: nan differences in assumed time zone this section contains impl...
Date.prototype.setSeconds() - JavaScript
number of milliseconds between 1 january 1970 00:00:00 utc and the updated date. description if you do not specify the msvalue parameter, the value returned from the getmilliseconds() method is used. if a parameter you specify is outside of the expected range, setseconds() attempts to update the date information in the date object accordingly. for example, if you use 100 for secondsvalue, the minutes stored in the date object will be incremented by 1, and 40 will be used for seconds. 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.setUTCSeconds() - JavaScript
r of milliseconds between 1 january 1970 00:00:00 utc and the updated date. description if you do not specify the msvalue parameter, the value returned from the getutcmilliseconds() method is used. if a parameter you specify is outside of the expected range, setutcseconds() attempts to update the date information in the date object accordingly. for example, if you use 100 for secondsvalue, the minutes stored in the date object will be incremented by 1, and 40 will be used for seconds. 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.toDateString() - JavaScript
dateobj.todatestring() return value a string representing the date portion of the given date object in human readable form in english. description date instances refer to a specific point in time. calling tostring() will return the date formatted in a human readable form in english. in spidermonkey, this consists of the date portion (day, month, and year) followed by the time portion (hours, minutes, seconds, and time zone). sometimes it is desirable to obtain a string of the time portion; such a thing can be accomplished with the totimestring() method. the todatestring() method is especially useful because compliant engines implementing ecma-262 may differ in the string obtained from tostring() for date objects, as the format is implementation-dependent and simple string slicing approa...
Date.prototype.toISOString() - JavaScript
!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 correc...
Date.prototype.toString() - JavaScript
prototype. date.prototype.tostring() returns a string representation of the date in the format specified in ecma-262 which can be summarised as: week day: 3 letter english week day name, e.g. "sat" space month name: 3 letter english month name, e.g. "sep" space date: 2 digit day in month, e.g. "01" space year: 4 digit year, e.g. "2018" space hour: 2 digit hour of day, e.g. "14" colon minute: 2 digit minute of hour, e.g. "53" colon second: 2 digit second of minute, e.g. "26" space the string "gmt" timezone offset sign, either: "+" for positive offsets (0 or greater) "-" for negative offsets (less than zero) two digit hour offset, e.g. "14" two digit minute offset, e.g. "00" optionally, a timezone name consisting of: space left bracket, i.e. "(" an...
Date.prototype.toTimeString() - JavaScript
timestring() return value a string representing the time portion of the given date in human readable form in american english. description date instances refer to a specific point in time. calling tostring() will return the date formatted in a human readable form in american english. in spidermonkey, this consists of the date portion (day, month, and year) followed by the time portion (hours, minutes, seconds, and time zone). sometimes it is desirable to obtain a string of the time portion; such a thing can be accomplished with the totimestring() method. the totimestring() method is especially useful because compliant engines implementing ecma-262 may differ in the string obtained from tostring() for date objects, as the format is implementation-dependent; simple string slicing approache...
Date.prototype.toUTCString() - JavaScript
format sring description www day of week, as three letters (e.g. sun, mon, ...) dd day of month, as two digits with leading zero if required mmm month, as three letters (e.g. jan, feb, ...) yyyy year, as four or more digits with leading zeroes if required hh hour, as two digits with leading zero if required mm minute, as two digits with leading zero if required ss seconds, as two digits with leading zero if required prior to ecmascript 2018, the format of the return value varied according to the platform. the most common return value was an rfc-1123 formatted date stamp, which is a slightly updated version of rfc-822 date stamps. examples using toutcstring() let today = new date('wed,...
Error.prototype.stack - JavaScript
he stack property the following html markup demonstrates the use of stack property. ...
Error.prototype.toString() - JavaScript
the tostring() method returns a string representing the specified error object. syntax e.tostring() return value a string representing the specified error object. description the error object overrides the object.prototype.tostring() method inherited by all objects. ...
FinalizationRegistry - JavaScript
complex factors may lead to objects being held alive for unexpected amounts of time, such as use with certain apis. notes on cleanup callbacks some notes on cleanup callbacks: developers shouldn't rely on cleanup callbacks for essential program logic. cleanup callbacks may be useful for reducing memory usage across the course of a program, but are unlikely to be useful otherwise. a conforming javascript implementation, even one that does garbage collection, is not required to call cleanup callbacks. when and whether it does so is entirely down to the implementation of the javascript engine. when a registered object is reclaimed, any cleanup callbacks for it may be called then, or some time later, or not at all. it's likely that major implementations will call cleanup callbacks at so...
Float32Array - JavaScript
found. see also array.prototype.find(). float32array.prototype.findindex() returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. see also array.prototype.findindex(). float32array.prototype.foreach() calls a function for each element in the array. see also array.prototype.foreach(). float32array.prototype.includes() determines whether a typed array includes a certain element, returning true or false as appropriate. see also array.prototype.includes(). float32array.prototype.indexof() returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. see also array.prototype.indexof(). float32array.prototype.join() joins all elements of an array into a string. see ...
Float64Array - JavaScript
found. see also array.prototype.find(). float64array.prototype.findindex() returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. see also array.prototype.findindex(). float64array.prototype.foreach() calls a function for each element in the array. see also array.prototype.foreach(). float64array.prototype.includes() determines whether a typed array includes a certain element, returning true or false as appropriate. see also array.prototype.includes(). float64array.prototype.indexof() returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. see also array.prototype.indexof(). float64array.prototype.join() joins all elements of an array into a string. see ...
Function.prototype.bind() - JavaScript
object to a real array. you could create a shortcut like this: const slice = array.prototype.slice; // ... slice.apply(arguments); with bind(), this can be simplified. in the following piece of code, slice() is a bound function to the apply() function of function.prototype, with the this value set to the slice() function of array.prototype. this means that additional apply() calls can be eliminated: // same as "slice" in the previous example const unboundslice = array.prototype.slice; const slice = function.prototype.apply.bind(unboundslice); // ... slice(arguments); specifications specification ecmascript (ecma-262)the definition of 'function.prototype.bind' in that specification. ...
Function.name - JavaScript
ject, please clone https://github.com/mdn/interactive-examples and send us a pull request. property attributes of function.name writable no enumerable no configurable yes note that in non-standard, pre-es2015 implementations the configurable attribute was false as well. 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. these tools are often used as part of a javascript build pipeline to reduce the size of a program prior to deploying it to production. such transformations often change a function's name at build-time. source code such as: functio...
Function.prototype.toSource() - JavaScript
syntax function.tosource(); return value a string representing the source code of the object. ...
Int16Array - JavaScript
f not found. see also array.prototype.find(). int16array.prototype.findindex() returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. see also array.prototype.findindex(). int16array.prototype.foreach() calls a function for each element in the array. see also array.prototype.foreach(). int16array.prototype.includes() determines whether a typed array includes a certain element, returning true or false as appropriate. see also array.prototype.includes(). int16array.prototype.indexof() returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. see also array.prototype.indexof(). int16array.prototype.join() joins all elements of an array into a string. see also...
Int32Array - JavaScript
f not found. see also array.prototype.find(). int32array.prototype.findindex() returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. see also array.prototype.findindex(). int32array.prototype.foreach() calls a function for each element in the array. see also array.prototype.foreach(). int32array.prototype.includes() determines whether a typed array includes a certain element, returning true or false as appropriate. see also array.prototype.includes(). int32array.prototype.indexof() returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. see also array.prototype.indexof(). int32array.prototype.join() joins all elements of an array into a string. see also...
Int8Array - JavaScript
d if not found. see also array.prototype.find(). int8array.prototype.findindex() returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. see also array.prototype.findindex(). int8array.prototype.foreach() calls a function for each element in the array. see also array.prototype.foreach(). int8array.prototype.includes() determines whether a typed array includes a certain element, returning true or false as appropriate. see also array.prototype.includes(). int8array.prototype.indexof() returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. see also array.prototype.indexof(). int8array.prototype.join() joins all elements of an array into a string. see also a...
Intl.Collator.supportedLocalesOf() - JavaScript
without having to fall back to the runtime's default locale. description returns an array with a subset of the language tags provided in locales. the language tags returned are those for which the runtime supports a locale in collation that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. examples using supportedlocalesof assuming a runtime that supports indonesian and german but not balinese in collation, supportedlocalesof returns the indonesian and german language tags unchanged, even though pinyin collation is not used with indonesian and a specialized german for indonesia is unlikely to be supported. note the specification of the "lookup" algorithm here — a "best fit" matcher might decide that indonesian is an adeq...
Intl.DateTimeFormat.prototype.format() - JavaScript
idirectional control characters around dates, so the output text will flow properly when concatenated with other text. for this reason you cannot expect to be able to compare the results of format() to a static value: let d = new date("2019-01-01t00:00:00.000000z"); let formatteddate = intl.datetimeformat(undefined, { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' }).format(d); "1.1.2019, 01:00:00" === formatteddate; // true in firefox and others // false in ie and edge note: see also this stackoverflow thread for more details and examples. specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.datetimeformat.format' in that specification. ...
Intl.DateTimeFormat.prototype.formatRange() - JavaScript
1 = new date(date.utc(2007, 0, 10, 10, 0, 0)); let date2 = new date(date.utc(2007, 0, 10, 11, 0, 0)); let date3 = new date(date.utc(2007, 0, 20, 10, 0, 0)); // > 'wed, 10 jan 2007 10:00:00 gmt' // > 'wed, 10 jan 2007 11:00:00 gmt' // > 'sat, 20 jan 2007 10:00:00 gmt' let fmt1 = new intl.datetimeformat("en", { year: '2-digit', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric' }); console.log(fmt1.format(date1)); console.log(fmt1.formatrange(date1, date2)); console.log(fmt1.formatrange(date1, date3)); // > '1/10/07, 10:00 am' // > '1/10/07, 10:00 – 11:00 am' // > '1/10/07, 10:00 am – 1/20/07, 10:00 am' let fmt2 = new intl.datetimeformat("en", { year: 'numeric', month: 'short', day: 'numeric' }); console.log(fmt2.format(date1)); console.lo...
Intl.DateTimeFormat.prototype.resolvedOptions() - JavaScript
options argument; undefined (representing the runtime's default time zone) if none was provided. warning: applications should not rely on undefined being returned, as future versions may return a string value identifying the runtime’s default time zone instead. hour12 the value provided for this property in the options argument or filled in as a default. weekday era year month day hour minute second timezonename the values resulting from format matching between the corresponding properties in the options argument and the available combinations and representations for date-time formatting in the selected locale. some of these properties may not be present, indicating that the corresponding components will not be represented in formatted output. examples using the resolvedoptio...
Intl.DateTimeFormat.supportedLocalesOf() - JavaScript
to fall back to the runtime's default locale. description returns an array with a subset of the language tags provided in locales. the language tags returned are those for which the runtime supports a locale in date and time formatting that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. examples using supportedlocalesof assuming a runtime that supports indonesian and german but not balinese in date and time formatting, supportedlocalesof returns the indonesian and german language tags unchanged, even though pinyin collation is neither relevant to date and time formatting nor used with indonesian, and a specialized german for indonesia is unlikely to be supported. note the specification of the "lookup" algorithm here —...
Intl.DisplayNames.supportedLocalesOf() - JavaScript
to fall back to the runtime's default locale. description returns an array with a subset of the language tags provided in locales. the language tags returned are those for which the runtime supports a locale in date and time formatting that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. examples using supportedlocalesof assuming a runtime that supports indonesian and german but not balinese in date and time formatting, supportedlocalesof returns the indonesian and german language tags unchanged, even though pinyin collation is neither relevant to date and time formatting nor used with indonesian, and a specialized german for indonesia is unlikely to be supported. note the specification of the "lookup" algorithm here —...
Intl.ListFormat.supportedLocalesOf() - JavaScript
to fall back to the runtime's default locale. description returns an array with a subset of the language tags provided in locales. the language tags returned are those for which the runtime supports a locale in date and time formatting that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. examples using supportedlocalesof assuming a runtime that supports indonesian and german but not balinese in date and time formatting, supportedlocalesof returns the indonesian and german language tags unchanged, even though pinyin collation is neither relevant to date and time formatting nor used with indonesian, and a specialized german for indonesia is unlikely to be supported. note the specification of the "lookup" algorithm here —...
Intl.Locale.prototype.caseFirst - JavaScript
certain locales use a character's case (uppercase or lowercase) in the collation process. this additional rule can be expressed in a locale's casefirst property. there are 3 values that the casefirst property can have, outlined in the table below. ...
Intl.Locale - JavaScript
locale.prototype.region returns the region of the world (usually a country) associated with the locale. intl.locale.prototype.script returns the script used for writing the particular language used in the locale. instance methods intl.locale.prototype.maximize() gets the most likely values for the language, script, and region of the locale based on existing values. intl.locale.prototype.minimize() gets the most likely values for the language, script, and region of the locale based on existing values. intl.locale.prototype.tostring() returns the locale's full locale identifier string. 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 ...
Intl.NumberFormat.prototype.formatToParts() - JavaScript
urrency the currency string, such as the symbols "$" and "€" or the name "dollar", "euro" depending on how currencydisplay is specified. decimal the decimal separator string ("."). fraction the fraction number. group the group separator string (","). infinity the infinity string ("∞"). integer the integer number. literal any literal strings or whitespace in the formatted number. minussign the minus sign string ("-"). nan the nan string ("nan"). plussign the plus sign string ("+"). percentsign the percent sign string ("%"). examples comparing format and formattoparts numberformat outputs localized, opaque strings that cannot be manipulated directly: var number = 3500; var formatter = new intl.numberformat('de-de', { style: 'currency', currency: 'eur' }); ...
Intl.NumberFormat.supportedLocalesOf() - JavaScript
having to fall back to the runtime's default locale. description returns an array with a subset of the language tags provided in locales. the language tags returned are those for which the runtime supports a locale in number formatting that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. examples using supportedlocalesof assuming a runtime that supports indonesian and german but not balinese in number formatting, supportedlocalesof returns the indonesian and german language tags unchanged, even though pinyin collation is neither relevant to number formatting nor used with indonesian, and a specialized german for indonesia is unlikely to be supported. note the specification of the "lookup" algorithm here — a "best fit" ...
Intl.NumberFormat - JavaScript
e, 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 console.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...
Intl.PluralRules.supportedLocalesOf() - JavaScript
aving to fall back to the runtime's default locale. description returns an array with a subset of the language tags provided in locales. the language tags returned are those for which the runtime supports a locale in plural formatting that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. examples using supportedlocalesof() assuming a runtime that supports indonesian and german but not balinese in plural formatting, supportedlocalesof returns the indonesian and german language tags unchanged, even though pinyin collation is neither relevant to plural formatting nor used with indonesian, and a specialized german for indonesia is unlikely to be supported. note the specification of the lookup algorithm here — a best fit matc...
Intl.RelativeTimeFormat.prototype.format() - JavaScript
he interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax relativetimeformat.format(value, unit) parameters value numeric value to use in the internationalized relative time message. unit unit to use in the relative time internationalized message. possible values are: "year", "quarter", "month", "week", "day", "hour", "minute", "second". plural forms are also permitted. description the function returned by the format getter formats a value and a unit into a string according to the locale and formatting options of this intl.relativetimeformat object. examples basic format usage the following example shows how to create a relative time formatter using the english language. // create a relative time formatter i...
Intl.RelativeTimeFormat.prototype.formatToParts() - JavaScript
ractive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax relativetimeformat.formattoparts(value, unit) parameters value numeric value to use in the internationalized relative time message. unit unit to use in the relative time internationalized message. possible values are: "year", "quarter", "month", "week", "day", "hour", "minute", "second". plural forms are also permitted. return value an array of objects containing the formatted relative time in parts. description the intl.relativetimeformat.prototype.formattoparts method is a version of the format method which it returns an array of objects which represent "parts" of the object, separating the formatted number into its consituent parts and separating it from ot...
Intl.RelativeTimeFormat.supportedLocalesOf() - JavaScript
to fall back to the runtime's default locale. description returns an array with a subset of the language tags provided in locales. the language tags returned are those for which the runtime supports a locale in date and time formatting that the locale matching algorithm used considers a match, so that it wouldn't have to fall back to the default locale. examples using supportedlocalesof assuming a runtime that supports indonesian and german but not balinese in date and time formatting, supportedlocalesof returns the indonesian and german language tags unchanged, even though pinyin collation is neither relevant to date and time formatting nor used with indonesian, and a specialized german for indonesia is unlikely to be supported. note the specification of the "lookup" algorithm here —...
JSON.parse() - JavaScript
.replace(rx_three, "]") .replace(rx_four, "") ) ) { // in the third stage we use the eval function to compile the text into a // javascript structure. the "{" operator is subject to a syntactic ambiguity // in javascript: it can begin a block or an object literal. we wrap the text // in parens to eliminate the ambiguity. j = eval("(" + text + ")"); // in the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return (typeof reviver === "function") ? walk({ "": j }, "") : j; } ...
JSON.stringify() - JavaScript
s part of a jsonp url, and the following utility can be used: function jsfriendlyjsonstringify (s) { return json.stringify(s). replace(/\u2028/g, '\\u2028'). replace(/\u2029/g, '\\u2029'); } var s = { a: string.fromcharcode(0x2028), b: string.fromcharcode(0x2029) }; try { eval('(' + json.stringify(s) + ')'); } catch (e) { console.log(e); // "syntaxerror: unterminated string literal" } // no need for a catch eval('(' + jsfriendlyjsonstringify(s) + ')'); // console.log in firefox unescapes the unicode if // logged to console, so we use alert alert(jsfriendlyjsonstringify(s)); // {"a":"\u2028","b":"\u2029"} note: properties of non-array objects are not guaranteed to be stringified in any particular order. do not rely on ordering of properties within t...
Map.prototype.forEach() - JavaScript
sent but have the value undefined. callback is invoked with three arguments: the entry's value the entry's key the map object being traversed if a thisarg parameter is provided to foreach, it will be passed to callback when invoked, for use as its this value. otherwise, the value undefined will be passed for use as its this value. the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. each value is visited once, except in the case when it was deleted and re-added before foreach has finished. callback is not invoked for values deleted before being visited. new values added before foreach has finished will be visited. foreach executes the callback function once for each element in the map object. it do...
Math.log1p() - JavaScript
sitory. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax math.log1p(x) parameters x a number. return value the natural logarithm (base e) of 1 plus the given number. if the number is less than -1, nan is returned. description for very small values of x, adding 1 can reduce or eliminate precision. the double floats used in js give you about 15 digits of precision. 1 + 1e-15 = 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off. when you calculate log(1 + x), you should get an answer very close to x, if x is small (that's why these are called 'natural' logarithms). if you calculate math...
NaN - JavaScript
configurable, non-writable property. even when this is not the case, avoid overriding it. it is rather rare to use nan in a program. there are five different types of operations that return nan: number cannot be parsed (e.g. parseint("blabla") or number(undefined)) math operation where the result is not a real number (e.g. math.sqrt(-1)) operand of an argument is nan (e.g. 7 ** nan) indeterminate form (e.g. 0 * infinity) any operation that involves a string and is not an addition operation (e.g. "foo"/3) examples testing against nan nan compares unequal (via ==, !=, ===, and !==) to any other value -- including to another nan value. use number.isnan() or isnan() to most clearly determine whether a value is nan. or perform a self-comparison: nan, and only nan, will compare unequal ...
Number.NEGATIVE_INFINITY - JavaScript
nite number in case of success. note, however, that isfinite would be more appropriate in such a case. because negative_infinity is a static property of number, you always use it as number.negative_infinity, rather than as a property of a number object you created. examples using negative_infinity in the following example, the variable smallnumber is assigned a value that is smaller than the minimum value. when the if statement executes, smallnumber has the value -infinity, so smallnumber is set to a more manageable value before continuing. var smallnumber = (-number.max_value) * 2; if (smallnumber === number.negative_infinity) { smallnumber = returnfinite(); } specifications specification ecmascript (ecma-262)the definition of 'number.negative_infinity' in that ...
Number.isFinite() - JavaScript
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax number.isfinite(value) parameters value the value to be tested for finiteness. return value a boolean indicating whether or not the given value is a finite number. description in comparison to the global isfinite() function, this method doesn't forcibly convert the parameter to a number. this means only values of the type number, that are also finite, return true. ...
Number.isInteger() - JavaScript
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax number.isinteger(value) parameters value the value to be tested for being an integer. return value a boolean indicating whether or not the given value is an integer. description if the target value is an integer, return true, otherwise return false. if the value is nan or infinity, return false. the method will also return true for floating point numbers that can be represented as integer. ...
Number.isNaN() - JavaScript
it is a more robust version of the original, global isnan(). the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax number.isnan(value) parameters value the value to be tested for nan. return value true if the given value is nan and its type is number; otherwise, false. description due to both equality operators, == and ===, evaluating to false when checking if nan is nan, the function number.isnan() has become necessary. ...
Number.isSafeInteger() - JavaScript
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. a safe integer is an integer that can be exactly represented as an ieee-754 double precision number, and whose ieee-754 representation cannot be the result of rounding any other integer to fit the ieee-754 representation. for example, 253 - 1 is a safe integer: it can be exactly represented, and no other integer rounds to it under any ieee-754 rounding mode. ...
Number.prototype.toLocaleString() - JavaScript
uage, 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('en-in', { maximumsignificantdigits: 3 })); // → 1,23,000 // use the host default language with options for number formatting var num = 30000.65; console.log(num.tolocalestring(undefined, {minimumfractiondigits: 2, ...
Object.create() - JavaScript
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 o...
Object.defineProperties() - JavaScript
o setter. the function will receive as its only argument the new value being assigned to the property. defaults to undefined. if a descriptor has neither of value, writable, get and set keys, it is treated as a data descriptor. if a descriptor has both value or writable and get or set keys, an exception is thrown. return value the object that was passed to the function. ...
Object.defineProperty() - JavaScript
erty is assigned, this function is called with one argument (the value being assigned to the property) and with this set to the object through which the property is assigned. defaults to undefined. if a descriptor has neither of value, writable, get and set keys, it is treated as a data descriptor. if a descriptor has both value or writable and get or set keys, an exception is thrown. bear in mind that these attributes are not necessarily the descriptor's own properties. inherited properties will be considered as well. in order to ensure these defaults are preserved, you might freeze the object.prototype upfront, specify all options explicitly, or point to null with object.create(null). // using __proto__ var obj = {}; var descriptor = object.create(null); // no inherited properties desc...
Object.getOwnPropertyDescriptor() - JavaScript
om/mdn/interactive-examples and send us a pull request. syntax object.getownpropertydescriptor(obj, prop) parameters obj the object in which to look for the property. prop the name or symbol of the property whose description is to be retrieved. return value a property descriptor of the given property if it exists on the object, undefined otherwise. description this method permits examination of the precise description of a property. a property in javascript consists of either a string-valued name or a symbol and a property descriptor. further information about property descriptor types and their attributes can be found in object.defineproperty(). a property descriptor is a record with some of the following attributes: value the value associated with the property (data descr...
Object.getOwnPropertyDescriptors() - JavaScript
the object.getownpropertydescriptors() method returns all own property descriptors of a given object. syntax object.getownpropertydescriptors(obj) parameters obj the object for which to get all own property descriptors. return value an object containing all own property descriptors of an object. might be an empty object, if there are no properties. description this method permits examination of the precise description of all own properties of an object. a property in javascript consists of either a string-valued name or a symbol and a property descriptor. further information about property descriptor types and their attributes can be found in object.defineproperty(). a property descriptor is a record with some of the following attributes: value the value associated with the...
Object.is() - JavaScript
the object.is() method determines whether two values are the same value. syntax object.is(value1, value2); parameters value1 the first value to compare. value2 the second value to compare. return value a boolean indicating whether or not the two arguments are the same value. description object.is() determines whether two values are the same value. two values are the same if one of the following holds: both undefined both null both true or both false both strings of the same length with the same characters in the same order both the same object (means both object have same reference) both numbers and both +0 both -0 both nan or both non-zero and both not nan and both have the same value this is not the same as being equal according to the == operato...
Object.isExtensible() - JavaScript
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax object.isextensible(obj) parameters obj the object which should be checked. return value a boolean indicating whether or not the given object is extensible. description objects are extensible by default: they can have new properties added to them, and (in engines that support __proto__) their __proto__ property can be modified. ...
Object.isFrozen() - JavaScript
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax object.isfrozen(obj) parameters obj the object which should be checked. return value a boolean indicating whether or not the given object is frozen. description an object is frozen if and only if it is not extensible, all its properties are non-configurable, and all its data properties (that is, properties which are not accessor properties with getter or setter components) are non-writable. ...
Object.isSealed() - JavaScript
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax object.issealed(obj) parameters obj the object which should be checked. return value a boolean indicating whether or not the given object is sealed. description returns true if the object is sealed, otherwise false. an object is sealed if it is not extensible and if all its properties are non-configurable and therefore not removable (but not necessarily non-writable). examples using object.issealed // objects aren't sealed by default. ...
Object.prototype.propertyIsEnumerable() - JavaScript
ve examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax obj.propertyisenumerable(prop) parameters prop the name of the property to test. return value a boolean indicating whether the specified property is enumerable and is the object's own property. description every object has a propertyisenumerable method. this method can determine whether the specified property in an object can be enumerated by a for...in loop, with the exception of properties inherited through the prototype chain. if the object does not have the specified property, this method returns false. examples a basic use of propertyisenumerable the following example shows the use of propertyisenumerable on objects and arrays: var o = {}; var a = []; o.prop = ...
Object.setPrototypeOf() - JavaScript
ction mammalspecies(smammalspecies) { this.species = smammalspecies; } mammalspecies.prototype = new mammal(); mammalspecies.prototype.constructor = mammalspecies; var ocat = new mammalspecies('felis'); console.log(ocat.ismammal); // 'yes' function animal() { this.breathing = 'yes'; } object.appendchain(ocat, new animal()); console.log(ocat.breathing); // 'yes' second example: transforming a primitive value into an instance of its constructor and append its chain to a prototype function mysymbol() { this.issymbol = 'yes'; } var nprime = 17; console.log(typeof nprime); // 'number' var oprime = object.appendchain(nprime, new mysymbol()); console.log(oprime); // '17' console.log(oprime.issymbol); // 'yes' console.log(typeof oprime); // 'object' third example: appending a cha...
Object.prototype.toSource() - JavaScript
the source code of the object. description the tosource() method returns the following values: for the built-in object object, tosource() returns the following string indicating that the source code is not available: function object() { [native code] } for instances of object, tosource() returns a string representing the source code. you can call tosource() while debugging to examine the contents of an object. overriding the tosource() method it is safe for objects to override the tosource() method. for example: function person(name) { this.name = name; } person.prototype.tosource = function person_tosource() { return 'new person(' + uneval(this.name) + ')'; }; console.log(new person('joe').tosource()); // ---> new person("joe") built-in tosource() methods each c...
Object.prototype.toString() - JavaScript
t(); o.tostring(); // returns [object object] note: starting in javascript 1.8.5, tostring() called on null returns [object null], and undefined returns [object undefined], as defined in the 5th edition of ecmascript and subsequent errata. see using tostring() to detect object class. parameters for numbers and bigints tostring() takes an optional parameter radix the value of radix must be minimum 2 and maximum 36. 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 out...
Object - JavaScript
propertysymbols() returns an array of all symbol properties found directly upon a given object. object.getprototypeof() returns the prototype (internal [[prototype]] property) of the specified object. object.is() compares if two values are the same value. equates all nan values (which differs from both abstract equality comparison and strict equality comparison). object.isextensible() determines if extending of an object is allowed. object.isfrozen() determines if an object was frozen. object.issealed() determines if an object is sealed. object.keys() returns an array containing the names of all of the given object's own enumerable string properties. object.preventextensions() prevents any extensions of an object. object.seal() prevents other code from deleting properties of ...
Promise.any() - JavaScript
hen any of the promises in the given iterable resolve, or if all the promises have rejected. description this method is useful for returning the first promise that fulfils. it short-circuits after a promise fulfils, so it does not wait for the other promises to complete once it finds one. unlike promise.all(), which returns an array of fulfillment values, we only get one fulfillment value (assuming at least one promise fulfills). this can be beneficial if we need only one promise to fulfil but we do not care which one does. also, unlike promise.race(), which returns the first settled value (either fulfillment or rejection), this method returns the first fulfilled value. this method will ignore all rejected promises up until the first promise that fulfils. fulfilment if any of the passed-...
Promise.prototype.finally() - JavaScript
the promise is settled, regardless of its outcome. the finally() method is very similar to calling .then(onfinally, onfinally) however there are a couple of differences: when creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it a finally callback will not receive any argument, since there's no reliable means of determining if the promise was fulfilled or rejected. this use case is for precisely when you do not care about the rejection reason, or the fulfillment value, and so there's no need to provide it. so for example: unlike promise.resolve(2).then(() => {}, () => {}) (which will be resolved with undefined), promise.resolve(2).finally(() => {}) will be resolved with 2. similarly, unlike promise.rejec...
RegExp.prototype.dotAll - JavaScript
e. property attributes of regexp.prototype.dotall writable no enumerable no configurable yes description the value of dotall is a boolean and true if the "s" flag was used; otherwise, false. the "s" flag indicates that the dot special character (".") should additionally match the following line terminator ("newline") characters in a string, which it would not match otherwise: u+000a line feed (lf) ("\n") u+000d carriage return (cr) ("\r") u+2028 line separator u+2029 paragraph separator this effectively means the dot will match any character on the unicode basic multilingual plane (bmp). to allow it to match astral characters, the "u" (unicode) flag should be used. using both flags in ...
RegExp.prototype.source - JavaScript
able no configurable yes examples using source var regex = /foobar/ig; console.log(regex.source); // "foobar", doesn't contain /.../ and "ig". empty regular expressions and escaping starting with ecmascript 5, the source property no longer returns an empty string for empty regular expressions. instead, the string "(?:)" is returned. in addition, line terminators (such as "\n") are escaped now. new regexp().source; // "(?:)" new regexp('\n').source === '\n'; // true, prior to es5 new regexp('\n').source === '\\n'; // true, starting with es5 specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.source' in that specification. ...
RegExp.prototype.toString() - JavaScript
...
RegExp - JavaScript
onstructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary. for example, the following are equivalent: let re = /\w+/ let re = new regexp('\\w+') perl-like regexp properties note that several of the regexp properties have both long and short (perl-like) names. both names always refer to the same value. (perl is the programming language from which javascript modeled its regular expressions.). see also deprecated regexp properties. constructor regexp() creates a new regexp object. static properties get regexp[@@species] the constructor function that is used to create derived objects. regexp.lastindex the index at which to start the next match. instance properties regexp.prototype.flags a string that c...
Set.prototype.forEach() - JavaScript
er, so the first two arguments are both values contained in the set. this is to make it consistent with other foreach() methods for map and array. if a thisarg parameter is provided to foreach(), it will be passed to callback when invoked, for use as its this value. otherwise, the value undefined will be passed for use as its this value. the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. each value is visited once, except in the case when it was deleted and re-added before foreach() has finished. callback is not invoked for values deleted before being visited. new values added before foreach() has finished will be visited. foreach() executes the callback function once for each element in the set object;...
Set.prototype.has() - JavaScript
teractive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax myset.has(value); parameters value the value to test for presence in the set object. return value returns true if an element with the specified value exists in the set object; otherwise false. note: technically speaking, has() uses the samevaluezero algorithm to determine whether the given element is found. 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}); // n...
String.prototype.charCodeAt() - JavaScript
t 128 unicode code points are a direct match of the ascii character encoding. (for information on unicode, see the javascript guide.) note: charcodeat() will always return a value that is less than 65536. this is because the higher code points are represented by a pair of (lower valued) "surrogate" pseudo-characters which are used to comprise the real character. because of this, in order to examine (or reproduce) the full character for individual character values of 65536 or greater, for such characters, it is necessary to retrieve not only charcodeat(i), but also charcodeat(i+1) (as if manipulating a string with two letters), or to use codepointat(i) instead. see examples 2 and 3 (below). charcodeat() returns nan if the given index is less than 0, or if it is equal to or greater than th...
String.prototype.endsWith() - JavaScript
the endswith() method determines whether a string ends with the characters of a specified string, returning true or false as appropriate. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.endswith(searchstring[, length]) parameters searchstring the characters to be searched for at the end of str. length optional if provided, it is used as the length of str. defaults to str.length. return value true if the given characters are found at the end of the string; otherwise, false. description this method lets you determine whether or not a string ends with another string. this method is case-sensiti...
String.prototype.includes() - JavaScript
the includes() method determines whether one string may be found within another string, returning true or false as appropriate. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.includes(searchstring[, position]) parameters searchstring a string to be searched for within str. position optional the position within the string at which to begin searching for searchstring. (defaults to 0.) return value true if the search string is found anywhere within the given string; otherwise, false if not. description this method lets you determine whether or not a string includes another string. case-sensit...
String.prototype.replace() - JavaScript
ds to $& above.) p1, p2, ... the nth string found by a parenthesized capture group (including named capturing groups), provided the first argument to replace() was a regexp object. (corresponds to $1, $2, etc. above.) for example, if /(\a+)(\b+)/, was given, p1 is the match for \a+, and p2 for \b+. offset the offset of the matched substring within the whole string being examined. (for example, if the whole string was 'abcd', and the matched substring was 'bc', then this argument will be 1.) string the whole string being examined. groups in browser versions supporting named capturing groups, will be an object whose keys are the used group names, and whose values are the matched portions (undefined if not matched). (the exact number of argu...
String.prototype.replaceAll() - JavaScript
the matched substring. (corresponds to $& above.) p1, p2, ... the nth string found by a parenthesized capture group, provided the first argument to replace() was a regexp object. (corresponds to $1, $2, etc. above.) for example, if /(\a+)(\b+)/, was given, p1 is the match for \a+, and p2 for \b+. offset the offset of the matched substring within the whole string being examined. (for example, if the whole string was 'abcd', and the matched substring was 'bc', then this argument will be 1.) string the whole string being examined. (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' ...
String.prototype.trim() - JavaScript
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.trim() return value a new string representing the str stripped of whitespace from both ends. ...
Symbol.hasInstance - JavaScript
the instanceof operator's behavior can be customized by this symbol. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
TypedArray.prototype.every() - JavaScript
will return true. callback is invoked with three arguments: the value of the element, the index of the element, and the array object being traversed. if a thisarg parameter is provided to every, it will be passed to callback when invoked, for use as its this value. otherwise, the value undefined will be passed for use as its this value. the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. every does not mutate the typed array on which it is called. examples testing size of all typed array elements the following example tests whether all elements in the typed array are bigger than 10. function isbigenough(element, index, array) { return element >= 10; } new uint8array([12, 5, 8, 130, 44]).every(isbig...
TypedArray.prototype.filter() - JavaScript
typed array. callback is invoked with three arguments: the value of the element the index of the element the typed array object being traversed if a thisarg parameter is provided to filter, it will be passed to callback when invoked, for use as its this value. otherwise, the value undefined will be passed for use as its this value. the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. filter() does not mutate the typed array on which it is called. the range of elements processed by filter() is set before the first invocation of callback. elements which are appended to the typed array after the call to filter() begins will not be visited by callback. if existing elements of the typed array are changed...
TypedArray.prototype.forEach() - JavaScript
and have the value undefined. callback is invoked with three arguments: the element value the element index the typed array being traversed if a thisarg parameter is provided to foreach(), it will be passed to callback when invoked, for use as its this value. otherwise, the value undefined will be passed for use as its this value. the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. the range of elements processed by foreach() is set before the first invocation of callback. elements that are appended to the typed array after the call to foreach() begins will not be visited by callback. if the values of existing elements of the typed array are changed, the value passed to callback will be the value a...
TypedArray.prototype.indexOf() - JavaScript
ot present. this method has the same algorithm as array.prototype.indexof(). typedarray is one of the typed array types here. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax typedarray.indexof(searchelement[, fromindex = 0]) parameters searchelement element to locate in the typed array. fromindex the index to start the search at. if the index is greater than or equal to the typed array's length, -1 is returned, which means the typed array will not be searched. if the provided index value is a negative number, it is taken as the offset from the end of the typed array. note: if the provided index is neg...
TypedArray.prototype.lastIndexOf() - JavaScript
the lastindexof() method returns the last index at which a given element can be found in the typed array, or -1 if it is not present. the typed array is searched backwards, starting at fromindex. this method has the same algorithm as array.prototype.lastindexof(). typedarray is one of the typed array types here. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax typedarray.lastindexof(searchelement[, fromindex = typedarray.length]) parameters searchelement element to locate in the typed array. fromindex optional. the index at which to start searching backwards. defaults to the typed array's length, i.e.
TypedArray.prototype.map() - JavaScript
been assigned values. mapfn is invoked with three arguments: the value of the element, the index of the element, and the typed array object being traversed. if a thisarg parameter is provided to map(), it will be passed to mapfn when invoked, for use as its this value. otherwise, the value undefined will be passed for use as its this value. the this value ultimately observable by mapfn is determined according to the usual rules for determining the this seen by a function. map() does not mutate the typed array on which it is called (although mapfn, if invoked, may do so). the range of elements processed by map() is set before the first invocation of mapfn. elements which are appended to the array after the call to map() begins will not be visited by mapfn. if existing elements of the type...
TypedArray.prototype.some() - JavaScript
some returns false. callback is invoked with three arguments: the value of the element, the index of the element, and the array object being traversed. if a thisarg parameter is provided to some, it will be passed to callback when invoked, for use as its this value. otherwise, the value undefined will be passed for use as its this value. the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. some does not mutate the typed array on which it is called. polyfill since there is no global object with the name typedarray, polyfilling must be done on an "as needed" basis. // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.some if (!uint8array.prototype.some) { object.defineproperty(uint8array.protot...
TypedArray - JavaScript
f not found. see also array.prototype.find(). typedarray.prototype.findindex() returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. see also array.prototype.findindex(). typedarray.prototype.foreach() calls a function for each element in the array. see also array.prototype.foreach(). typedarray.prototype.includes() determines whether a typed array includes a certain element, returning true or false as appropriate. see also array.prototype.includes(). typedarray.prototype.indexof() returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. see also array.prototype.indexof(). typedarray.prototype.join() joins all elements of an array into a string. see also...
Uint16Array - JavaScript
ot found. see also array.prototype.find(). uint16array.prototype.findindex() returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. see also array.prototype.findindex(). uint16array.prototype.foreach() calls a function for each element in the array. see also array.prototype.foreach(). uint16array.prototype.includes() determines whether a typed array includes a certain element, returning true or false as appropriate. see also array.prototype.includes(). uint16array.prototype.indexof() returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. see also array.prototype.indexof(). uint16array.prototype.join() joins all elements of an array into a string. see al...
Uint32Array - JavaScript
ot found. see also array.prototype.find(). uint32array.prototype.findindex() returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. see also array.prototype.findindex(). uint32array.prototype.foreach() calls a function for each element in the array. see also array.prototype.foreach(). uint32array.prototype.includes() determines whether a typed array includes a certain element, returning true or false as appropriate. see also array.prototype.includes(). uint32array.prototype.indexof() returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. see also array.prototype.indexof(). uint32array.prototype.join() joins all elements of an array into a string. see al...
Uint8Array - JavaScript
f not found. see also array.prototype.find(). uint8array.prototype.findindex() returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. see also array.prototype.findindex(). uint8array.prototype.foreach() calls a function for each element in the array. see also array.prototype.foreach(). uint8array.prototype.includes() determines whether a typed array includes a certain element, returning true or false as appropriate. see also array.prototype.includes(). uint8array.prototype.indexof() returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. see also array.prototype.indexof(). uint8array.prototype.join() joins all elements of an array into a string. see also...
Uint8ClampedArray - JavaScript
array.prototype.find(). uint8clampedarray.prototype.findindex() returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. see also array.prototype.findindex(). uint8clampedarray.prototype.foreach() calls a function for each element in the array. see also array.prototype.foreach(). uint8clampedarray.prototype.includes() determines whether a typed array includes a certain element, returning true or false as appropriate. see also array.prototype.includes(). uint8clampedarray.prototype.indexof() returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. see also array.prototype.indexof(). uint8clampedarray.prototype.join() joins all elements of an array into a st...
WeakMap - JavaScript
on of values in the map. native weakmaps can be particularly useful constructs when mapping keys to information about the key that is valuable only if the key has not been garbage collected. because the references are weak, weakmap keys are not enumerable. there is no method to obtain a list of the keys. if they were, the list would depend on the state of garbage collection, introducing non-determinism. if you want to have a list of keys, you should use a map. constructor weakmap() creates a new weakmap object. instance methods weakmap.prototype.delete(key) removes any value associated to the key. weakmap.prototype.has(key) will return false afterwards. weakmap.prototype.get(key) returns the value associated to the key, or undefined if there is none. weakmap.prototype.has(key) ...
WebAssembly.Global - JavaScript
{ output.innerhtml += `testing ${msg}: `; if (got !== expected) output.innerhtml += `fail!<br>got: ${got}<br>expected: ${expected}<br>`; else output.innerhtml += `success! ...
WebAssembly.Module() constructor - JavaScript
alled to synchronously compile given webassembly binary code. however, the primary way to get a module is through an asynchronous compilation function like webassembly.compile(). syntax important: since compilation for large modules can be expensive, developers should only use the module() constructor when synchronous compilation is absolutely required; the asynchronous webassembly.compilestreaming() method should be used at all other times. new webassembly.module(buffersource); parameters buffersource a typed array or arraybuffer containing the binary code of the .wasm module you want to compile. examples synchronously compiling a webassembly module var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; function createwasmmodu...
WebAssembly.Module.customSections() - JavaScript
(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. since there is a "name" section in the example, an arraybuffer object is returned. ...
WebAssembly.Module.exports() - JavaScript
y.module object. return value an array containing objects representing the exported functions of the given module. exceptions if module is not a webassembly.module object instance, a typeerror is thrown. 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(). var worker = new worker("wasm_worker.js"); webassembly.compilestreaming(fetch('simple.wasm')) .then(mod => worker.postmessage(mod) ); in the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread. when the module is received, we create an...
WebAssembly.Module.imports() - JavaScript
return value an array containing objects representing the imported functions of the given module. exceptions if module is not a webassembly.module object instance, a typeerror is thrown. examples using imports the following example (see imports.html source code; see it live also) compiles the loaded simple.wasm module. this module is then queried for its imports. webassembly.compilestreaming(fetch('simple.wasm')) .then(function(mod) { var imports = webassembly.module.imports(mod); console.log(imports[0]); }); the output looks like this: { module: "imports", name: "imported_func", kind: "function" } specifications specification webassembly javascript interfacethe definition of 'imports()' in that specification. browser compatibility the compati...
WebAssembly.Module - JavaScript
urns an array containing descriptions of all the declared exports. webassembly.module.imports() given a module, returns an array containing descriptions of all the declared imports. 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(). var worker = new worker("wasm_worker.js"); webassembly.compilestreaming(fetch('simple.wasm')) .then(mod => worker.postmessage(mod) ); in the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread. when the modul...
WebAssembly.compile() - JavaScript
the following example compiles the loaded simple.wasm byte code using the compile() function and then sends it to a worker using postmessage(). var worker = new worker("wasm_worker.js"); fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => webassembly.compile(bytes) ).then(mod => worker.postmessage(mod) ); note: you'll probably want to use webassembly.compilestreaming() in most cases, as it is more efficient than compile(). specifications specification webassembly javascript interfacethe definition of 'compile()' in that specification. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-dat...
encodeURI() - JavaScript
...
globalThis - JavaScript
n global scope the this value is globalthis. html and the windowproxy in many engines globalthis will be a reference to the actual global object, but in web browsers, due to iframe and cross-window security considerations, it references a proxy around the actual global object (which you can't directly access). this distinction is rarely relevant in common usage, but important to be aware of. naming several other popular name choices such as self and global were removed from consideration because of their potential to break compatibility with existing code. see the language proposal's "naming" document for more details. examples search for the global across environments prior to globalthis, the only reliable cross-platform way to get the global object for an environment was function('re...
isFinite() - JavaScript
the global isfinite() function determines whether the passed value is a finite number. if needed, the parameter is first converted to a number. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax isfinite(testvalue) parameters testvalue the value to be tested for finiteness. return value false if the argument is positive or negative infinity or nan or undefined; otherwise, true. description isfinite is a top-level function and is not associated with any object. you can use this function to determine whether a number is a finite number. the isfinite function examines the number in its argument. if th...
parseFloat() - JavaScript
erted to one using the tostring abstract operation. leading whitespace in this argument is ignored. return value a floating point number parsed from the given string. or nan when the first non-whitespace character cannot be converted to a number. description parsefloat is a top-level function and not a method of any object. if parsefloat encounters a character other than a plus sign (+), minus sign (- u+002d hyphen-minus), numeral (0–9), decimal point (.), or exponent (e or e), it returns the value up to that character, ignoring the invalid character and characters following it. a second decimal point also stops parsing (characters up to that point will still be parsed). leading and trailing spaces in the argument are ignored. if the argument’s first character can’t be conve...
parseInt() - JavaScript
hat 10 (decimal) should be used, but not all browsers support this yet. for this reason, always specify a radix when using parseint. if the input string begins with any other value, the radix is 10 (decimal). if the first character cannot be converted to a number, parseint returns nan. for arithmetic purposes, the nan value is not a number in any radix. you can call the isnan function to determine if the result of parseint is nan. if nan is passed on to arithmetic operations, the operation result will also be nan. to convert a number to its string literal in a particular radix, use thatnumber.tostring(radix). bigint warning: parseint converts a bigint to a number and loses precision in the process. this is because trailing non-numeric values, including "n", are discarded. octal inter...
undefined - JavaScript
e your code difficult to maintain and debug. // don't do this // logs "foo string" (function() { var undefined = 'foo'; console.log(undefined, typeof undefined); })(); // logs "foo string" (function(undefined) { console.log(undefined, typeof undefined); })('foo'); examples strict equality and undefined you can use undefined and the strict equality and inequality operators to determine whether a variable has a value. in the following code, the variable x is not initialized, and the if statement evaluates to true. var x; if (x === undefined) { // these statements execute } else { // these statements do not execute } note: the strict equality operator (as opposed to the standard equality operator) must be used here, because x == undefined also checks whether x is null, w...
Iteration protocols - JavaScript
, while other types (such as object) are not. in order to be iterable, an object must implement the @@iterator method, meaning that the object (or one of the objects up its prototype chain) must have a property with a @@iterator key which is available via constant symbol.iterator: property value [symbol.iterator] a zero-argument function that returns an object, conforming to the iterator protocol. whenever an object needs to be iterated (such as at the beginning of a for...of loop), its @@iterator method is called with no arguments, and the returned iterator is used to obtain the values to be iterated. note that when this zero-argument function is called, it is invoked as a method on the iterable object. therefore inside of the function, the this keyword ...
Assignment (=) - JavaScript
ng the assignment operator is possible in order to assign a single value to multiple variables the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax operator: x = y examples simple assignment and chaining // assuming the following variables // x = 5 // y = 10 // z = 25 x = y // x is 10 x = y = z // x, y and z are all 25 specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification. ...
Division assignment (/=) - JavaScript
riable by the value of the right operand and assigns the result to the variable. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax 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 (**) - JavaScript
write an ambiguous exponentiation expression. that is, you cannot put a unary operator (+/-/~/!/delete/void/typeof) immediately before the base number; doing so will cause a syntaxerror. -2 ** 2; // 4 in bash, -4 in other languages. // this is invalid in javascript, as the operation is ambiguous. -(2 ** 2); // -4 in javascript and the author's intention is unambiguous. note that some programming languages use the caret symbol ^ for exponentiation, but javascript uses that symbol for the bitwise logical xor operator. examples basic exponentiation 2 ** 3 // 8 3 ** 2 // 9 3 ** 2.5 // 15.588457268119896 10 ** -1 // 0.1 nan ** 2 // nan associativity 2 ** 3 ** 2 // 512 2 ** (3 ** 2) // 512 (2 ** 3) ** 2 // 64 usage with unary operators to invert the sign of the result of an expo...
Exponentiation assignment (**=) - JavaScript
**=) raises the value of a variable to the power of the right operand. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax 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. ...
Logical AND (&&) - JavaScript
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). this happens because the value of the operator is already determined after the evaluation of the first operand. see example: function a(){ console.log('called a'); return false; } function b(){ console.log('called b'); return true; } console.log( a() && b() ); // logs "called a" due to the function call, // then logs false (which is the resulting value of the operator) operator precedence the following expressions might seem equivalent, but they are not, be...
Logical OR (||) - JavaScript
or possible "short-circuit" evaluation using the following rule: (some truthy expression) || expr is short-circuit evaluated to the truthy 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). this happens because the value of the operator is already determined after the evaluation of the first operand. see example: function a(){ console.log('called a'); return false; } function b(){ console.log('called b'); return true; } console.log( b() || a() ); // logs "called b" due to the function call, // then logs true (which is the resulting value of the operator) operator precedence the following expressions might seem equivalent, but they are not, bec...
Logical OR assignment (||=) - JavaScript
les project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax expr1 ||= expr2 description short-circuit evaluation the logical or operator works like this: x || y; // returns x when x is truthy // returns y when x is not truthy the logical or operator short-circuits: the second operand is only evaluated if the first operand doesn’t already determine the result. logical or assignment short-circuits as well, meaning it only performs an assignment if the logical operation would evaluate the right-hand side. in other words, x ||= y is equivalent to: x || (x = y); and not equivalent to the following which would always perform an assignment: x = x || y; note that this behavior is different to mathematical and bitwise assignment operators. ...
Multiplication assignment (*=) - JavaScript
y the value of the right operand and assigns the result to the variable. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax operator: x *= y meaning: x = x * y examples using multiplication assignment // assuming the following variable // bar = 5 bar *= 2 // 10 bar *= 'foo' // nan specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification. ...
Object initializer - JavaScript
5 has no generators): let o = { generator: function* () { ........... } }; for more information and examples about methods, see method definitions. computed property names starting with ecmascript 2015, the object initializer syntax also supports computed property names. that allows you to put an expression in brackets [], that will be computed and used as the property name. this is reminiscent of the bracket notation of the property accessor syntax, which you may have used to read and set properties already. now you can use a similar syntax in object literals, too: // computed property names (es2015) let i = 0 let a = { ['foo' + ++i]: i, ['foo' + ++i]: i, ['foo' + ++i]: i } console.log(a.foo1) // 1 console.log(a.foo2) // 2 console.log(a.foo3) // 3 let param = 'size' let...
Operator precedence - JavaScript
operators with higher precedence become the operands of operators with lower precedence. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. precedence and associativity consider an expression describable by the representation below. note that both op1 and op2 are fill-in-the-blanks for operators. a op1 b op2 c if op1 and op2 have different precedence levels (see the table below), the operator with the highest precedence goes first and associativity does not matter. ...
Remainder assignment (%=) - JavaScript
by the value of the right operand and assigns the remainder to the variable. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax 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. ...
Subtraction assignment (-=) - JavaScript
f the right operand from a variable and assigns the result to the variable. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax operator: x -= y meaning: x = x - y examples using subtraction assignment // assuming the following variable // bar = 5 bar -= 2 // 3 bar -= 'foo' // nan specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification. ...
await - JavaScript
can split execution flow, allowing the caller of the await's function to resume execution before the deferred continuation of the await's function. after the await defers the continuation of its function, if this is the first await executed by the function, immediate execution also continues by returning to the function's caller a pending promise for the completion of the await's function and resuming execution of that caller. examples awaiting a promise to be fulfilled if a promise is passed to an await expression, it waits for the promise to be fulfilled and returns the fulfilled value. function resolveafter2seconds(x) { return new promise(resolve => { settimeout(() => { resolve(x); }, 2000); }); } async function f1() { var x = await resolveafter2seconds(10); cons...
instanceof - JavaScript
ons, this will be a valid and strong issue. 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. components.interfaces.nsifile) calls obj.queryinterface(xpcominterface) and returns true if queryinterface succeeded. a side effect of such call is that you can use xpcominterface's properties on obj after a successful instanceof test. unlike standard javascript globals, the test obj instanceof xpcominterface works as expected, even if obj is from a different scope. examples demo...
new.target - JavaScript
ion the new.target syntax consists of the keyword new, a dot, and the identifier target. normally, the left-hand side of the dot is the object on which property access is performed, but here, new is not an object. the new.target pseudo-property is available in all functions. in class constructors, it refers to the constructed class. in ordinary functions, it refers to the function itself, assuming it was invoked via the new operator; otherwise new.target is undefined. in arrow functions, new.target is inherited from the surrounding scope. examples new.target in function calls in normal function calls (as opposed to constructor function calls), new.target is undefined. this lets you detect whether a function was called with new as a constructor. function foo() { if (!new.target) { t...
typeof - JavaScript
let idata = 99; typeof idata + ' wisen'; // 'number wisen' typeof (idata + ' wisen'); // 'string' regular expressions callable regular expressions were a non-standard addition in some browsers. typeof /s/ === 'function'; // chrome 1-12 non-conform to ecmascript 5.1 typeof /s/ === 'object'; // firefox 5+ conform to ecmascript 5.1 errors before ecmascript ...
debugger - JavaScript
, such as setting a breakpoint. if no debugging functionality is available, this statement has no effect. 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. function potentiallybuggycode() { debugger; // do potentially buggy stuff to examine, step through, etc. } when the debugger is invoked, execution is paused at the debugger statement. it is like a breakpoint in the script source. specifications specification ecmascript (ecma-262)the definition of 'debugger statement' in that specification. ...
for await...of - JavaScript
); yield 4; } (async function() { for await (let num of generator()) { console.log(num); } })(); // 0 // 1 // 2 // 3 // 4 // compare with for-of loop: for (let numorpromise of generator()) { console.log(numorpromise); } // 0 // 1 // promise { 2 } // promise { 3 } // 4 note: be aware of yielding rejected promises from sync generator. in such case for await...of throws when consuming rejected promise and doesn't call finally blocks within that generator. this can be undesireable if you need to free some allocated resources with try/finally. function* generatorwithrejectedpromises() { try { yield 0; yield 1; yield promise.resolve(2); yield promise.reject(3); yield 4; throw 5; } finally { console.log('called finally') } } (async function() ...
for...in - JavaScript
rties of the object itself and those the object inherits from its prototype chain (properties of nearer prototypes take precedence over those of prototypes further away from the object in its prototype chain). deleted, added, or modified properties a for...in loop iterates over the properties of an object in an arbitrary order (see the delete operator for more on why one cannot depend on the seeming orderliness of iteration, at least in a cross-browser setting). if a property is modified in one iteration and then visited at a later time, its value in the loop is its value at that later time. a property that is deleted before it has been visited will not be visited later. properties added to the object over which iteration is occurring may either be visited or omitted from iteration. in ge...
function* - JavaScript
param optional the name of a formal parameter for the function. statements the statements comprising the body of the function. description generators are functions that can be exited and later re-entered. their context (variable bindings) will be saved across re-entrances. generators in javascript -- especially when combined with promises -- are a very powerful tool for asynchronous programming as they mitigate -- if not entirely eliminate -- the problems with callbacks, such as callback hell and inversion of control. however, an even simpler solution to these problems can be achieved with async functions. calling a generator function does not execute its body immediately; an iterator object for the function is returned instead. when the iterator's next() method is called, the generat...
label - JavaScript
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. foo: { console.log('face'); break fo...
return - JavaScript
a number. function square(x) { return x * x; } var demo = square(3); // demo will equal 9 if the value is omitted, undefined is returned instead. the following return statements all break the function execution: return; return true; return false; return x; return x + y / 3; automatic semicolon insertion the return statement is affected by automatic semicolon insertion (asi). no line terminator is allowed between the return keyword and the expression. return a + b; is transformed by asi into: return; a + b; the console will warn "unreachable code after return statement". starting with firefox 40, a warning is shown in the console if unreachable code is found after a return statement. to avoid this problem (to prevent asi), you could use parentheses: return ( a + b ); ex...
var - JavaScript
at the time "x = y" is evaluated, y exists so no referenceerror is thrown and its value is undefined. so, x is assigned the undefined value. then, y is assigned the value 'a'. consequently, after the first line, x === undefined && y ==...
while - JavaScript
as n is less than three. var n = 0; var x = 0; while (n < 3) { n++; x += n; } each iteration, the loop increments n and adds it to x. therefore, x and n take on the following values: after the first pass: n = 1 and x = 1 after the second pass: n = 2 and x = 3 after the third pass: n = 3 and x = 6 after completing the third pass, the condition n < 3 is no longer true, so the loop terminates. specifications specification ecmascript (ecma-262)the definition of 'while statement' in that specification. ...
Statements and declarations - JavaScript
tiple lines. multiple statements may occur on a single line if each statement is separated by a semicolon. this isn't a keyword, but a group of keywords. statements and declarations by category for an alphabetical listing see the sidebar on the left. control flow block a block statement is used to group zero or more statements. the block is delimited by a pair of curly brackets. break terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement. continue terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration. empty an empty statement is used to provide no statement, although the javascript syntax would ex...
Transitioning to strict mode - JavaScript
strict mode rules. thorough testing will need to be performed to make sure nothing breaks. not using eval if you don't really need it may be another pragmatic solution. strictness-neutral code a potential "downside" of moving strict code to strict mode is that the semantics may be different in legacy browsers which do not implement strict mode. in some rare occasions (like bad concatenation or minification), your code also may not run in the mode you wrote and tested it in. here are the rules to make your code strictness-neutral: write your code as strict and make sure no strict-only errors (from the above "new runtime errors" section) are thrown. stay away from semantic differences eval: use it only if you know what you're doing arguments: always access function arguments via...
JavaScript shells - JavaScript
shell including both native and javascript libraries. gluescript - a standalone javascript shell for writing cross-platform javascript applications. it can use wxwidgets for gui apps and was formerly called wxjavascript. jspl - a standalone javascript shell enhanced by perl. can use perl modules directly from javascript: dbi for database integration, gtk2 for gui apps, posix for system programming, etc. the best of cpan now for javascript programmers. shelljs - portable unix shell commands for node.js list of javascript shells the following javascript shells work with mozilla. firefox has a built-in javascript console, which support multi-line editing. javascript shell (js) - a command line interpreter for javascript xpcshell is an xpconnect - enabled shell, sometimes useful for ...
dir - Web app manifests
Web › Manifest › dir
type string mandatory no the base direction in which to display direction-capable members of the manifest. together with the lang member, it helps to correctly display right-to-left languages. the dir member can be set to one of the following values: auto — text direction is determined by the user agent ltr — left to right rtl — right to left the directionality-capable members are: name short_name description note: if the value is omitted or set to auto, the browser will use the unicode bidirectional algorithm to make a best guess about the text's direction. example "dir": "rtl", "lang": "ar", "short_name": "!أنا من التطبيق" specification specification status comment feedback web app man...
iarc_rating_id - Web app manifests
note: the same code can be shared across multiple participating storefronts, as long as the distributed product remains the same (i.e., doesn’t serve totally different code paths on different storefronts). ...
icons - Web app manifests
ave one or more of the following values, separated by spaces: monochrome: a user agent can present this icon where a monochrome icon with a solid fill is needed. the color information in the icon is discarded and only the alpha data is used. the icon can then be used by the user agent like a mask over any solid fill. maskable: the image is designed with icon masks and safe zone in mind, such that any part of the image outside the safe zone can safely be ignored and masked away by the user agent. any: the user agent is free to display the icon in any context (this is the default value). specification specification status comment feedback web app manifestthe definition of 'icons' in that specification. working...
lang - Web app manifests
Web › Manifest › lang
type string mandatory no the lang member is a string containing a single language tag. it specifies the primary language for the values of the manifest's directionality-capable members, and together with dir determines their directionality. examples "lang": "en-us" specification specification status comment feedback web app manifestthe definition of 'lang' in that specification. working draft initial definition. web app manifest working group drafts ...
shortcuts - Web app manifests
on. when user invokes a shortcut, the user agent will navigate to the address given by shortcut's url member. examples the following is a list of shortcuts a calendar app might have: "shortcuts" : [ { "name": "today's agenda", "url": "/today", "description": "list of events planned for today" }, { "name": "new event", "url": "/create/event" }, { "name": "new reminder", "url": "/create/reminder" } ] specification specification status comment feedback web app manifestthe definition of 'shortcuts' in that specification. working draft initial definition. web app manifest working group drafts ...
<mlabeledtr> - MathML
child elements of <mlabeledtr> must be <mtd> elements. the first child is the label whereas all other children are representing row contents and are treated identically to children of <mtr> elements. attributes class, id, style provided for use with stylesheets. columnalign overrides the horizontal alignment of cells specified by <mtable> for this row. possible values are: left, center and right. groupalign href used to set a hyperlink to a specified uri. mathbackground the background color. ...
<mmultiscripts> - MathML
laceholder for empty scripts (not for the base). see the examples section for a correct usage. attributes class, id, style provided for use with stylesheets. href used to set a hyperlink to a specified uri. mathbackground the background color. you can use #rgb, #rrggbb and html color names. mathcolor the text color. you can use #rgb, #rrggbb and html color names. subscriptshift the minimum space by which to shift the subscript below the baseline of the expression, as a css length. this property is deprecated and will be removed in the future. superscriptshift the minimum space by which to shift the superscript above the baseline of the expression, as a css length. this property is deprecated and will be removed in the future. examples using <mprescripts/> sample rende...
<mo> - MathML
Web › MathML › Element › mo
tur ; example sans-serif ; example bold-sans-serif ; example sans-serif-italic ; example sans-serif-bold-italic ; example monospace ; example initial ; مثال tailed ; مثال looped ; مثال stretched ; مثال maxsize if stretchy is true, this attribute specifies the maximum size of the operator. allowed values are: infinity an arbitrary length minsize if stretchy is true, this attribute specifies the minimum size of the operator. allowed values are: infinity an arbitrary length movablelimits specifies whether attached under- and overscripts move to sub- and superscript positions when displaystyle is false. allowed values are either true or false. rspace the amount of space after the operator (see length for values and units...
<ms> - MathML
Web › MathML › Element › ms
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. note that quotation marks should not be specified unless they are part of the string literal. the content of an <ms> element is not an ascii string per se, but rather a sequence of characters and <mglyph> and <malignmark> elements. attributes class, id, style provided for use with stylesheets. dir the text direction. possible values are either ltr (left to right) or rtl (right to left). ...
<mstyle> - MathML
Web › MathML › Element › mstyle
eakstyle to use for infix operators. the values before, after and duplicate are allowed. scriptlevel controls mostly the font-size. the higher the scriptlevel, the smaller the font size. this attribute accepts a non-negative integer, as well as a "+" or a "-" sign, which increments or decrements the current value. in addition, the scriptlevel attribute can never reduce the font size below scriptminsize in order to avoid unreadable small font sizes and depends on the multiplier specified in scriptsizemultiplier. scriptminsize specifies a minimum font size allowed due to changes in scriptlevel. the default value is 8pt. scriptsizemultiplier specifies the multiplier to be used to adjust font size due to changes in scriptlevel. the default value is 0.71. the <mstyle> element accepts all a...
<msub> - MathML
Web › MathML › Element › msub
ch a subscript to an expression. it uses the following syntax: <msub> base subscript </msub>. attributes class, id, style provided for use with stylesheets. href used to set a hyperlink to a specified uri. mathbackground the background color. you can use #rgb, #rrggbb and html color names. mathcolor the text color. you can use #rgb, #rrggbb and html color names. subscriptshift the minimum space by which to shift the subscript below the baseline of the expression, as a length value. this attribute is deprecated and will be removed in the future. examples sample rendering: rendering in your browser: x 1 <math> <msub> <mi>x</mi> <mn>1</mn> </msub> </math> specifications specification status comment mathml 3.0the definition o...
<msubsup> - MathML
an expression. it uses the following syntax: <msubsup> base subscript superscript </msubsup>. attributes class, id, style provided for use with stylesheets. href used to set a hyperlink to a specified uri. mathbackground the background color. you can use #rgb, #rrggbb and html color names. mathcolor the text color. you can use #rgb, #rrggbb and html color names. subscriptshift the minimum space by which to shift the subscript below the baseline of the expression, as a length value. this attribute is deprecated and will be removed in the future. superscriptshift the minimum space by which to shift the superscript above the baseline of the expression, as a length value. this attribute is deprecated and will be removed in the future. examples sample rendering: renderin...
<msup> - MathML
Web › MathML › Element › msup
uperscript to an expression. it uses the following syntax: <msup> base superscript </msup>. attributes class, id, style provided for use with stylesheets. href used to set a hyperlink to a specified uri. mathbackground the background color. you can use #rgb, #rrggbb and html color names. mathcolor the text color. you can use #rgb, #rrggbb and html color names. superscriptshift the minimum space by which to shift the superscript up from the baseline of the expression, as a length value. this attribute is deprecated and will be removed in the future. examples sample rendering: rendering in your browser: x 2 <math> <msup> <mi>x</mi> <mn>2</mn> </msup> </math> specifications specification status comment mathml 3.0the definiti...
<semantics> - MathML
al expressions. the <semantics> element acts as a container element associating annotations and must have child elements (it will raise an invalid markup error otherwise). the <annotation> element is the container element containing semantic information in a non-xml format, whereas the <annotation-xml> element contains content in an xml format, e.g. content mathml or openmath. the rules of determining the visible child in a <semantics> element are the following: if no rule other rule applies: by default only the first child is rendered, which is supposed to be presentation markup. if the first child is a presentation mathml element other than <annotation> or <annotation-xml>, render the first child. if no presentation mathml is found, render the first <annotation> or <annotation-xml> c...
MathML: Deriving the Quadratic Formula - MathML
eral form, and solve for x: a ⁢ x 2 + b ⁢ x + c = 0 a ⁢ x 2 + b ⁢ x = - c x 2 + b a ⁤ x = -c a divide out leading coefficient. x 2 + b a ⁤ x + b 2 a 2 = - c ( 4 a ) a ( 4 a ) + b 2 4 a 2 complete the square. ( x + b 2 a ) ( x + b 2 a ) = b 2 - 4 a c 4 a 2 discriminant revealed. ( x + b 2 a ) 2 = b 2 - 4 a c 4 a 2 x + b 2 a = b 2 - 4 a c 4 a 2 x = -b 2 a ±{c} b 2 - 4 a c 4 a 2 there's the vertex formula. x = - b ±{c} b 2 - 4 a c 2 a ...
Image file type and format guide - Web media technologies
ely easier than video formats, as there are fewer options with broad support, and each tends to have a specific set of use-cases. photographs photographs typically fare well with lossy compression (depending on the encoder's configuration). this makes jpeg and webp good choices for photographs, with jpeg being more compatible but webp perhaps offering better compression. to maximize quality and minimize download time, consider providing both using a fallback with webp as the first choice and jpeg as the second. otherwise, jpeg is the safe choice for compatibility. best choice fallback webp or jpeg jpeg icons for smaller images such as icons, use a lossless format to avoid loss of detail in a size-constrained image. while lossless webp is ideal for this p...
Mapping the width and height attributes of media container elements to their aspect-ratio - Web media technologies
age’s intrinsic aspect ratio. once such an image loads, if the internal aspect ratio is still applied it will result in the <img> not displaying the image correctly. therefore, once the image is loaded, we start using the intrinsic aspect ratio of the loaded image rather than the aspect ratio from the attributes, so it displays at the correct aspect ratio. summary so there you have it — eliminating another piece of jank from web layout! there is no need for a web developer to do anything special to their code to take advantage of this, besides returning to the habit of using width and height attributes in their html. they'll just get it for free. note: this new mechanism is enabled in firefox 69 in beta and nightly as the spec is worked out (controlled by the layout.css.width-and-hei...
Add to Home screen - Progressive web apps (PWAs)
you'd follow for any android icon (see the android icon design guidelines). link the html to the manifest to finish setting up your manifest, you need to reference it from the html of your application's home page: <link rel="manifest" href="manifest.webmanifest"> browsers that support a2hs will know where to look for your manifest once this is in place. what does a2hs not give you? bear in mind that when you add an app to your home screen, it just makes the app easily accessible — it doesn't download the app's assets and data to your device and make the app available offline, or anything like that. to make your app work offline, you have to use the service worker api to handle storing the assets offline, and if required, web storage or indexeddb to store its data. in our example app...
Installing and uninstalling web apps - Progressive web apps (PWAs)
conveniently invoked as they have a presence in a device’s home screen or app list or bar. this makes it simple for a user to use a gesture to access an app by tapping or clicking its icon. the application itself may then manifest as in a chromeless view (without the full browser chrome) but it nevertheless is executing effectively as a tab within the browser. for users, the experience of a seemingly-native pwa is more comfortable and convenient than a typical web site. by reducing the user experience differential between the web app and native apps on the user's device, you reduce both the loss of any muscle memory they have revolving around the native interface of the device and the sensation of "something isn't quite right" that users can experience when switching between native and web...
PWA developer guide - Progressive web apps (PWAs)
talled on the user's device... ...
How to make PWAs installable - Progressive web apps (PWAs)
me to be shown on the home screen. description: a sentence or two explaining what your app does. icons: a bunch of icon information — source urls, sizes, and types. be sure to include at least a few, so that one that fits best will be chosen for the user's device. start_url: the index document to launch when starting the app. display: how the app is displayed; can be fullscreen, standalone, minimal-ui, or browser. theme_color: a primary color for the ui, used by operating system. background_color: a color used as the app's default background, used during install and on the splash screen. a minimal web manifest must have at least a name and an icons field with at least one icon defined; that icon must have at least the src, sizes, and type sub-fields as well. beyond that, everything ...
Progressive loading - Progressive web apps (PWAs)
...
Progressive web apps (PWAs)
b appsin this structural overview, we'll look at the features that make up a standard web application, as well as some design patterns you can follow when building your pwa. everything below this point is left over from the old version of this page and will be revamped as other content is overhauled. core pwa guides the following guides show you what need to do to implement a pwa, by examining a simple example and showing you how all the pieces work. introduction to progressive web apps progressive web app structure making pwas work offline with service workers how to make pwas installable how to make pwas re-engageable using notifications and push progressive loading technology guides client-side storage — a lengthy guide showing how and when to use web storage, in...
Web API reference - Web technology reference
Web › Reference › API
each individual interface across all apis is listed in the index. there's also a listing of all available events in the event reference. document object model the dom is an api that allows access to and modification of the current document. it allows manipulation of document node and element. ...
Web technology reference
to interpret the content of the page. introduction to html | learn html | html5 | developer guide | element reference | reference css — styling the web cascading style sheets are used to describe the appearance of web content. introduction to css | getting started with css | learn css | common css questions | reference javascript — dynamic client-side scripting the javascript programming language is used to add interactivity and other dynamic features to web sites. learn javascript | developer guide | reference ...
SVG Core Attributes - SVG: Scalable Vector Graphics
Web › SVG › Attribute › Core
he element for the purposes of sequential focus navigation. value type: <integer>; animatable: no xml:base specifies a base iri other than the base iri of the document. value type: <iri>; animatable: no xml:lang it is a universal attribute allowed in all xml dialects to mark up the natural human language that an element contains. it's almost identical in usage to html's lang, but in conforming xml 1.0 documents, it does not allow the use of a null attribute value (xml:lang="") to indicate an unknown language. instead, use xml:lang="und". svg 2 introduce the new lang attributes. if both lang and xml:lang attribute are used, xml:lang has priority over lang. value: any valid language id; animatable: no xml:space deprecated since svg 2 svg supports the standard xml attribute...
baseProfile - SVG: Scalable Vector Graphics
the attribute does not specify any processing restrictions; it can be considered metadata. for example, the value of the attribute could be used by an authoring tool to warn the user when they are modifying the document beyond the scope of the specified base profile. each svg profile should define the text that is appropriate for this attribute. ...
color-interpolation - SVG: Scalable Vector Graphics
controls which color space is used. the color-interpolation property chooses between color operations occurring in the srgb color space or in a (light energy linear) linearized rgb color space. having chosen the appropriate color space, component-wise linear interpolation is used. when a child element is blended into a background, the value of the color-interpolation property on the child determines the type of blending, not the value of the color-interpolation on the parent. for gradients which make use of the href or the deprecated xlink:href attribute to reference another gradient, the gradient uses the propertyʼs value from the gradient element which is directly referenced by the fill or stroke property. when animating colors, color interpolation is performed according to the value of...
diffuseConstant - SVG: Scalable Vector Graphics
the brighter the lighting-color, the smaller this number should be. ...
dur - SVG: Scalable Vector Graphics
Web › SVG › Attribute › dur
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 specifies the length of the simple duration. the value must be greater than 0 and can be expressed with hours (h), minutes (m), seconds (s) or milliseconds (ms). itʼs possible to combine those time representations to create some complex durations like hh:mm:ss.iii or mm:ss.iii. media this value specifies the simple duration as the intrinsic media duration. this is only valid for elements that define media. (for animation elements the attribute will be ignored if media is specified.) indefinite this value ...
font-size-adjust - SVG: Scalable Vector Graphics
" font-size-adjust="0.58"> this is the 10px times, but now adjusted to the same aspect ratio as the verdana. </text> </svg> usage notes default value none value none | <number> animatable yes none choose the size of the font based only on the font-size property. <number> choose the size of the font so that its lowercase letters (as determined by the x-height of the font) are the specified number times the font-size. the number specified should generally be the aspect ratio (ratio of x-height to font size) of the first choice font-family. this means that the first-choice font, when available, will appear the same size in browsers, whether or not they support font-size-adjust. 0 yields text of zero height (hidden text). specif...
glyph-orientation-vertical - SVG: Scalable Vector Graphics
rst-level non-ideographic text. all further embedding of writing modes or bidirectional processing will be based on the first-level rotation. note: text set in this "rotated" manner may contain ligatures or other glyph combining and reordering common to the language and script. (this presentation form does not disable auto-ligature formation or similar context-driven variations.) the determination of which characters should be auto-rotated may vary across user agents. the determination is based on a complex interaction between country, language, script, character properties, font, and character context. <angle> the value of the angle is restricted to 0, 90, 180, and 270 degrees. if another angle is specified, it is rounded to the closest of the permitted values. a value of 0de...
href - SVG: Scalable Vector Graphics
Web › SVG › Attribute › href
being the target of the given animation element. if the url points to multiple target elements, if the given target element is not capable of being a target of the given animation element, or if the given target element is not part of the current document, then the animation element will not affect any target element. however, the animation element will still operate normally with regard to its timing properties. specifically, timeevents are dispatched and the animation element can be used as syncbase in an identical fashion to when the url refers to a valid target element. if the href attribute or the deprecated xlink:href attribute is not provided, then the target element will be the immediate parent element of the current animation element. if both xlink:href and href are specified, the v...
id - SVG: Scalable Vector Graphics
Web › SVG › Attribute › id
fication (e.g., mydrawing.svg#svgview(viewbox(0,200,1000,1000))) or a basic media fragment when used as a url target fragment. it must be valid in xml documents. a stand-alone svg document uses xml 1.0 syntax, which specifies that valid ids only include designated characters (letters, digits, and a few punctuation marks), and do not start with a digit, a full stop (.) character, or a hyphen-minus (-) character. specifications specification status comment scalable vector graphics (svg) 2the definition of 'id' in that specification. candidate recommendation defines the allowed values in more detail. scalable vector graphics (svg) 1.1 (second edition)the definition of 'id' in that specification. recommendation initial definition ...
lang - SVG: Scalable Vector Graphics
Web › SVG › Attribute › lang
alue <language-tag> default value none animatable no <language-tag> this value specifies the language used for the element. the syntax of this value is defined in the bcp 47 specification. the most common syntax is a value formed by a lowercase two-character part for the language and an uppercase two-character part for the region or country, separated by a minus sign, e.g. en-us for us english or de-at for austrian german. specifications specification status comment scalable vector graphics (svg) 2the definition of 'lang' in that specification. candidate recommendation made the lang attribute (without namespace) available on all elements and defined the interaction between both. scalable vector graphics (...
media - SVG: Scalable Vector Graphics
Web › SVG › Attribute › media
the media attribute specifies a media query that must be matched for a style sheet to apply. 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. if not specified, the style sheet is applied unconditionally. specific...
panose-1 - SVG: Scalable Vector Graphics
the panose-1 attribute indicates the panose-1 number of a font face. panose-1 is an industry standard truetype font classification and matching technology. the panose system consists of a set of ten numbers that categorize the key attributes of a latin typeface, a classification procedure for creating those numbers, and mapper software that determines the closest possible font match given a set of typefaces. 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. the initial value zero for each panose digit means "any", i.e. all fonts will match the p...
pointsAtZ - SVG: Scalable Vector Graphics
the pointsatz attribute represents the y location in the coordinate system established by attribute primitiveunits on the <filter> element of the point at which the light source is pointing, assuming that, in the initial local coordinate system, the positive z-axis comes out towards the person viewing the content and assuming that one unit along the z-axis equals one unit in x and y. 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%"...
rendering-intent - SVG: Scalable Vector Graphics
ptions cause different methods to be used for translating colors to the color gamut of the target rendering device. 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. perceptual this value preserves the relationship between colors. it attempts to maintain relative color values among the pixels as they are mapped to the target device gamut. sometimes pixel values that were originally within the target device gamut are changed in order to avoid hue shifts and discontinuities and to preserve as much as possible the ...
requiredExtensions - SVG: Scalable Vector Graphics
in this specification. each extension is identified by an url reference. usage notes value <list-of-extensions> default value none animatable no <list-of-extensions> the value is a list of references (iri references in svg 1, url references in svg 2) which identify the required extensions, with the individual values separated by white space. determines whether all of the named extensions are supported by the user agent. if all of the given extensions are supported, then the attribute evaluates to true; otherwise, the current element and its children are skipped and thus will not be rendered. note: if a given extension reference contains white space within itself, that white space must be escaped. requiredextensions is often used in conjunc...
side - SVG: Scalable Vector Graphics
Web › SVG › Attribute › side
the side attribute determines the side of a path the text is placed on (relative to the path direction). 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 ...
spacing - SVG: Scalable Vector Graphics
Web › SVG › Attribute › spacing
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. exact this value indicates that the typographic characters should be rendered exactly according to the spacing rules as specified by the layout rules for text-on-a-path. ...
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. reflect this value indicates that the gradient repeats in reverse beyond its edges. repeat this value specifies that the gradient repeats in the original order beyond its edges. defining a gradient's edges by default, a gradient reaches to the edges of the shape being filled. ...
stemh - SVG: Scalable Vector Graphics
Web › SVG › Attribute › stemh
there may be two or more designed widths. for example, the main vertical stems of roman characters will differ from the thin stems on serifed "m" and "n", plus there may be different widths for uppercase and lowercase characters in the same font. also, either by design or by error, all stems may have slightly different widths. if this attribute is used, the units-per-em must also be used. ...
stemv - SVG: Scalable Vector Graphics
Web › SVG › Attribute › stemv
the stemv attribute indicates the vertical stem width of the font. the vertical stem width is the width of vertical (or near-vertical) stems of glyphs. this information is often tied to hinting, and may not be directly accessible in some font formats. the measurement is meant for the dominant vertical stem in the font because there might be different groupings of vertical stems (e.g., one main one, and one lighter weight one as for an uppercase "m" or "n"). if this attribute is used, the units-per-em must also be used. 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. specifications specification ...
targetX - SVG: Scalable Vector Graphics
Web › SVG › Attribute › targetX
the leftmost column of the matrix is column number zero. the value must be such that: 0 <= targetx < orderx. 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. specifications specification status comment filter effects module level 1the definition of 'targetx' in that specification. ...
targetY - SVG: Scalable Vector Graphics
Web › SVG › Attribute › targetY
the topmost row of the matrix is row number zero. the value must be such that: 0 <= targety < ordery. 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. specifications specification status comment filter effects module level 1the definition of 'targety' in that specification. ...
text-decoration - SVG: Scalable Vector Graphics
ion attribute defines whether text is decorated with an underline, overline and/or strike-through. it is a shorthand for the text-decoration-line and text-decoration-style properties. the fill and stroke of the text decoration are given by the fill and stroke of the text at the point where the text decoration is declared. the paint order of the text decoration, i.e. the fill and stroke, is determined by the value of the paint-order attribute at the point where the text decoration is declared. note: as a presentation attribute, text-decoration can be used as a css property. see the css text-decoration property for more information. as a presentation attribute, it can be applied to any element but it has effect only on the following five elements: <altglyph>, <text>, <textpath>, <tref>, and...
textLength - SVG: Scalable Vector Graphics
s-serif" font-size="60" fill="green"> hello world! </text> </svg> first, a <rect> element is used to create and stroke a rectangle to contain the text. then <text> is used to create the text element itself, with an id of "hello". html the html is also simple, with only two displayed elements contained inside a grouping <div>: <div class="controls"> <input type="range" id="widthslider" min="80" max="978"> <span id="widthdisplay"></span> </div> the <input> element, of type "range", is used to create the slider control the user will manipulate to change the width of the text. a <span> element of id "widthdisplay" is provided to display the current width value. javascript finally, let's have a look at the javascript code. it starts by stashing references to the elements it will n...
type - SVG: Scalable Vector Graphics
Web › SVG › Attribute › type
pt> elements, it defines the content type of the element. ...
values - SVG: Scalable Vector Graphics
Web › SVG › Attribute › values
s a list of numbers, which is interpreted differently depending on the value of the type attribute: for type="matrix", values is a list of 20 matrix values (a00 a01 a02 a03 a04 a10 a11 ... a34), separated by whitespace and/or a comma. for type="saturate", values is a single real number value (0 to 1). for type="huerotate", values is a single one real number value (degrees). for type="luminancetoalpha", values is not applicable. specifications specification status comment filter effects module level 1the definition of 'values for <fecolormatrix>' in that specification. working draft no change svg animations level 2the definition of 'values for <animate>, <animatecolor>, <animatemotion>, and <animatetransform>' in that specification. ...
viewBox - SVG: Scalable Vector Graphics
Web › SVG › Attribute › viewBox
the numbers separated by whitespace and/or a comma, which specify a rectangle in user space which is mapped to the bounds of the viewport established for the associated svg element (not the browser viewport). ...
xlink:show - SVG: Scalable Vector Graphics
d in the same window or tab. this is similar to the effect achieved by an html <a> element with target set to _self. embed this value specifies that instead of linking to the resource it will be loaded and shown within the document. this is similar to the effect achieved by an html <img> element. other this value indicates that other markup present in the link, i.e. the target attribute, determines its behavior. none this value specifies that there is no indication for how to refer to the linked resource. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'xlink:show' in that specification. recommendation initial definition ...
xml:lang - SVG: Scalable Vector Graphics
alue <language-tag> default value none animatable no <language-tag> this value specifies the language used for the element. the syntax of this value is defined in the bcp 47 specification. the most common syntax is a value formed by a lowercase two-character part for the language and an uppercase two-character part for the region or country, separated by a minus sign, e.g. en-us for us english or de-at for austrian german. specifications specification status comment scalable vector graphics (svg) 2the definition of 'xml:lang' in that specification. candidate recommendation made the lang attribute (without namespace) available on all elements and defined the interaction between both. scalable vector graphi...
z - SVG: Scalable Vector Graphics
Web › SVG › Attribute › z
the z attribute defines the location along the z-axis for a light source in the coordinate system established by the primitiveunits attribute on the <filter> element, assuming that, in the initial coordinate system, the positive z-axis comes out towards the person viewing the content and assuming that one unit along the z-axis equals one unit in x and y. 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%"> ...
<a> - SVG: Scalable Vector Graphics
Web › SVG › Element › a
aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role usage notes categoriescontainer elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elementsstructural elementsgradient elements<a>, <altglyphdef>, <clippath>, <color-profile>, <cursor>, <filter>, <font>, <font-face>, <foreignobject>, <image>, <marker>, <mask>, <pattern>, <script>, <style>, ...
<altGlyph> - SVG: Scalable Vector Graphics
Web › SVG › Element › altGlyph
ibutes core attributes most notably: id lang styling attributes class, style conditional processing attributes most notably: requiredextensions, systemlanguage event attributes global event attributes, document element event attributes, graphical event attributes presentation attributes most notably: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, dominant-baseline, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, text-anchor, transform, vector-effect, visibility xlink attributes xlink:href, xlink:type, xlink:role, xlink:arcrole, xlink:title, xlink:show, xlink:actuate dom interfa...
<animateColor> - SVG: Scalable Vector Graphics
ement specifies a color transformation over time. usage context categoriesbasic shape element, graphics element, shape elementpermitted contentany number of the following elements, in any order:descriptive elements attributes global attributes conditional processing attributes core attributes animation event attributes xlink attributes animation attribute target attributes animation timing attributes animation value attributes animation addition attributes externalresourcesrequired specific attributes by from to dom interface this element implements the svganimatecolorelement interface. example svg <svg width="120" height="120" xmlns="http://www.w3.org/2000/svg"> <circle cx="60" cy="60" r="50"> <animatecolor attributename="fill" attributetype="xml" fr...
<animateTransform> - SVG: Scalable Vector Graphics
specifications specification status comment svg animations level 2the definition of '<animatetransform>' in that specification. edit...
<circle> - SVG: Scalable Vector Graphics
Web › SVG › Element › circle
candidate recomme...
<cursor> - SVG: Scalable Vector Graphics
Web › SVG › Element › cursor
pointer position (i.e., the hot spot). the png format is recommended because it supports the ability to define a transparency mask via an alpha channel. if a different image format is used, this format should support the definition of a transparency mask (two options: provide an explicit alpha channel or use a particular pixel color to indicate transparency). if the transparency mask can be determined, the mask defines the shape of the cursor; otherwise, the cursor is an opaque rectangle. typically, the other pixel information (e.g., the r, g and b channels) defines the colors for those parts of the cursor which are not masked out. note that cursors usually contain at least two colors so that the cursor can be visible over most backgrounds. usage context categoriesnonepermitted contentany ...
<ellipse> - SVG: Scalable Vector Graphics
Web › SVG › Element › ellipse
candidate recomm...
<feColorMatrix> - SVG: Scalable Vector Graphics
rcles" transform="translate(0 210)" filter="url(#colormesaturate)" /> <text x="70" y="260">saturate</text> <!-- huerotate --> <filter id="colormehuerotate"> <fecolormatrix in="sourcegraphic" type="huerotate" values="180" /> </filter> <use href="#circles" transform="translate(0 280)" filter="url(#colormehuerotate)" /> <text x="70" y="330">huerotate</text> <!-- luminancetoalpha --> <filter id="colormelta"> <fecolormatrix in="sourcegraphic" type="luminancetoalpha" /> </filter> <use href="#circles" transform="translate(0 350)" filter="url(#colormelta)" /> <text x="70" y="400">luminancetoalpha</text> </svg> result screenshotlive sample specifications specification status comment filter effects module level 1the...
<foreignObject> - SVG: Scalable Vector Graphics
candidate recommendation scalable vector graphics (svg) 1.1 (second edition)the definition of '<foreign...
<g> - SVG: Scalable Vector Graphics
Web › SVG › Element › g
aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role usage notes categoriescontainer element, structural elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elementsstructural elementsgradient elements<a>, <altglyphdef>, <clippath>, <color-profile>, <cursor>, <filter>, <font>, <font-face>, <foreignobject>, <image>, <marker>, <mask>, <pattern>,...
<line> - SVG: Scalable Vector Graphics
Web › SVG › Element › line
candidate recommend...
<path> - SVG: Scalable Vector Graphics
Web › SVG › Element › path
working draft scalable vector graphics (svg) 2the...
<polygon> - SVG: Scalable Vector Graphics
Web › SVG › Element › polygon
candidate recomm...
<polyline> - SVG: Scalable Vector Graphics
Web › SVG › Element › polyline
candidate recom...
<rect> - SVG: Scalable Vector Graphics
Web › SVG › Element › rect
candidate recommend...
<textPath> - SVG: Scalable Vector Graphics
Web › SVG › Element › textPath
aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role xlink attributes xlink:title usage notes categoriestext content element, text content child elementpermitted contentcharacter data and any number of the following elements, in any order:descriptive elements<a>, <altglyph>, <animate>, <animatecolor>, <set>, <tref>, <tspan> specifications specification status comment scalable v...
<use> - SVG: Scalable Vector Graphics
Web › SVG › Element › use
aria-hidden, aria-invalid, aria-keyshortcuts, aria-label, aria-labelledby, aria-level, aria-live, aria-modal, aria-multiline, aria-multiselectable, aria-orientation, aria-owns, aria-placeholder, aria-posinset, aria-pressed, aria-readonly, aria-relevant, aria-required, aria-roledescription, aria-rowcount, aria-rowindex, aria-rowspan, aria-selected, aria-setsize, aria-sort, aria-valuemax, aria-valuemin, aria-valuenow, aria-valuetext, role xlink attributes xlink:href, xlink:title usage notes categoriesgraphics element, graphics referencing element, structural elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elements specifications specification status comment scalable vector graphics (svg) 2the definition...
Scripting - SVG: Scalable Vector Graphics
Web › SVG › Scripting
tyle.setproperty("fill-opacity", "0.0") throws a domexception - syntax err in mozilla. this behaviour is specified by the w3c in the dom level 2 style specification. the function setproperty is defined as a function with three parameters. the above can be replaced with 'svgelement.style.setproperty("fill-opacity", "0.0", "")', which is standards compliant. links svg wiki on scripting and programming ...
Basic Transformations - SVG: Scalable Vector Graphics
<svg width="40" height="50" style="background-color:#bff;"> <rect x="0" y="0" width="10" height="10" transform="translate(30,40) rotate(45)" /> </svg> this example shows again the small square shown above that this time is also rotated by 45 degrees. skewing to make a rhombus out of our rectangle, the skewx() and skewy() transformations are available. each one takes an angle that determines how far the element will be skewed. scaling scale() changes the size of an element. it takes two numbers, the first being the x scale factor and the second being the y scale factor. the factors are taken as the ratio of the transformed dimension to the original. for example, 0.5 shrinks by 50%. if the second number is omitted, it is assumed to be equal to the first. complex transformations w...
Getting started - SVG: Scalable Vector Graphics
ater elements are rendered atop previous elements. the further down an element is the more it will be visible. svg files on the web can be displayed directly in the browser or embedded in html files via several methods: if the html is xhtml and is delivered as type application/xhtml+xml, the svg can be directly embedded in the xml source. if the html is html5, and the browser is a conforming html5 browser, the svg can also be directly embedded. however, there may be syntax changes necessary to conform to the html5 specification. the svg file can be referenced with an object element: <object data="image.svg" type="image/svg+xml" /> likewise an iframe element can be used: <iframe src="image.svg"></iframe> an img element can theoretically be use...
Gradients in SVG - SVG: Scalable Vector Graphics
sample the stops used here are the same as before, but now the object will be red in the center, and in all directions gradually change to blue at the edge. like linear gradients, the <radialgradient> node can take several attributes to describe its position and orientation. however, unlike linear gradients, it's a bit more complex. the radial gradient is again defined by two points, which determine where its edges are. the first of these defines a circle around which the gradient ends. it requires a center point, designated by the cx and cy attributes, and a radius, r. setting these three attributes will allow you to move the gradient around and change its size, as shown in the second rect above. the second point is called the focal point and is defined by the fx and fy attributes. while ...
Tools for SVG - SVG: Scalable Vector Graphics
ogram. inkscape offers state-of-the-art vector drawing, and it's open source. moreover, it uses svg as its native file format. to store inkscape specific data, it extends the svg file with elements and attributes in a custom namespace, but you can also choose to export as plain svg. adobe illustrator url: www.adobe.com/products/illustrator/ before adobe acquired macromedia, it was the most prominent promoter of svg. from this time stems the good support of svg in illustrator. however, the resulting svg often shows some quirks, that make it necessary to post-process it for general applicability. apache batik url: xmlgraphics.apache.org/batik/ batik is a set of open source tools under the roof of the apache software foundation. the toolkit is written in java and offers almost complete sv...
SVG: Scalable Vector Graphics
Web › SVG
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. connect 4 jvectormap (interactive maps for data visualization) jointjs (javascript diagramming library) d3 ( javascript library for visualizing data with html, svg, and css ) ...
Mixed content - Web security
ortions of the webpage. for example, an attacker could replace an image served over http with an inappropriate image or message to the user. the attacker could also infer information about the user's activities by watching which images are served to the user; often images are only served on a specific page within a website. if the attacker observes http requests to certain images, they could determine which webpage the user is visiting. passive content list this section lists all types of http requests which are considered passive content: <img> (src attribute) <audio> (src attribute) <video> (src attribute) <object> subresources (when an <object> performs http requests) mixed active content mixed active content is content that has access to all or parts of the document object mode...
Referer header: privacy and security concerns - Web security
or when combined with a unique user token, and transmitting sensitive data in different ways. you should use post rather than get wherever possible, to avoid passing sensitive data to other locations via urls. you should always use https for your sites. this has many security advantages, including the fact that https sites will never transmit referer information to non-https sites. this is becoming less useful in this context now that most of the web is using https, but it is still a worthy consideration. in addition, you should consider removing any third party content (e.g. social networking widgets embedded in <iframe>) from secure areas of your website, like password reset pages, payment forms, login areas, etc. you can also mitigate such risks using: the referrer-policy header on...
Securing your site - Web security
ser information security how to turn off form autocompletion form fields support autocompletion in gecko; that is, their values can be remembered and automatically brought back the next time the user visits your site. for certain types of data, you may wish to disable this feature. privacy and the :visited selector this article discusses changes made to the getcomputedstyle() method that eliminates the ability for malicious sites to figure out the user's browsing history. 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. the same issues can arise if you use an old or insecure algorithm for hashing (such as md5). you should use a passwo...
Transport Layer Security - Web security
s previous versions of tls. for the web, tls 1.3 can be enabled without affecting compatibility with some rare exceptions (see below). the major changes in tls 1.3 are: the tls 1.3 handshake completes in one round trip in most cases, reducing handshake latency. a server can enable a 0-rtt (zero round trip time) handshake. clients that reconnect to the server can send requests immediately, eliminating the latency of the tls handshake entirely. though the performance gains from 0-rtt can be significant, they come with some risk of replay attack, so some care is needed before enabling this feature. tls 1.3 supports forward-secure modes only, unless the connection is resumed or it uses a pre-shared key. tls 1.3 defines a new set of cipher suites that are exclusive to tls 1.3. these cipher ...
Tutorials
before you start to use apis — interfaces for manipulating different aspects of the browser and operating system the site is running on, or even data from other websites or services. in this module, we will explore what apis are, and how to use some of the most common apis you'll come across often in your development work. a re-introduction to javascript a recap of the javascript programming language aimed at intermediate-level developers. eloquent javascript a comprehensive guide to intermediate and advanced javascript methodologies. speaking javascript for programmers who want to learn javascript quickly and properly, and for javascript programmers who want to deepen their skills and/or look up specific topics. essential javascript design patterns an introduction to essent...
Using shadow DOM - Web Components
zilla.org/">mozilla homepage</a></p> </section> </body> </html> this fragment produces the following dom structure: shadow dom allows hidden dom trees to be attached to elements in the regular dom tree — this shadow dom tree starts with a shadow root, underneath which can be attached to any elements you want, in the same way as the normal dom. there are some bits of shadow dom terminology to be aware of: shadow host: the regular dom node that the shadow dom is attached to. shadow tree: the dom tree inside the shadow dom. shadow boundary: the place where the shadow dom ends, and the regular dom begins. shadow root: the root node of the shadow tree. you can affect the nodes in the shadow dom in exactly the same way as non-shadow nodes — for example appending children ...
Axes - XPath
Web › XPath › Axes
erent axes in the xpath specification. an axis represents a relationship to the context node, and is used to locate nodes relative to that node on the tree. the following is an extremely brief description of the thirteen available axes and the degree of support available in gecko. for further information on using xpath expressions, please see the for further reading section at the end of transforming xml with xslt document. also see the 'axes' section in the xpath spec. ancestor indicates all the ancestors of the context node beginning with the parent node and traveling through to the root node. ancestor-or-self indicates the context node and all of its ancestors, including the root node. attribute indicates the attributes of the context node. only elements have attributes. this ax...
choose - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the choose function returns one of the specified objects based on a boolean parameter. note: this method should be used instead of if(), which has been deprecated. syntax choose( boolean , object1, object2 ) arguments boolean the boolean operation to use when determining which object to return. object1 the first object to consider returning. object2 the second object to consider returning. returns if the boolean parameter is true, the first object is returned; otherwise, the second object is returned. note: all parameters are evaluated, even the one that's not returned. defined xforms 1.1 gecko support supported. ...
contains - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the contains function determines whether the first argument string contains the second argument string and returns boolean true or false. syntax contains(haystack, needle) arguments haystack the string to be searched needle the string to look for as a substring of haystack returns true if haystack contains needle. otherwise, false. defined xpath 1.0 4.2 gecko support supported. ...
element-available - XPath
syntax element-available(qname ) arguments qname must evaluate to a valid qname. the qname is expanded into an expanded-name using the namespace declarations in scope for the expression. returns returns true if and only if the expanded-name is the name of an instruction. if the expanded-name has a namespace uri equal to the xslt namespace uri, then it refers to an element defined by xslt. otherwise, it refers to an extension element. ...
function-available - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the function-available function determines if a given function is available and returns boolean true or false. syntax function-available(name ) arguments name the name of the function to test. returns boolean true or false. defined xpath 1.0 15 gecko support supported. ...
id - XPath
Web › XPath › Functions › id
an individual id. the returned node set is the nodes corresponding to those ids. if expression is a string, or anything other than a node-set, then expression is treated as a space-separated list of ids. the returned node set is the nodes corresponding to those ids. returns a node-set containing the node or nodes identified by the given id or ids. notes the dtd of the xml document determines what attribute is an id. see xpath 1.0 5.2.1 defined xpath 1.0 4.1 gecko support partially supported. ...
lang - XPath
Web › XPath › Functions › lang
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the lang function determines whether the context node matches the given language and returns boolean true or false. syntax lang(string ) arguments string the language code or localization (language and country) code to be matched. returns true if the context node matches the given languages. otherwise, false. notes a node's language is determined by its xml:lang attribute. if the current node does not have an xml:lang attribute, then the value of the xml:lang attribute of the nearest ancestor that has an xml:lang attribute will determine the current node's language. if the language cannot be determined (no ancestor has an xml:lang attribute), this function will return false. i...
last - XPath
Web › XPath › Functions › last
defined xpath 1.0 4.1 gecko support supported. ...
position - XPath
exslt functions, xpath functions, xpath axes the position function returns a number equal to the context position from the expression evaluation context. syntax position() returns an integer equal to the context position from the expression evaluation context. notes note that a node's position in a context is not zero-based. the first node has a position of 1. the context is determined by the rest of the path. <xsl:template match="//a[position() = 5]"> <!-- this template matches the fifth a element anywhere in the document. --> </xsl:template> <xsl:template match="//div[@class='foo']/bar[position() = 1]"> <!-- this template matches the first bar element that is a child of a div element with a class attribute equal to "foo" --> </xsl:template> defined x...
<xsl:key> - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element › key
tions, xpath axes the <xsl:key> element declares a named key which can be used elsewhere in the stylesheet with the key( ) function. syntax <xsl:key name=name match=expression use=expression /> required attributes name specifies a name for this key. must be a qname. match defines the nodes for which this key is applicable. use specifies an xpath expression that will be used to determine the value of the key for each of the applicable nodes. optional attributes none. type top-level, must be the child of <xsl:stylesheet> or <xsl:transform>. defined xslt, section 12.2. gecko support supported. ...
<xsl:message> - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element › message
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the <xsl:message> element outputs a message (to the javascript console in ns) and optionally terminates execution of the stylesheet. it can be useful for debugging. syntax <xsl:message terminate="yes" | "no" > template </xsl:message> required attributes none. optional attributes terminate set to "yes", indicates that execution should be terminated. the default value is "no", in which case the message is output and execution continues. type instruction, appears within a template. defined xslt, section 13. gecko support supported. ...
<xsl:otherwise> - XSLT: Extensible Stylesheet Language Transformations
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the <xsl:otherwise> element is used to define the action that should be taken when none of the <xsl:when> conditions apply. it is similar to the else or default case in other programing languages. syntax <xsl:otherwise> template </xsl:otherwise> required attributes none. optional attributes none. type subinstruction, must appear as the last child of an <xsl:choose> element, within a template. defined xslt, section 9.2 gecko support supported. ...
<xsl:sort> - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element › sort
syntax <xsl:sort select=expression order="ascending" | "descending" case-order="upper-first" | "lower-first" lang=xml:lang-code data-type="text" | "number" /> required attributes none. optional attributes select uses an xpath expression to specify the nodes to be sorted. ...
<xsl:template> - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element › template
functions, xpath functions, xpath axes the <xsl:template> element defines an output producing template. this element must have either the match attribute or the name attribute set. syntax <xsl:template match=pattern name=name mode=name priority=number> <xsl:param> [optional] template </xsl:template> required attributes none. optional attributes match specifies a pattern that determines the elements for which this template should be used. it is a required attribute if there is no name attribute. name specifies a name for this template, by which it can be invoked through the <xsl:call-template> element. mode specifies a particular mode for this template, which can be matched by an attribute of the <xsl:apply-templates> element. this is useful for processing the same i...
PI Parameters - XSLT: Extensible Stylesheet Language Transformations
rent node used when executing the stylesheet. the context position is the position of the context node in the initial current node list used when executing the stylesheet. the context size is the size of the initial current node list used when executing the stylesheet. no variables are available. the function library is the standard xpath function library. the namespace declarations are determined by the xslt-param-namespace pis, see below. if the select attribute fails to parse or execute, the pi is ignored (in particular, it does not fall back to the value attribute). xslt-param-namespace the xslt-param-namespace uses two attributes: prefix the prefix that is mapped. namespace the namespace the prefix maps to. an xslt-param-namespace pi affects the expression in the selec...
An Overview - XSLT: Extensible Stylesheet Language Transformations
an xslt stylesheet is an xml document. unlike css, which has its own specialized syntax, an xslt stylesheet is an xml document, which must conform to all xml rules, including well-formedness. so the model for transformation is that one xml document is used to transform another xml document. an xslt stylesheet is marked as such by the inclusion of a standard xslt heading. ...
Web technology for developers
ble vector graphics let you describe images as sets of vectors and shapes in order to allow them to scale smoothly regardless of the size at which they're drawn. mathml the mathematical markup language makes it possible to display complex mathematical equations and syntax. temporary the stuff below here is temporary to help keep track of things while organization work is ongoing. pay it no mind. accessibilitycss houdinicss: cascading style sheetsdemos of open web technologiesdeveloper guidesexsltevent referencehtml: hypertext markup languagehttpjavascriptmathmlopensearch description formatprivacy, permissions, and information securityprogressive web apps (pwas)svg: scalable vector graphicstutorialsweb apisweb componentsweb performanceweb app manifestsweb media technologiesweb security...
Converting WebAssembly text format to wasm - WebAssembly
: you can also convert the assembly back into the text representation using the wasm2wat tool; for example wasm2wat simple.wasm -o text.wat. viewing the assembly output because the output file is assembly-based, it can’t be viewed in a normal text editor. however, you can view it using the wat2wasm tool’s -v option. try this: wat2wasm simple.wat -v this will give you an output in your terminal in the following way: ...